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 new file mode 100644 index 00000000000..cc88f9a8000 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/MetaGenerator.java @@ -0,0 +1,180 @@ +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.*; + +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/resources/codegen/README.mustache b/modules/swagger-codegen/src/main/resources/codegen/README.mustache new file mode 100644 index 00000000000..d40b9b35813 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/codegen/README.mustache @@ -0,0 +1,74 @@ +# Swagger Codegen for the {{name}} library + +## Overview +This is a boiler-plate project to generate your own client library with Swagger. It's goal is +to get you started with the basic plumbing so you can put in your own logic. It won't work without +your changes applied. + +## What's Swagger? +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. + +## How do I use this? +At this point, you've likely generated a client setup. It will include something along these lines: + +``` +. +|- README.md // this file +|- pom.xml // build script +|-- src +|--- main +|---- java +|----- {{generatorPackage}}.{{generatorClass}}.java // generator file +|---- resources +|----- {{name}} // template files +|----- META-INF +|------ services +|------- com.wordnik.swagger.codegen.CodegenConfig +``` + +You _will_ need to make changes in at least the following: + +`{{generatorClass}}.java` + +Templates in this folder: + +`src/main/resources/{{name}}` + +Once modified, you can run this: + +``` +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 +``` + +Now your templates are available to the client generator and you can write output values + +## But how do I modify this? +The `{{generatorClass}}.java` has comments in it--lots of comments. There is no good substitute +for reading the code more, though. See how the `{{generatorClass}}` implements `CodegenConfig`. +That class has the signature of all values that can be overridden. + +For the templates themselves, you have a number of values available to you for generation. +You can execute the `java` command from above while passing different debug flags to show +the object you have available during client generation: + +``` +# The following additional debug options are available for all codegen targets: +# -DdebugSwagger prints the swagger specification as interpreted by the codegen +# -DdebugModels prints models passed to the template engine +# -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 +``` + +Will, for example, output the debug info for operations. You can use this info +in the `api.mustache` file. \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/codegen/api.template b/modules/swagger-codegen/src/main/resources/codegen/api.template new file mode 100644 index 00000000000..9dbc8dd4ba1 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/codegen/api.template @@ -0,0 +1,28 @@ + +# This is a sample api mustache template. It is representing a ficticous +# language and won't be usable or compile to anything without lots of changes. +# Use it as an example. You can access the variables in the generator object +# like such: + +# use the package from the `apiPackage` variable +package: {{package}} + +# operations block +{{#operations}} +classname: {{classname}} + +# loop over each operation in the API: +{{#operation}} + +# each operation has a `nickname`: +nickname: {{nickname}} + +# and parameters: +{{#allParams}} +{{paramName}}: {{dataType}} +{{/allParams}} + +{{/operation}} + +# end of operations block +{{/operations}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/codegen/generatorClass.mustache b/modules/swagger-codegen/src/main/resources/codegen/generatorClass.mustache new file mode 100644 index 00000000000..53b3a60ad1b --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/codegen/generatorClass.mustache @@ -0,0 +1,191 @@ +package {{generatorPackage}}; + +import com.wordnik.swagger.codegen.*; +import com.wordnik.swagger.models.properties.*; + +import java.util.*; +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 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 "{{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 + */ + 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 + ); + + /** + * 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 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); + } + else + type = swaggerType; + return toModelName(type); + } +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/codegen/model.template b/modules/swagger-codegen/src/main/resources/codegen/model.template new file mode 100644 index 00000000000..e69de29bb2d diff --git a/modules/swagger-codegen/src/main/resources/codegen/pom.mustache b/modules/swagger-codegen/src/main/resources/codegen/pom.mustache new file mode 100644 index 00000000000..f827a2f56b6 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/codegen/pom.mustache @@ -0,0 +1,102 @@ + + 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.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 + + + + + + + com.wordnik + 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/codegen/services.mustache b/modules/swagger-codegen/src/main/resources/codegen/services.mustache new file mode 100644 index 00000000000..9b16ae65f14 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/codegen/services.mustache @@ -0,0 +1 @@ +{{fullyQualifiedGeneratorClass}} \ No newline at end of file