added meta generator

This commit is contained in:
Tony Tam 2015-03-02 23:28:59 -08:00
parent 6b823b88d9
commit a724cd0780
7 changed files with 576 additions and 0 deletions

View File

@ -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<String, CodegenConfig> configs = new HashMap<String, CodegenConfig>();
static String configString;
static {
List<CodegenConfig> extensions = getExtensions();
StringBuilder sb = new StringBuilder();
for(CodegenConfig config : extensions) {
if(sb.toString().length() != 0)
sb.append(", ");
sb.append(config.getName());
configs.put(config.getName(), config);
configString = sb.toString();
}
}
public static void main(String[] args) {
new MetaGenerator().generate(args);
}
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<SupportingFile> supportingFiles = new ArrayList<SupportingFile>();
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<File> files = new ArrayList<File>();
Map<String, Object> data = new HashMap<String, Object>();
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<CodegenConfig> getExtensions() {
ServiceLoader<CodegenConfig> loader = ServiceLoader.load(CodegenConfig.class);
List<CodegenConfig> output = new ArrayList<CodegenConfig>();
Iterator<CodegenConfig> itr = loader.iterator();
while(itr.hasNext()) {
output.add(itr.next());
}
return output;
}
static void usage(Options options) {
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp( "MetaGenerator. Generator for creating a new template set " +
"and configuration for Codegen. The output will be based on the language you " +
"specify, and includes default templates to include.", options );
}
public static CodegenConfig getConfig(String name) {
if(configs.containsKey(name)) {
return configs.get(name);
}
return null;
}
}

View File

@ -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.

View File

@ -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}}

View File

@ -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<String> (
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<String>(
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);
}
}

View File

@ -0,0 +1,102 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>io.swagger</groupId>
<artifactId>{{name}}-swagger-codegen</artifactId>
<packaging>jar</packaging>
<name>{{name}}-swagger-codegen</name>
<version>1.0.0</version>
<prerequisites>
<maven>2.2.0</maven>
</prerequisites>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.12</version>
<configuration>
<systemProperties>
<property>
<name>loggerPath</name>
<value>conf/log4j.properties</value>
</property>
</systemProperties>
<argLine>-Xms512m -Xmx1500m</argLine>
<parallel>methods</parallel>
<forkMode>pertest</forkMode>
</configuration>
</plugin>
<!-- attach test jar -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.2</version>
<executions>
<execution>
<goals>
<goal>jar</goal>
<goal>test-jar</goal>
</goals>
</execution>
</executions>
<configuration>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<executions>
<execution>
<id>add_sources</id>
<phase>generate-sources</phase>
<goals>
<goal>add-source</goal>
</goals>
<configuration>
<sources>
<source>src/main/java</source>
</sources>
</configuration>
</execution>
<execution>
<id>add_test_sources</id>
<phase>generate-test-sources</phase>
<goals>
<goal>add-test-source</goal>
</goals>
<configuration>
<sources>
<source>src/test/java</source>
</sources>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>com.wordnik</groupId>
<artifactId>swagger-codegen</artifactId>
<version>${swagger-codegen-version}</version>
<scope>provided</scope>
</dependency>
</dependencies>
<properties>
<swagger-codegen-version>2.1.2-M1</swagger-codegen-version>
<maven-plugin-version>1.0.0</maven-plugin-version>
<junit-version>4.8.1</junit-version>
</properties>
</project>

View File

@ -0,0 +1 @@
{{fullyQualifiedGeneratorClass}}