moved to modules per #411

This commit is contained in:
Tony Tam 2015-02-05 07:17:38 -08:00
parent 450894c52e
commit 6bb2e4ccb4
202 changed files with 26147 additions and 0 deletions

View File

@ -0,0 +1,63 @@
<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">
<parent>
<groupId>com.wordnik</groupId>
<artifactId>swagger-codegen-project</artifactId>
<version>2.1.0-SNAPSHOT</version>
<relativePath>../..</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>com.wordnik</groupId>
<artifactId>swagger-codegen-distribution</artifactId>
<packaging>jar</packaging>
<name>swagger-codegen-distribution</name>
<version>2.1.0-SNAPSHOT</version>
<build>
<testSourceDirectory>src/test/scala</testSourceDirectory>
<outputDirectory>target/classes</outputDirectory>
<testOutputDirectory>target/test-classes</testOutputDirectory>
<defaultGoal>install</defaultGoal>
<directory>target</directory>
<finalName>${project.artifactId}-${project.version}</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>2.3</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<minimizeJar>false</minimizeJar>
<createDependencyReducedPom>true</createDependencyReducedPom>
<dependencyReducedPomLocation>
${java.io.tmpdir}/dependency-reduced-pom.xml
</dependencyReducedPomLocation>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifest>
<mainClass>com.wordnik.swagger.codegen.Codegen</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>com.wordnik</groupId>
<artifactId>swagger-codegen</artifactId>
<version>${project.parent.version}</version>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,391 @@
<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">
<parent>
<groupId>com.wordnik</groupId>
<artifactId>swagger-codegen-project</artifactId>
<version>2.1.0-SNAPSHOT</version>
<relativePath>../..</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>com.wordnik</groupId>
<artifactId>swagger-codegen</artifactId>
<packaging>jar</packaging>
<name>swagger-codegen</name>
<version>2.1.0-SNAPSHOT</version>
<build>
<sourceDirectory>src/main/java</sourceDirectory>
<defaultGoal>install</defaultGoal>
<extensions>
<extension>
<groupId>org.jvnet.wagon-svn</groupId>
<artifactId>wagon-svn</artifactId>
<version>1.8</version>
</extension>
<extension>
<groupId>org.apache.maven.wagon</groupId>
<artifactId>wagon-ssh-external</artifactId>
<version>1.0-alpha-6</version>
</extension>
<extension>
<groupId>org.apache.maven.wagon</groupId>
<artifactId>wagon-webdav</artifactId>
<version>1.0-beta-1</version>
</extension>
</extensions>
<directory>target</directory>
<finalName>${project.artifactId}-${project.version}</finalName>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.3.2</version>
<executions>
<execution>
<goals>
<goal>java</goal>
</goals>
</execution>
</executions>
<configuration>
<mainClass>com.wordnik.swagger.codegen.Codegen</mainClass>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<mainClass>com.wordnik.swagger.codegen.Codegen</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/lib</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>net.alchim31.maven</groupId>
<artifactId>scala-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>add-source</goal>
<goal>compile</goal>
<goal>testCompile</goal>
</goals>
</execution>
</executions>
<configuration>
<configuration>
<recompileMode>incremental</recompileMode>
</configuration>
<jvmArgs>
<jvmArg>-Xmx384m</jvmArg>
</jvmArgs>
<args>
<arg>-target:jvm-1.6</arg>
<arg>-deprecation</arg>
</args>
<launchers>
<launcher>
<id>run-scalatest</id>
<mainClass>org.scalatest.tools.Runner</mainClass>
<args>
<arg>-p</arg>
<arg>${project.build.testOutputDirectory}</arg>
</args>
<jvmArgs>
<jvmArg>-Xmx512m</jvmArg>
</jvmArgs>
</launcher>
</launchers>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>2.1.2</version>
<executions>
<execution>
<id>attach-sources</id>
<phase>verify</phase>
<goals>
<goal>jar-no-fork</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>2.7</version>
<configuration>
<aggregate>true</aggregate>
<source>1.6</source>
<encoding>UTF-8</encoding>
<maxmemory>1g</maxmemory>
<links>
<link>http://java.sun.com/javase/6/docs/api/</link>
</links>
<excludePackageNames>${javadoc.package.exclude}</excludePackageNames>
</configuration>
<executions>
<execution>
<id>attach-javadocs</id>
<phase>verify</phase>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.0</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.4</version>
<configuration>
<archive>
<manifestEntries>
<mode>development</mode>
<url>${project.url}</url>
<implementation-version>${project.version}</implementation-version>
<package>com.wordnik</package>
</manifestEntries>
</archive>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-site-plugin</artifactId>
<version>2.1</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-release-plugin</artifactId>
<version>2.1</version>
</plugin>
</plugins>
<pluginManagement>
<plugins>
<plugin>
<groupId>net.alchim31.maven</groupId>
<artifactId>scala-maven-plugin</artifactId>
<version>${scala-maven-plugin-version}</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-gpg-plugin</artifactId>
<configuration>
<releaseProfiles>release</releaseProfiles>
<goals>sign</goals>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
<profiles>
<profile>
<id>release-profile</id>
<properties>
<skipTests>true</skipTests>
</properties>
<build>
<plugins>
<plugin>
<groupId>net.alchim31.maven</groupId>
<artifactId>scala-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>compile</goal>
<goal>testCompile</goal>
</goals>
</execution>
</executions>
<configuration />
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<executions>
<execution>
<id>add-source</id>
<phase>prepare-package</phase>
<goals>
<goal>add-source</goal>
</goals>
<configuration>
<sources>
<source>src/main/scala</source>
</sources>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>release-sign-artifacts</id>
<activation>
<property>
<name>performRelease</name>
<value>true</value>
</property>
</activation>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-gpg-plugin</artifactId>
<executions>
<execution>
<id>sign-artifacts</id>
<phase>verify</phase>
<goals>
<goal>sign</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<reporting>
<outputDirectory>target/site</outputDirectory>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>2.9</version>
<configuration>
<aggregate>true</aggregate>
<debug>true</debug>
<links>
<link>http://java.sun.com/javaee/5/docs/api</link>
<link>http://java.sun.com/j2se/1.5.0/docs/api</link>
</links>
<excludePackageNames />
</configuration>
</plugin>
<plugin>
<groupId>net.alchim31.maven</groupId>
<artifactId>scala-maven-plugin</artifactId>
<version>${scala-maven-plugin-version}</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jxr-plugin</artifactId>
<version>2.3</version>
<configuration>
<aggregate>true</aggregate>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-project-info-reports-plugin</artifactId>
<version>2.6</version>
<reportSets>
<reportSet>
<reports>
<report>project-team</report>
</reports>
</reportSet>
</reportSets>
</plugin>
</plugins>
</reporting>
<dependencies>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-parser</artifactId>
<version>${swagger-parser-version}</version>
</dependency>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-legacy-spec-parser</artifactId>
<version>${swagger-parser-version}</version>
</dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>swagger-core</artifactId>
<version>${swagger-core-version}</version>
</dependency>
<dependency>
<groupId>com.samskivert</groupId>
<artifactId>jmustache</artifactId>
<version>${jmustache-version}</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io-version}</version>
</dependency>
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-plugin-tools-api</artifactId>
<version>2.0</version>
</dependency>
<dependency>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<version>${felix-version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-ext</artifactId>
<version>${slf4j-version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j-version}</version>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>${commons-lang-version}</version>
</dependency>
<dependency>
<groupId>commons-cli</groupId>
<artifactId>commons-cli</artifactId>
<version>${commons-cli-version}</version>
</dependency>
<dependency>
<groupId>org.scalatest</groupId>
<artifactId>scalatest_2.11</artifactId>
<version>${scala-test-version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<repositories>
<repository>
<id>sonatype-snapshots</id>
<url>https://oss.sonatype.org/content/repositories/snapshots</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
</repositories>
</project>

View File

@ -0,0 +1,59 @@
/**
* Copyright 2014 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.models.Swagger;
public class ClientOptInput {
private ClientOpts opts;
private Swagger swagger;
protected CodegenConfig config;
public ClientOptInput swagger(Swagger swagger) {
this.setSwagger(swagger);
return this;
}
public ClientOptInput opts(ClientOpts opts) {
this.setOpts(opts);
return this;
}
public CodegenConfig getConfig() {
return config;
}
public void setConfig(CodegenConfig config) {
this.config = config;
}
public void setOpts(ClientOpts opts) {
this.opts = opts;
}
public ClientOpts getOpts() {
return opts;
}
public void setSwagger(Swagger swagger) {
this.swagger = swagger;
}
public Swagger getSwagger() {
return swagger;
}
}

View File

@ -0,0 +1,52 @@
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<String, String> properties = new HashMap<String, String>();
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<String, String> getProperties() {
return properties;
}
public void setProperties(Map<String, String> 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();
}
}

View File

@ -0,0 +1,123 @@
package com.wordnik.swagger.codegen;
import com.wordnik.swagger.codegen.languages.*;
import com.wordnik.swagger.models.Swagger;
import com.wordnik.swagger.util.*;
import io.swagger.parser.SwaggerParser;
import org.apache.commons.cli.*;
import java.io.File;
import java.util.*;
public class Codegen extends DefaultGenerator {
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) {
List<CodegenConfig> extensions = getExtensions();
Map<String, CodegenConfig> configs = new HashMap<String, CodegenConfig>();
StringBuilder sb = new StringBuilder();
for(CodegenConfig config : extensions) {
if(sb.toString().length() != 0)
sb.append(", ");
sb.append(config.getName());
configs.put(config.getName(), config);
}
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[" + sb.toString() + "]");
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");
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("l"))
clientOptInput.setConfig(getConfig(cmd.getOptionValue("l"), configs));
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")), configs);
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"));
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<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( "Codegen", options );
}
static CodegenConfig getConfig(String name, Map<String, CodegenConfig> configs) {
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);
}
}
}
}

View File

@ -0,0 +1,51 @@
package com.wordnik.swagger.codegen;
import com.wordnik.swagger.models.*;
import com.wordnik.swagger.models.properties.*;
import java.util.*;
public interface CodegenConfig {
String getName();
String getHelp();
Map<String, Object> additionalProperties();
String apiPackage();
String apiFileFolder();
String fileSuffix();
String outputFolder();
String templateDir();
String modelFileFolder();
String modelPackage();
String toApiName(String name);
String toModelName(String name);
String toParamName(String name);
String escapeReservedWord(String name);
String getTypeDeclaration(Property p);
String getTypeDeclaration(String name);
void processOpts();
Set<String> reservedWords();
List<SupportingFile> supportingFiles();
void setOutputDir(String dir);
String getOutputDir();
CodegenModel fromModel(String name, Model model);
CodegenOperation fromOperation(String resourcePath, String httpMethod, Operation operation);
Set<String> defaultIncludes();
Map<String, String> typeMapping();
Map<String, String> instantiationTypes();
Map<String, String> importMapping();
Map<String, String> apiTemplateFiles();
Map<String, String> modelTemplateFiles();
void processSwagger(Swagger swagger);
String toApiFilename(String name);
String toModelFilename(String name);
String toModelImport(String name);
String toApiImport(String name);
void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, Map<String, List<CodegenOperation>> operations);
Map<String, Object> postProcessModels(Map<String, Object> objs);
Map<String, Object> postProcessOperations(Map<String, Object> objs);
}

View File

@ -0,0 +1,16 @@
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<CodegenProperty> vars = new ArrayList<CodegenProperty>();
public Set<String> imports = new HashSet<String>();
public Boolean hasVars, emptyVars, hasMoreModels;
public ExternalDocs externalDocs;
}

View File

@ -0,0 +1,38 @@
package com.wordnik.swagger.codegen;
import java.util.HashMap;
import java.util.Map;
public final class CodegenModelFactory {
private static final Map<CodegenModelType, Class<?>> typeMapping = new HashMap<CodegenModelType, Class<?>>();
/**
* 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> 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);
}
}
}

View File

@ -0,0 +1,20 @@
package com.wordnik.swagger.codegen;
public enum CodegenModelType {
MODEL(CodegenModel.class),
OPERATION(CodegenOperation.class),
PARAMETER(CodegenParameter.class),
PROPERTY(CodegenProperty.class),
RESPONSE(CodegenResponse.class);
private final Class<?> defaultImplementation;
private CodegenModelType(Class<?> defaultImplementation) {
this.defaultImplementation = defaultImplementation;
}
public Class<?> getDefaultImplementation() {
return defaultImplementation;
}
}

View File

@ -0,0 +1,29 @@
package com.wordnik.swagger.codegen;
import com.wordnik.swagger.models.*;
import java.util.*;
public class CodegenOperation {
public Boolean hasConsumes, hasProduces, hasParams, returnTypeIsPrimitive, returnSimpleType, subresourceOperation;
public String path, operationId, returnType, httpMethod, returnBaseType,
returnContainer, summary, notes, baseName, defaultResponse;
public List<Map<String, String>> consumes, produces;
public CodegenParameter bodyParam;
public List<CodegenParameter> allParams = new ArrayList<CodegenParameter>();
public List<CodegenParameter> bodyParams = new ArrayList<CodegenParameter>();
public List<CodegenParameter> pathParams = new ArrayList<CodegenParameter>();
public List<CodegenParameter> queryParams = new ArrayList<CodegenParameter>();
public List<CodegenParameter> headerParams = new ArrayList<CodegenParameter>();
public List<CodegenParameter> formParams = new ArrayList<CodegenParameter>();
public List<String> tags;
public List<CodegenResponse> responses = new ArrayList<CodegenResponse>();
public final List<CodegenProperty> responseHeaders = new ArrayList<CodegenProperty>();
public Set<String> imports = new HashSet<String>();
public List<Map<String, String>> examples;
public ExternalDocs externalDocs;
// legacy support
public String nickname;
}

View File

@ -0,0 +1,37 @@
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;
/**
* 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;
return output;
}
}

View File

@ -0,0 +1,24 @@
package com.wordnik.swagger.codegen;
import java.util.*;
public class CodegenProperty {
public String baseName, complexType, getter, setter, description, datatype,
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 Double minimum, maximum, exclusiveMinimum, exclusiveMaximum;
public Boolean hasMore = null, required = null, secondaryParam = null;
public Boolean isPrimitiveType, isContainer, isNotContainer;
public boolean isEnum;
public List<String> _enum;
public Map<String, Object> allowableValues;
}

View File

@ -0,0 +1,10 @@
package com.wordnik.swagger.codegen;
import java.util.*;
public class CodegenResponse {
public String code, message;
public Boolean hasMore;
public List<Map<String, String>> examples;
Object schema;
}

View File

@ -0,0 +1,883 @@
package com.wordnik.swagger.codegen;
import com.wordnik.swagger.models.*;
import com.wordnik.swagger.models.parameters.*;
import com.wordnik.swagger.models.properties.*;
import com.wordnik.swagger.util.Json;
import org.apache.commons.lang.StringUtils;
import java.util.*;
public class DefaultCodegen {
protected String outputFolder = "";
protected Set<String> defaultIncludes = new HashSet<String>();
protected Map<String, String> typeMapping = new HashMap<String, String>();
protected Map<String, String> instantiationTypes = new HashMap<String, String>();
protected Set<String> reservedWords = new HashSet<String>();
protected Set<String> languageSpecificPrimitives = new HashSet<String>();
protected Map<String, String> importMapping = new HashMap<String, String>();
protected String modelPackage = "", apiPackage = "", fileSuffix;
protected Map<String, String> apiTemplateFiles = new HashMap<String, String>();
protected Map<String, String> modelTemplateFiles = new HashMap<String, String>();
protected String templateDir;
protected Map<String, Object> additionalProperties = new HashMap<String, Object>();
protected List<SupportingFile> supportingFiles = new ArrayList<SupportingFile>();
public void processOpts(){
if(additionalProperties.containsKey("templateDir")) {
this.setTemplateDir((String)additionalProperties.get("templateDir"));
}
}
// override with any special post-processing
public Map<String, Object> postProcessModels(Map<String, Object> objs) {
return objs;
}
// override with any special post-processing
public Map<String, Object> postProcessOperations(Map<String, Object> 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", " ");
output = output.replace("\"", "\\\"");
return output;
}
return input;
}
public Set<String> defaultIncludes() {
return defaultIncludes;
}
public Map<String, String> typeMapping() {
return typeMapping;
}
public Map<String, String> instantiationTypes() {
return instantiationTypes;
}
public Set<String> reservedWords() {
return reservedWords;
}
public Set<String> languageSpecificPrimitives() {
return languageSpecificPrimitives;
}
public Map<String, String> 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<String, String> apiTemplateFiles() {
return apiTemplateFiles;
}
public Map<String, String> modelTemplateFiles() {
return modelTemplateFiles;
}
public String apiFileFolder() {
return outputFolder + "/" + apiPackage().replaceAll("\\.", "/");
}
public String modelFileFolder() {
return outputFolder + "/" + modelPackage().replaceAll("\\.", "/");
}
public Map<String, Object> additionalProperties() {
return additionalProperties;
}
public List<SupportingFile> 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 String toApiFilename(String name) {
return initialCaps(name) + "Api";
}
public String toModelFilename(String name) {
return name;
}
public String toVarName(String name) {
if(reservedWords.contains(name))
return escapeReservedWord(name);
else
return name;
}
public String toParamName(String name) {
if(reservedWords.contains(name)) {
return escapeReservedWord(name);
}
return name;
}
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<String>(
Arrays.asList("double",
"int",
"long",
"short",
"char",
"float",
"String",
"boolean",
"Boolean",
"Double",
"Void",
"Integer",
"Long",
"Float")
);
typeMapping = new HashMap<String, String>();
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<String, String>();
reservedWords = new HashSet<String>();
importMapping = new HashMap<String, String>();
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.*");
}
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 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 initialCaps(String name) {
return Character.toUpperCase(name.charAt(0)) + name.substring(1);
}
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 = model.getDescription();
m.classname = toModelName(name);
m.classVarName = toVarName(name);
m.modelJson = Json.pretty(model);
m.externalDocs = model.getExternalDocs();
int count = 0;
if(model instanceof ArrayModel) {
ArrayModel am = (ArrayModel) model;
ArrayProperty arrayProperty = new ArrayProperty(am.getItems());
CodegenProperty cp = fromProperty(name, arrayProperty);
if(cp.complexType != null && !defaultIncludes.contains(cp.complexType))
m.imports.add(cp.complexType);
m.parent = toInstantiationType(arrayProperty);
String containerType = cp.containerType;
if(instantiationTypes.containsKey(containerType))
m.imports.add(instantiationTypes.get(containerType));
if(typeMapping.containsKey(containerType)) {
containerType = typeMapping.get(containerType);
cp.containerType = containerType;
m.imports.add(containerType);
}
}
else if (model instanceof RefModel) {
// TODO
}
else {
ModelImpl impl = (ModelImpl) model;
if(impl.getAdditionalProperties() != null) {
MapProperty mapProperty = new MapProperty(impl.getAdditionalProperties());
CodegenProperty cp = fromProperty(name, mapProperty);
if(cp.complexType != null && !defaultIncludes.contains(cp.complexType))
m.imports.add(cp.complexType);
m.parent = toInstantiationType(mapProperty);
String containerType = cp.containerType;
if(instantiationTypes.containsKey(containerType))
m.imports.add(instantiationTypes.get(containerType));
if(typeMapping.containsKey(containerType)) {
containerType = typeMapping.get(containerType);
cp.containerType = containerType;
m.imports.add(containerType);
}
}
if(impl.getProperties() != null && impl.getProperties().size() > 0) {
m.hasVars = true;
for(String key: impl.getProperties().keySet()) {
Property prop = impl.getProperties().get(key);
if(prop == null) {
System.out.println("null property for " + key);
}
else {
CodegenProperty cp = fromProperty(key, prop);
cp.required = false;
if(impl.getRequired() != null) {
for(String req : impl.getRequired()) {
if(key.equals(req))
cp.required = true;
}
}
if(cp.complexType != null && !defaultIncludes.contains(cp.complexType)) {
m.imports.add(cp.complexType);
}
m.vars.add(cp);
count += 1;
if(count != impl.getProperties().keySet().size())
cp.hasMore = new Boolean(true);
if(cp.isContainer != null) {
String arrayImport = typeMapping.get("array");
if(arrayImport != null &&
!languageSpecificPrimitives.contains(arrayImport) &&
!defaultIncludes.contains(arrayImport))
m.imports.add(arrayImport);
}
if(cp.complexType != null &&
!languageSpecificPrimitives.contains(cp.complexType) &&
!defaultIncludes.contains(cp.complexType))
m.imports.add(cp.complexType);
if(cp.baseType != null &&
!languageSpecificPrimitives.contains(cp.baseType) &&
!defaultIncludes.contains(cp.baseType))
m.imports.add(cp.baseType);
}
}
}
else {
m.emptyVars = true;
}
}
return m;
}
public CodegenProperty fromProperty(String name, Property p) {
if(p == null) {
System.out.println("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" + initialCaps(name);
property.setter = "set" + initialCaps(name);
property.example = p.getExample();
property.defaultValue = toDefaultValue(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<String, Object> allowableValues = new HashMap<String, Object>();
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<String> _enum = sp.getEnum();
property._enum = _enum;
property.isEnum = true;
// legacy support
Map<String, Object> allowableValues = new HashMap<String, Object>();
allowableValues.put("values", _enum);
property.allowableValues = allowableValues;
}
}
property.datatype = property.isEnum
? StringUtils.capitalize(property.name) + "Enum"
: getTypeDeclaration(p);
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) {
System.out.println("skipping invalid property:");
Json.prettyPrint(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 {
property.isNotContainer = true;
if(languageSpecificPrimitives().contains(type))
property.isPrimitiveType = true;
else
property.complexType = property.baseType;
}
return property;
}
public CodegenOperation fromOperation(String path, String httpMethod, Operation operation){
CodegenOperation op = CodegenModelFactory.newInstance(CodegenModelType.OPERATION);
Set<String> imports = new HashSet<String>();
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();
System.out.println("generated operationId " + operationId);
}
op.path = path;
op.operationId = operationId;
op.summary = escapeText(operation.getSummary());
op.notes = escapeText(operation.getDescription());
op.tags = operation.getTags();
Response methodResponse = null;
if(operation.getConsumes() != null && operation.getConsumes().size() > 0) {
List<Map<String, String>> c = new ArrayList<Map<String, String>>();
int count = 0;
for(String key: operation.getConsumes()) {
Map<String, String> mediaType = new HashMap<String, String>();
mediaType.put("mediaType", key);
count += 1;
if (count < operation.getConsumes().size())
mediaType.put("hasMore", "true");
c.add(mediaType);
}
op.consumes = c;
op.hasConsumes = true;
}
if(operation.getProduces() != null && operation.getProduces().size() > 0) {
List<Map<String, String>> c = new ArrayList<Map<String, String>>();
int count = 0;
for(String key: operation.getProduces()) {
Map<String, String> mediaType = new HashMap<String, String>();
mediaType.put("mediaType", key);
count += 1;
if (count < operation.getProduces().size())
mediaType.put("hasMore", "true");
c.add(mediaType);
}
op.produces = c;
op.hasProduces = true;
}
if(operation.getResponses() != null) {
for(String responseCode: new TreeSet<String>(operation.getResponses().keySet())) {
Response response = operation.getResponses().get(responseCode);
if (responseCode.startsWith("2")) {
// use the first, i.e. the smallest 2xx response status as methodResponse
methodResponse = response;
break;
}
}
if(methodResponse == null && operation.getResponses().keySet().contains("default")) {
methodResponse = operation.getResponses().get("default");
}
for(String responseCode: operation.getResponses().keySet()) {
Response response = operation.getResponses().get(responseCode);
if(response != methodResponse) {
CodegenResponse r = fromResponse(responseCode, response);
op.responses.add(r);
}
for(int i = 0; i < op.responses.size() - 1; i++) {
CodegenResponse r = op.responses.get(i);
r.hasMore = new Boolean(true);
}
}
}
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 = toExamples(methodResponse.getExamples());
op.defaultResponse = toDefaultValue(responseProperty);
op.returnType = cm.datatype;
if(cm.isContainer != null) {
op.returnContainer = cm.complexType;
}
else
op.returnSimpleType = true;
if (languageSpecificPrimitives().contains(op.returnBaseType) || op.returnBaseType == null)
op.returnTypeIsPrimitive = true;
}
addHeaders(methodResponse, op.responseHeaders);
}
if(op.returnBaseType == null) {
op.returnTypeIsPrimitive = true;
op.returnSimpleType = true;
}
if(op.returnBaseType != null &&
!defaultIncludes.contains(op.returnBaseType) &&
!languageSpecificPrimitives.contains(op.returnBaseType))
imports.add(op.returnBaseType);
List<Parameter> parameters = operation.getParameters();
CodegenParameter bodyParam = null;
List<CodegenParameter> allParams = new ArrayList<CodegenParameter>();
List<CodegenParameter> bodyParams = new ArrayList<CodegenParameter>();
List<CodegenParameter> pathParams = new ArrayList<CodegenParameter>();
List<CodegenParameter> queryParams = new ArrayList<CodegenParameter>();
List<CodegenParameter> headerParams = new ArrayList<CodegenParameter>();
List<CodegenParameter> cookieParams = new ArrayList<CodegenParameter>();
List<CodegenParameter> formParams = new ArrayList<CodegenParameter>();
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".equals(p.dataType))
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 = 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());
return r;
}
public CodegenParameter fromParameter(Parameter param, Set<String> imports) {
CodegenParameter p = CodegenModelFactory.newInstance(CodegenModelType.PARAMETER);
p.baseName = param.getName();
p.description = param.getDescription();
p.required = param.getRequired();
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) {
System.out.println("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;
imports.add(pr.baseType);
}
else
property = PropertyBuilder.build(qp.getType(), qp.getFormat(), null);
if(property == null) {
System.out.println("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");
}
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);
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());
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;
}
protected List<Map<String, String>> toExamples(Map<String, String> examples) {
if(examples == null)
return null;
List<Map<String, String>> output = new ArrayList<Map<String, String>>();
for(String key: examples.keySet()) {
String value = examples.get(key);
Map<String, String> kv = new HashMap<String, String>();
kv.put("contentType", key);
kv.put("example", value);
output.add(kv);
}
return output;
}
private void addHeaders(Response response, List<CodegenProperty> target) {
if (response.getHeaders() != null) {
for (Map.Entry<String, Property> headers : response.getHeaders().entrySet()) {
target.add(fromProperty(headers.getKey(), headers.getValue()));
}
}
}
private List<CodegenParameter> addHasMore(List<CodegenParameter> 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<String, Object> addHasMore(Map<String, Object> 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<String, List<CodegenOperation>> operations) {
List<CodegenOperation> opList = operations.get(tag);
if(opList == null) {
opList = new ArrayList<CodegenOperation>();
operations.put(tag, opList);
}
opList.add(co);
co.baseName = tag;
}
}

View File

@ -0,0 +1,371 @@
package com.wordnik.swagger.codegen;
import com.wordnik.swagger.models.*;
import com.wordnik.swagger.util.*;
import com.samskivert.mustache.*;
import org.apache.commons.io.FileUtils;
import java.util.*;
import java.util.regex.*;
import java.io.*;
public class DefaultGenerator implements Generator {
private CodegenConfig config;
private ClientOptInput opts = null;
private Swagger swagger = null;
public Generator opts(ClientOptInput opts) {
this.opts = opts;
this.swagger = opts.getSwagger();
ClientOpts clientOpts = opts.getOpts();
this.config = opts.getConfig();
this.config.additionalProperties().putAll(clientOpts.getProperties());
return this;
}
public void generate() {
if(swagger == null || config == null) {
throw new RuntimeException("missing swagger input or config!");
}
if(System.getProperty("debugSwagger") != null) {
Json.prettyPrint(swagger);
}
try {
config.processOpts();
if(swagger.getInfo() != null) {
Info info = swagger.getInfo();
if(info.getTitle() != null)
config.additionalProperties().put("appName", info.getTitle());
if(info.getDescription() != null)
config.additionalProperties().put("appDescription", 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());
}
}
StringBuilder hostBuilder = new StringBuilder();
if(swagger.getSchemes() != null && swagger.getSchemes().size() > 0) {
hostBuilder.append(swagger.getSchemes().get(0).toValue());
hostBuilder.append("://");
}
else
hostBuilder.append("https://");
hostBuilder.append(swagger.getHost()).append(swagger.getBasePath());
String basePath = hostBuilder.toString();
List<Object> allOperations = new ArrayList<Object>();
List<Object> allModels = new ArrayList<Object>();
// models
Map<String, Model> definitions = swagger.getDefinitions();
for(String name: definitions.keySet()) {
Model model = definitions.get(name);
Map<String, Model> modelMap = new HashMap<String, Model>();
modelMap.put(name, model);
Map<String, Object> models = processModels(config, modelMap);
models.putAll(config.additionalProperties());
allModels.add(((List<Object>)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));
}
}
if(System.getProperty("debugModels") != null) {
System.out.println("############ Model info ############");
Json.prettyPrint(allModels);
}
// apis
Map<String, List<CodegenOperation>> paths = processPaths(swagger.getPaths());
for(String tag : paths.keySet()) {
List<CodegenOperation> ops = paths.get(tag);
Map<String, Object> operation = processOperations(config, tag, ops);
operation.put("basePath", basePath);
operation.put("baseName", tag);
operation.put("modelPackage", config.modelPackage());
operation.putAll(config.additionalProperties());
operation.put("classname", config.toApiName(tag));
allOperations.add(operation);
for(String templateName : config.apiTemplateFiles().keySet()) {
String suffix = config.apiTemplateFiles().get(templateName);
String filename = config.apiFileFolder() +
File.separator +
config.toApiFilename(tag) +
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(operation));
}
}
if(System.getProperty("debugOperations") != null) {
System.out.println("############ Operation info ############");
Json.prettyPrint(allOperations);
}
// supporting files
Map<String, Object> bundle = new HashMap<String, Object>();
bundle.putAll(config.additionalProperties());
bundle.put("apiPackage", config.apiPackage());
Map<String, Object> apis = new HashMap<String, Object>();
apis.put("apis", allOperations);
if(swagger.getBasePath() != null) {
bundle.put("basePath", swagger.getBasePath());
}
bundle.put("apiInfo", apis);
bundle.put("models", allModels);
bundle.put("apiFolder", config.apiPackage().replaceAll("\\.", "/"));
bundle.put("modelPackage", config.modelPackage());
if (swagger.getExternalDocs() != null) {
bundle.put("externalDocs", swagger.getExternalDocs());
}
for(int i = 0; i < allModels.size() - 1; i++) {
HashMap<String, CodegenModel> cm = (HashMap<String, CodegenModel>) allModels.get(i);
CodegenModel m = cm.get("model");
m.hasMoreModels = true;
}
if(System.getProperty("debugSupportingFiles") != null) {
System.out.println("############ Supporting file info ############");
Json.prettyPrint(bundle);
}
for(SupportingFile support : config.supportingFiles()) {
String outputFolder = config.outputFolder();
if(support.folder != null && !"".equals(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));
}
else {
String template = readTemplate(config.templateDir() + File.separator + support.templateFile);
FileUtils.writeStringToFile(new File(outputFilename), template);
System.out.println("copying file to " + outputFilename);
}
}
config.processSwagger(swagger);
}
catch (Exception e) {
e.printStackTrace();
}
}
public Map<String, List<CodegenOperation>> processPaths(Map<String, Path> paths) {
Map<String, List<CodegenOperation>> ops = new HashMap<String, List<CodegenOperation>>();
List<String> tags = null;
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 void processOperation(String resourcePath, String httpMethod, Operation operation, Map<String, List<CodegenOperation>> operations) {
if(operation != null) {
List<String> tags = operation.getTags();
if(tags == null) {
tags = new ArrayList<String>();
tags.add("default");
}
for(String tag : tags) {
CodegenOperation co = config.fromOperation(resourcePath, httpMethod, operation);
co.tags = new ArrayList<String>();
co.tags.add(sanitizeTag(tag));
config.addOperationToGroup(sanitizeTag(tag), resourcePath, operation, co, operations);
}
}
}
protected String sanitizeTag(String tag) {
// remove spaces and make strong case
String [] parts = tag.split(" ");
StringBuffer buf = new StringBuffer();
for(String part: parts) {
if(!"".equals(part)) {
buf.append(Character.toUpperCase(part.charAt(0)));
if(part.length() > 1)
buf.append(part.substring(1));
}
}
return buf.toString().replaceAll("[^a-zA-Z ]", "");
}
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;
}
public Map<String, Object> processOperations(CodegenConfig config, String tag, List<CodegenOperation> ops) {
Map<String, Object> operations = new HashMap<String, Object>();
Map<String, Object> objs = new HashMap<String, Object>();
objs.put("classname", config.toApiName(tag));
objs.put("operation", ops);
operations.put("operations", objs);
operations.put("package", config.apiPackage());
Set<String> allImports = new HashSet<String>();
for(CodegenOperation op: ops) {
allImports.addAll(op.imports);
}
List<Map<String, String>> imports = new ArrayList<Map<String, String>>();
for(String i: allImports) {
Map<String, String> im = new HashMap<String, String>();
String m = config.importMapping().get(i);
if(m == null)
m = config.toModelImport(i);
if(m != null) {
im.put("import", m);
imports.add(im);
}
}
operations.put("imports", imports);
config.postProcessOperations(operations);
return operations;
}
public Map<String, Object> processModels(CodegenConfig config, Map<String, Model> definitions) {
Map<String, Object> objs = new HashMap<String, Object>();
objs.put("package", config.modelPackage());
List<Object> models = new ArrayList<Object>();
List<Object> model = new ArrayList<Object>();
Set<String> allImports = new HashSet<String>();
for(String key: definitions.keySet()) {
Model mm = definitions.get(key);
CodegenModel cm = config.fromModel(key, mm);
Map<String, Object> mo = new HashMap<String, Object>();
mo.put("model", cm);
models.add(mo);
allImports.addAll(cm.imports);
}
objs.put("models", models);
List<Map<String, String>> imports = new ArrayList<Map<String, String>>();
for(String i: allImports) {
Map<String, String> im = new HashMap<String, String>();
String m = config.importMapping().get(i);
if(m == null)
m = config.toModelImport(i);
if(m != null && !config.defaultIncludes().contains(m)) {
im.put("import", m);
imports.add(im);
}
// add instantiation types
m = config.instantiationTypes().get(i);
if(m != null && !config.defaultIncludes().contains(m)) {
im.put("import", m);
imports.add(im);
}
}
objs.put("imports", imports);
config.postProcessModels(objs);
return objs;
}
}

View File

@ -0,0 +1,8 @@
package com.wordnik.swagger.codegen;
import com.wordnik.swagger.models.Swagger;
public interface Generator {
Generator opts(ClientOptInput opts);
void generate();
}

View File

@ -0,0 +1,13 @@
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;
}
}

View File

@ -0,0 +1,6 @@
package com.wordnik.swagger.codegen.auth;
public interface AuthMethod {
String getType();
void setType(String type);
}

View File

@ -0,0 +1,86 @@
#---------------------------------------------------------------------
# Global settings
#---------------------------------------------------------------------
global
log 127.0.0.1 local2
chroot /var/lib/haproxy
pidfile /var/run/haproxy.pid
maxconn 4000
user haproxy
group haproxy
daemon
#---------------------------------------------------------------------
# common defaults that all the 'listen' and 'backend' sections will
# use if not designated in their block
#---------------------------------------------------------------------
defaults
mode http
log global
option dontlognull
option httpclose
option httplog
option forwardfor
option redispatch
timeout connect 10000 # default 10 second time out if a backend is not found
timeout client 300000
timeout server 300000
maxconn 60000
retries 3
#---------------------------------------------------------------------
# main frontend which proxys to the backends
#---------------------------------------------------------------------
frontend main *:80
default_backend app
acl is_swagger_online hdr_beg(host) -i online.swagger.io
acl is_swagger_io hdr_beg(host) -i swagger.io
acl is_old hdr_beg(host) -i swagger.wordnik.com
acl is_old_editor hdr_beg(host) -i editor.swagger.wordnik.com
acl is_validator_swagger path_beg /swagger.json
# online spec validator
reqrep ([^\ ]*)\ /validator/(.*) \1\ /validator/validator/\2 if is_swagger_online
# something that didn't work
reqrep ([^\ ]*)\ /swagger.json(.*) \1\ /validator/swagger.json if is_validator_swagger
# swagger schema
reqrep ^([^\ :]*)\ /v2/schema.json(.*) \1\ /swagger-api/swagger-spec/master/schemas/v2.0/schema.json\2
acl is_swagger_spec path_beg /swagger-api/swagger-spec
# swagger docs
reqrep ^([^\ :]*)\ /swagger-core/documentation/annotations/apidocs/current(.*) \1\ /swagger-core/apidocs/\2
acl is_swagger_docs path_beg /swagger-core/apidocs
use_backend github_swagger_io if is_swagger_docs
use_backend validator if is_swagger_online
use_backend validator if is_validator_swagger
use_backend github_swagger_io if is_swagger_io !is_swagger_spec
use_backend github_swagger_spec if is_swagger_spec
redirect location http://editor.swagger.io if is_old_editor
redirect location http://swagger.io if is_old
#---------------------------------------------------------------------
# round robin balancing between the various backends
#---------------------------------------------------------------------
backend github_swagger_io
balance roundrobin
server gh1 swagger-api.github.io:80 check
backend github_swagger_spec
http-request set-header Host raw.githubusercontent.com
rspirep ^Content-type:(.*) Content-Type:\ application/json
rspirep ^Access-Control-Allow-Origin:(.*) Access-Control-Allow-Origin:*
balance roundrobin
server gh2 raw.githubusercontent.com:443 check ssl verify none
backend validator
balance roundrobin
server app1 127.0.0.1:8000 check
backend app
balance roundrobin
server app1 127.0.0.1:8000 check

View File

@ -0,0 +1,106 @@
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 = "com.wordnik.client";
protected String groupId = "com.wordnik";
protected String artifactId = "swagger-client";
protected String artifactVersion = "1.0.0";
protected String sourceFolder = "src/main/java";
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 = "com.wordnik.client.api";
modelPackage = "com.wordnik.client.model";
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("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"));
languageSpecificPrimitives = new HashSet<String>(
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().replaceAll("\\.", "/");
}
public String modelFileFolder() {
return outputFolder + "/" + sourceFolder + "/" + modelPackage().replaceAll("\\.", "/");
}
@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);
}
}

View File

@ -0,0 +1,115 @@
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-client";
protected String artifactVersion = "1.0.0";
protected String sourceFolder = "src/main/java";
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<String> (
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("apiInvoker.mustache",
(sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "ApiInvoker.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"));
languageSpecificPrimitives = new HashSet<String>(
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().replaceAll("\\.", "/");
}
public String modelFileFolder() {
return outputFolder + "/" + sourceFolder + "/" + modelPackage().replaceAll("\\.", "/");
}
@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);
}
}

View File

@ -0,0 +1,129 @@
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 JaxRSServerCodegen extends JavaClientCodegen implements CodegenConfig {
protected String invokerPackage = "com.wordnik.api";
protected String groupId = "com.wordnik";
protected String artifactId = "swagger-server";
protected String artifactVersion = "1.0.0";
protected String sourceFolder = "src/main/java";
protected String title = "Swagger Server";
public String getName() {
return "jaxrs";
}
public String getHelp() {
return "Generates a Java JAXRS Server application.";
}
public JaxRSServerCodegen() {
super();
outputFolder = "generated-code/javaJaxRS";
modelTemplateFiles.put("model.mustache", ".java");
apiTemplateFiles.put("api.mustache", ".java");
templateDir = "JavaJaxRS";
apiPackage = "com.wordnik.api";
modelPackage = "com.wordnik.model";
additionalProperties.put("invokerPackage", invokerPackage);
additionalProperties.put("groupId", groupId);
additionalProperties.put("artifactId", artifactId);
additionalProperties.put("artifactVersion", artifactVersion);
additionalProperties.put("title", title);
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"));
languageSpecificPrimitives = new HashSet<String>(
Arrays.asList(
"String",
"boolean",
"Boolean",
"Double",
"Integer",
"Long",
"Float")
);
}
@Override
public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, Map<String, List<CodegenOperation>> 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<CodegenOperation> opList = operations.get(basePath);
if(opList == null) {
opList = new ArrayList<CodegenOperation>();
operations.put(basePath, opList);
}
opList.add(co);
co.baseName = basePath;
}
public Map<String, Object> postProcessOperations(Map<String, Object> objs) {
Map<String, Object> operations = (Map<String, Object>)objs.get("operations");
if(operations != null) {
List<CodegenOperation> ops = (List<CodegenOperation>) operations.get("operation");
for(CodegenOperation operation : ops) {
if(operation.returnType == null)
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;
}
}

View File

@ -0,0 +1,79 @@
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 NodeJSServerCodegen 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 String getName() {
return "nodejs";
}
public String getHelp() {
return "Generates a node.js server application compatible with the 1.2 swagger specification.";
}
public NodeJSServerCodegen() {
super();
outputFolder = "generated-code/nodejs";
apiTemplateFiles.put("api.mustache", ".js");
templateDir = "nodejs";
apiPackage = "app.apis";
modelPackage = "app";
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("models.mustache", modelPackage, "models.js"));
supportingFiles.add(new SupportingFile("main.mustache", "", "main.js"));
supportingFiles.add(new SupportingFile("README.mustache", "", "README.js"));
languageSpecificPrimitives = new HashSet<String>(
Arrays.asList(
"String",
"boolean",
"Boolean",
"Double",
"Integer",
"Long",
"Float")
);
typeMapping.put("array", "array");
}
@Override
public String escapeReservedWord(String name) {
return "_" + name;
}
@Override
public String apiFileFolder() {
return outputFolder + File.separator + apiPackage().replaceAll("\\.", File.separator);
}
public String modelFileFolder() {
return outputFolder + File.separator + modelPackage().replaceAll("\\.", File.separator);
}
@Override
public String getSwaggerType(Property p) {
String swaggerType = super.getSwaggerType(p);
String type = null;
if(typeMapping.containsKey(swaggerType)) {
return typeMapping.get(swaggerType);
}
else
type = swaggerType;
return toModelName(type);
}
}

View File

@ -0,0 +1,216 @@
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 ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
protected Set<String> foundationClasses = new HashSet<String>();
protected String sourceFolder = "client";
protected static String PREFIX = "SWG";
public String getName() {
return "objc";
}
public String getHelp() {
return "Generates an Objective-C client library.";
}
public ObjcClientCodegen() {
super();
outputFolder = "generated-code/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<String>(
Arrays.asList(
"bool",
"int",
"NSString",
"NSObject",
"NSArray",
"NSNumber",
"NSDictionary",
"NSMutableArray",
"NSMutableDictionary")
);
languageSpecificPrimitives = new HashSet<String>(
Arrays.asList(
"NSNumber",
"NSString",
"NSObject",
"bool")
);
reservedWords = new HashSet<String>(
Arrays.asList(
"void", "char", "short", "int", "void", "char", "short", "int",
"long", "float", "double", "signed", "unsigned", "id", "const",
"volatile", "in", "out", "inout", "bycopy", "byref", "oneway",
"self", "super"
));
typeMapping = new HashMap<String, String>();
typeMapping.put("enum", "NSString");
typeMapping.put("Date", "SWGDate");
typeMapping.put("DateTime", "SWGDate");
// typeMapping.put("Date", "SWGDate");
typeMapping.put("boolean", "NSNumber");
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<String, String> ();
importMapping.put("Date", "SWGDate");
foundationClasses = new HashSet<String> (
Arrays.asList(
"NSNumber",
"NSObject",
"NSString",
"NSDictionary")
);
instantiationTypes.put("array", "NSMutableArray");
instantiationTypes.put("map", "NSMutableDictionary");
supportingFiles.add(new SupportingFile("SWGObject.h", sourceFolder, "SWGObject.h"));
supportingFiles.add(new SupportingFile("SWGObject.m", sourceFolder, "SWGObject.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("SWGDate.h", sourceFolder, "SWGDate.h"));
supportingFiles.add(new SupportingFile("SWGDate.m", sourceFolder, "SWGDate.m"));
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) {
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) ||
foundationClasses.contains(type) ||
importMapping.values().contains(type) ||
defaultIncludes.contains(type) ||
languageSpecificPrimitives.contains(type)) {
return Character.toUpperCase(type.charAt(0)) + type.substring(1);
}
else {
return PREFIX + Character.toUpperCase(type.charAt(0)) + type.substring(1);
}
}
@Override
public String toModelImport(String name) {
// name = name + ".h";
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 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_]","");
if(paramName.startsWith("new") || reservedWords.contains(paramName)) {
return escapeReservedWord(paramName);
}
else
return paramName;
}
public String escapeReservedWord(String name) {
return "_" + name;
}
}

View File

@ -0,0 +1,110 @@
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";
// protected String sourceFolder = "";
public String getName() {
return "php";
}
public String getHelp() {
return "Generates a PHP client library.";
}
public PhpClientCodegen() {
super();
outputFolder = "generated-code/php";
modelTemplateFiles.put("model.mustache", ".php");
apiTemplateFiles.put("api.mustache", ".php");
templateDir = "php";
typeMapping.clear();
languageSpecificPrimitives.clear();
reservedWords = new HashSet<String> (
Arrays.asList(
"int")
);
additionalProperties.put("invokerPackage", invokerPackage);
additionalProperties.put("groupId", groupId);
additionalProperties.put("artifactId", artifactId);
additionalProperties.put("artifactVersion", artifactVersion);
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");
supportingFiles.add(new SupportingFile("Swagger.mustache", "", "Swagger.php"));
}
@Override
public String escapeReservedWord(String name) {
return "_" + name;
}
@Override
public String apiFileFolder() {
return outputFolder + "/" + apiPackage().replaceAll("\\.", "/");
}
public String modelFileFolder() {
return outputFolder + "/" + modelPackage().replaceAll("\\.", "/");
}
@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";
}
}

View File

@ -0,0 +1,117 @@
/**
* Copyright 2014 Wordnik, 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.languages;
import com.wordnik.swagger.codegen.*;
import com.wordnik.swagger.models.properties.*;
public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig {
public String getName() {
return "python";
}
public String getHelp() {
return "Generates a Python client library.";
}
public PythonClientCodegen() {
super();
outputFolder = "generated-code/python";
modelTemplateFiles.put("model.mustache", ".py");
apiTemplateFiles.put("api.mustache", ".py");
templateDir = "python";
apiPackage = "";
modelPackage = "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", "long");
typeMapping.put("double", "float");
typeMapping.put("array", "list");
typeMapping.put("map", "map");
typeMapping.put("boolean", "bool");
typeMapping.put("string", "str");
typeMapping.put("date", "datetime");
supportingFiles.add(new SupportingFile("swagger.mustache", "", "swagger.py"));
supportingFiles.add(new SupportingFile("__init__.mustache", "", "__init__.py"));
supportingFiles.add(new SupportingFile("__init__.mustache", modelPackage, "__init__.py"));
}
@Override
public String escapeReservedWord(String name) {
return "_" + name;
}
@Override
public String apiFileFolder() {
return outputFolder + "/" + apiPackage().replaceAll("\\.", "/");
}
public String modelFileFolder() {
return outputFolder + "/" + modelPackage().replaceAll("\\.", "/");
}
@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";
}
}

View File

@ -0,0 +1,182 @@
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-client";
protected String artifactVersion = "1.0.0";
protected String sourceFolder = "src/main/java";
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<String> (
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);
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<String, String>();
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<String>(
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().replaceAll("\\.", "/");
}
public String modelFileFolder() {
return outputFolder + "/" + sourceFolder + "/" + modelPackage().replaceAll("\\.", "/");
}
@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";
}
}

View File

@ -0,0 +1,174 @@
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 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<String> (
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<String>(
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<String>(
Arrays.asList(
"String",
"boolean",
"Boolean",
"Double",
"Integer",
"Long",
"Float",
"Object")
);
instantiationTypes.put("array", "ArrayList");
instantiationTypes.put("map", "HashMap");
importMapping = new HashMap<String, String> ();
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().replaceAll("\\.", "/");
}
public String modelFileFolder() {
return outputFolder + "/" + sourceFolder + "/" + modelPackage().replaceAll("\\.", "/");
}
@Override
public Map<String, Object> postProcessOperations(Map<String, Object> objs) {
Map<String, Object> operations = (Map<String, Object>) objs.get("operations");
List<CodegenOperation> operationList = (List<CodegenOperation>) operations.get("operation");
for(CodegenOperation op: operationList) {
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);
}
}

View File

@ -0,0 +1,72 @@
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 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";
}
}

View File

@ -0,0 +1,81 @@
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 StaticHtmlGenerator 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 String getName() {
return "html";
}
public String getHelp() {
return "Generates a static HTML file.";
}
public StaticHtmlGenerator() {
super();
outputFolder = "docs";
templateDir = "htmlDocs";
defaultIncludes = new HashSet<String>();
String partner = "our Partner";
if(System.getProperty("partner") != null)
partner = System.getProperty("partner");
additionalProperties.put("partner", partner);
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<String>();
languageSpecificPrimitives = new HashSet<String>();
importMapping = new HashMap<String, String> ();
}
@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<String, Object> postProcessOperations(Map<String, Object> objs) {
Map<String, Object> operations = (Map<String, Object>) objs.get("operations");
List<CodegenOperation> operationList = (List<CodegenOperation>) operations.get("operation");
for(CodegenOperation op: operationList) {
op.httpMethod = op.httpMethod.toLowerCase();
}
return objs;
}
}

View File

@ -0,0 +1,38 @@
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 String getName() {
return "swagger";
}
public String getHelp() {
return "Creates a static swagger.json file.";
}
public SwaggerGenerator() {
super();
outputFolder = "generated-code/swagger";
}
@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();
}
}
}

View File

@ -0,0 +1,243 @@
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<String> foundationClasses = new HashSet<String>();
protected String sourceFolder = "client";
protected static String PREFIX = "Sami";
protected Map<String, String> namespaces = new HashMap<String, String>();
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<String>(
Arrays.asList(
"bool",
"int",
"long")
);
languageSpecificPrimitives = new HashSet<String>();
additionalProperties().put("prefix", PREFIX);
reservedWords = new HashSet<String>(
// 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<String, String>();
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<String, String>();
namespaces = new HashMap<String, String> ();
namespaces.put("DateTime", "Tizen::Base::DateTime");
namespaces.put("Integer", "Tizen::Base::Integer");
namespaces.put("Long", "Tizen::Base::Long");
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<String> (
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;
}
}

View File

@ -0,0 +1,50 @@
package {{invokerPackage}};
import groovyx.net.http.HTTPBuilder
import groovyx.net.http.Method
import static groovyx.net.http.ContentType.JSON
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)
}
}
}

View File

@ -0,0 +1,56 @@
package {{package}};
import groovyx.net.http.*
import static groovyx.net.http.ContentType.*
import static groovyx.net.http.Method.*
import {{invokerPackage}}.ApiUtils
//-------------
{{#imports}}import {{import}}
{{/imports}}
import java.util.*;
@Mixin(ApiUtils)
{{#operations}}
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}}"
// 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}}
{{#queryParams}}if(!"null".equals(String.valueOf({{paramName}})))
queryParams.put("{{paramName}}", String.valueOf({{paramName}}))
{{/queryParams}}
{{#headerParams}}headerParams.put("{{paramName}}", {{paramName}})
{{/headerParams}}
invokeApi(onSuccess, onFailure, basePath, versionPath, resourcePath, queryParams, headerParams,
"{{httpMethod}}", "{{returnContainer}}",
{{#returnBaseType}}{{{returnBaseType}}}.class {{/returnBaseType}}{{^returnBaseType}}null {{/returnBaseType}})
}
{{/operation}}
}
{{/operations}}

View File

@ -0,0 +1,32 @@
apply plugin: 'groovy'
apply plugin: 'idea'
def artifactory = 'buildserver.supportspace.com'
group = 'com.supportspace'
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 {
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'
}
task wrapper(type: Wrapper) { gradleVersion = '1.6' }

View File

@ -0,0 +1,21 @@
package {{package}};
import groovy.transform.Canonical
{{#imports}}import {{import}};
{{/imports}}
{{#models}}
{{#model}}
@Canonical
class {{classname}} {
{{#vars}}
{{#description}}/* {{{description}}} */
{{/description}}
{{{datatype}}} {{name}} = {{{defaultValue}}}
{{/vars}}
}
{{/model}}
{{/models}}

View File

@ -0,0 +1,23 @@
package {{invokerPackage}};
import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.core.JsonGenerator.Feature;
import com.fasterxml.jackson.datatype.joda.*;
public class JsonUtil {
public static ObjectMapper mapper;
static {
mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
mapper.registerModule(new JodaModule());
}
public static ObjectMapper getJsonMapper() {
return mapper;
}
}

View File

@ -0,0 +1,109 @@
package {{package}};
import {{invokerPackage}}.ApiException;
import {{invokerPackage}}.ApiInvoker;
import {{modelPackage}}.*;
import java.util.*;
{{#imports}}import {{import}};
{{/imports}}
import com.sun.jersey.multipart.FormDataMultiPart;
import javax.ws.rs.core.MediaType;
import java.io.File;
import java.util.Map;
import java.util.HashMap;
{{#operations}}
public class {{classname}} {
String basePath = "{{basePath}}";
ApiInvoker apiInvoker = ApiInvoker.getInstance();
public ApiInvoker getInvoker() {
return apiInvoker;
}
public void setBasePath(String basePath) {
this.basePath = basePath;
}
public String getBasePath() {
return basePath;
}
{{#operation}}
{{#errorList}} //error info- code: {{code}} reason: "{{reason}}" model: {{#responseModel}}{{responseModel}}
{{/responseModel}}{{^responseModel}}<none>
{{/responseModel}}
{{/errorList}}
public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}}{{nickname}} ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws ApiException {
Object postBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}};
{{#requiredParamCount}}
// verify required params are set
if({{/requiredParamCount}}{{#requiredParams}} {{paramName}} == null {{#hasMore}}|| {{/hasMore}}{{/requiredParams}}{{#requiredParamCount}}) {
throw new ApiException(400, "missing required params");
}
{{/requiredParamCount}}
// create path and map variables
String path = "{{path}}".replaceAll("\\{format\\}","json"){{#pathParams}}
.replaceAll("\\{" + "{{paramName}}" + "\\}", apiInvoker.escapeString({{{paramName}}}.toString())){{/pathParams}};
// query params
Map<String, String> queryParams = new HashMap<String, String>();
Map<String, String> headerParams = new HashMap<String, String>();
Map<String, String> formParams = new HashMap<String, String>();
{{#queryParams}}if(!"null".equals(String.valueOf({{paramName}})))
queryParams.put("{{baseName}}", String.valueOf({{paramName}}));
{{/queryParams}}
{{#headerParams}}headerParams.put("{{baseName}}", {{paramName}});
{{/headerParams}}
String[] contentTypes = {
{{#consumes}}"{{mediaType}}"{{#hasMore}},{{/hasMore}}{{/consumes}}
};
String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json";
if(contentType.startsWith("multipart/form-data")) {
boolean hasFields = false;
FormDataMultiPart mp = new FormDataMultiPart();
{{#formParams}}{{#notFile}}
hasFields = true;
mp.field("{{baseName}}", {{paramName}}, MediaType.MULTIPART_FORM_DATA_TYPE);
{{/notFile}}{{#isFile}}
hasFields = true;
mp.field("{{baseName}}", {{paramName}}, MediaType.MULTIPART_FORM_DATA_TYPE);
{{/isFile}}{{/formParams}}
if(hasFields)
postBody = mp;
}
else {
{{#formParams}}{{#notFile}}formParams.put("{{baseName}}", {{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 {
return {{#returnType}}null{{/returnType}};
}
} catch (ApiException ex) {
if(ex.getCode() == 404) {
return {{#returnType}} null{{/returnType}};
}
else {
throw ex;
}
}
}
{{/operation}}
}
{{/operations}}

View File

@ -0,0 +1,29 @@
package {{invokerPackage}};
public class ApiException extends Exception {
int code = 0;
String message = null;
public ApiException() {}
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;
}
}

View File

@ -0,0 +1,187 @@
package {{invokerPackage}};
import com.fasterxml.jackson.core.JsonGenerator.Feature;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.client.filter.LoggingFilter;
import com.sun.jersey.api.client.WebResource.Builder;
import com.sun.jersey.multipart.FormDataMultiPart;
import javax.ws.rs.core.Response.Status.Family;
import javax.ws.rs.core.MediaType;
import java.util.Map;
import java.util.HashMap;
import java.util.List;
import java.io.IOException;
import java.net.URLEncoder;
import java.io.UnsupportedEncodingException;
public class ApiInvoker {
private static ApiInvoker INSTANCE = new ApiInvoker();
private Map<String, Client> hostMap = new HashMap<String, Client>();
private Map<String, String> defaultHeaderMap = new HashMap<String, String>();
private boolean isDebug = false;
public void enableDebug() {
isDebug = true;
}
public static ApiInvoker getInstance() {
return INSTANCE;
}
public void addDefaultHeader(String key, String value) {
defaultHeaderMap.put(key, value);
}
public String escapeString(String str) {
try{
return URLEncoder.encode(str, "utf8").replaceAll("\\+", "%20");
}
catch(UnsupportedEncodingException e) {
return str;
}
}
public static Object deserialize(String json, String containerType, Class cls) throws ApiException {
try{
if("List".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());
}
}
public static 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());
}
}
public String invokeAPI(String host, String path, String method, Map<String, String> queryParams, Object body, Map<String, String> headerParams, Map<String, String> formParams, String contentType) throws ApiException {
Client 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 querystring = b.toString();
Builder builder = client.resource(host + path + querystring).accept("application/json");
for(String key : headerParams.keySet()) {
builder.header(key, headerParams.get(key));
}
for(String key : defaultHeaderMap.keySet()) {
if(!headerParams.containsKey(key)) {
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(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(body == null)
response = builder.put(ClientResponse.class, serialize(body));
else {
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
}
}
}
response = builder.type(contentType).put(ClientResponse.class, formParamBuilder.toString());
}
else
response = builder.type(contentType).put(ClientResponse.class, serialize(body));
}
}
else if ("DELETE".equals(method)) {
if(body == null)
response = builder.delete(ClientResponse.class, serialize(body));
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) {
return (String) response.getEntity(String.class);
}
else {
throw new ApiException(
response.getClientResponseStatus().getStatusCode(),
response.getEntity(String.class));
}
}
private Client getClient(String host) {
if(!hostMap.containsKey(host)) {
Client client = Client.create();
if(isDebug)
client.addFilter(new LoggingFilter());
hostMap.put(host, client);
}
return hostMap.get(host);
}
}

View File

@ -0,0 +1,49 @@
package {{package}};
{{#imports}}import {{import}};
{{/imports}}
import com.wordnik.swagger.annotations.*;
import com.fasterxml.jackson.annotation.JsonProperty;
{{#models}}
{{#model}}{{#description}}
/**
* {{description}}
**/{{/description}}
@ApiModel(description = "{{{description}}}")
public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} { {{#vars}}
private {{{datatype}}} {{name}} = {{{defaultValue}}};{{#allowableValues}}
//{{^min}}public enum {{name}}Enum { {{#values}} {{.}}, {{/values}} };
{{/min}}{{/allowableValues}}{{/vars}}
{{#vars}}
/**{{#description}}
* {{{description}}}{{/description}}{{#minimum}}
* minimum: {{minimum}}{{/minimum}}{{#maximum}}
* maximum: {{maximum}}{{/maximum}}
**/
@ApiModelProperty(required = {{required}}, value = "{{{description}}}")
@JsonProperty("{{name}}")
public {{{datatype}}} {{getter}}() {
return {{name}};
}
public void {{setter}}({{{datatype}}} {{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();
}
}
{{/model}}
{{/models}}

View File

@ -0,0 +1,168 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>{{groupId}}</groupId>
<artifactId>{{artifactId}}</artifactId>
<packaging>jar</packaging>
<name>{{artifactId}}</name>
<version>{{artifactVersion}}</version>
<scm>
<connection>scm:git:git@github.com:wordnik/swagger-mustache.git</connection>
<developerConnection>scm:git:git@github.com:wordnik/swagger-codegen.git</developerConnection>
<url>https://github.com/wordnik/swagger-codegen</url>
</scm>
<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>
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/lib</outputDirectory>
</configuration>
</execution>
</executions>
</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-annotations</artifactId>
<version>${swagger-annotations-version}</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-client</artifactId>
<version>${jersey-version}</version>
</dependency>
<dependency>
<groupId>com.sun.jersey.contribs</groupId>
<artifactId>jersey-multipart</artifactId>
<version>${jersey-version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${jackson-version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>${jackson-version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson-version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-joda</artifactId>
<version>2.1.5</version>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>${jodatime-version}</version>
</dependency>
<!-- test dependencies -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit-version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<swagger-annotations-version>1.5.0-M1</swagger-annotations-version>
<jersey-version>1.7</jersey-version>
<jackson-version>2.1.4</jackson-version>
<jodatime-version>2.3</jodatime-version>
<junit-version>4.8.1</junit-version>
<maven-plugin-version>1.0.0</maven-plugin-version>
<junit-version>4.8.1</junit-version>
</properties>
</project>

View File

@ -0,0 +1,9 @@
package {{apiPackage}};
public class ApiException extends Exception{
private int code;
public ApiException (int code, String msg) {
super(msg);
this.code = code;
}
}

View File

@ -0,0 +1,26 @@
package {{apiPackage}};
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 {
}
}

View File

@ -0,0 +1,68 @@
package {{apiPackage}};
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;
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;
}
@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;
}
}

View File

@ -0,0 +1,9 @@
package {{apiPackage}};
public class NotFoundException extends ApiException {
private int code;
public NotFoundException (int code, String msg) {
super(code, msg);
this.code = code;
}
}

View File

@ -0,0 +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
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)

View File

@ -0,0 +1,40 @@
package {{package}};
import {{modelPackage}}.*;
import com.wordnik.swagger.annotations.*;
import com.sun.jersey.multipart.FormDataParam;
{{#imports}}import {{import}};
{{/imports}}
import java.util.List;
import {{package}}.NotFoundException;
import javax.ws.rs.core.Response;
import javax.ws.rs.*;
@Path("/{{baseName}}")
@Api(value = "/{{baseName}}", description = "the {{baseName}} API")
{{#operations}}
public class {{classname}} {
{{#operation}}
@{{httpMethod}}
{{#subresourceOperation}}@Path("{{path}}"){{/subresourceOperation}}
{{#hasConsumes}}@Consumes({ {{#consumes}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} }){{/hasConsumes}}
{{#hasProduces}}@Produces({ {{#produces}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }){{/hasProduces}}
@ApiOperation(value = "{{{summary}}}", notes = "{{{notes}}}", response = {{{returnType}}}.class{{#returnContainer}}, responseContainer = "{{{returnContainer}}}"{{/returnContainer}})
@ApiResponses(value = { {{#responses}}
@ApiResponse(code = {{{code}}}, message = "{{{message}}}"){{#hasMore}},
{{/hasMore}}{{/responses}} })
public Response {{nickname}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}},
{{/hasMore}}{{/allParams}})
throws NotFoundException {
// do some magic!
return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build();
}
{{/operation}}
}
{{/operations}}

View File

@ -0,0 +1 @@
{{#isBodyParam}}@ApiParam(value = "{{{description}}}" {{#required}},required=true{{/required}} {{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) {{{dataType}}} {{paramName}}{{/isBodyParam}}

View File

@ -0,0 +1 @@
{{#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}}}"{{#required}}, required=true{{/required}} {{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}})@FormDataParam("{{paramName}}") {{{dataType}}} {{paramName}}{{/isFile}}{{/isFormParam}}

View File

@ -0,0 +1 @@
{{#isHeaderParam}}@ApiParam(value = "{{{description}}}" {{#required}},required=true{{/required}} {{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}})@HeaderParam("{{paramName}}") {{{dataType}}} {{paramName}}{{/isHeaderParam}}

View File

@ -0,0 +1,47 @@
package {{package}};
{{#imports}}import {{import}};
{{/imports}}
import com.wordnik.swagger.annotations.*;
{{#models}}
{{#model}}{{#description}}
/**
* {{description}}
**/{{/description}}
@ApiModel(description = "{{{description}}}")
public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} { {{#vars}}
/**{{#description}}
* {{{description}}}{{/description}}{{#minimum}}
* minimum: {{minimum}}{{/minimum}}{{#maximum}}
* maximum: {{maximum}}{{/maximum}}
**/
private {{{datatype}}} {{name}} = {{{defaultValue}}};{{#isEnum}}
public enum {{datatype}} { {{#_enum}}{{.}}{{^-last}}, {{/-last}}{{/_enum}} };
{{/isEnum}}{{/vars}}
{{#vars}}
@ApiModelProperty(required = {{required}}, value = "{{{description}}}")
public {{{datatype}}} {{getter}}() {
return {{name}};
}
public void {{setter}}({{{datatype}}} {{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();
}
}
{{/model}}
{{/models}}

View File

@ -0,0 +1 @@
{{#isPathParam}}@ApiParam(value = "{{{description}}}"{{#required}},required=true{{/required}}{{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}} {{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) @PathParam("{{paramName}}") {{{dataType}}} {{paramName}}{{/isPathParam}}

View File

@ -0,0 +1,141 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>{{groupId}}</groupId>
<artifactId>{{artifactId}}</artifactId>
<packaging>jar</packaging>
<name>{{artifactId}}</name>
<version>{{artifactVersion}}</version>
<build>
<sourceDirectory>src/main/java</sourceDirectory>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.1.1</version>
</plugin>
<plugin>
<artifactId>maven-failsafe-plugin</artifactId>
<version>2.6</version>
<executions>
<execution>
<goals>
<goal>integration-test</goal>
<goal>verify</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.mortbay.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>${jetty-version}</version>
<configuration>
<webAppConfig>
<contextPath>{{^basePath}}/{{/basePath}}{{#basePath}}{{basePath}}{{/basePath}}</contextPath>
</webAppConfig>
<webAppSourceDirectory>target/${project.artifactId}-${project.version}</webAppSourceDirectory>
<webDefaultXml>${project.basedir}/conf/jetty/webdefault.xml</webDefaultXml>
<stopPort>8079</stopPort>
<stopKey>stopit</stopKey>
<connectors>
<connector implementation="org.eclipse.jetty.server.nio.SelectChannelConnector">
<port>8002</port>
<maxIdleTime>60000</maxIdleTime>
<confidentialPort>8443</confidentialPort>
</connector>
</connectors>
</configuration>
<executions>
<execution>
<id>start-jetty</id>
<phase>pre-integration-test</phase>
<goals>
<goal>run</goal>
</goals>
<configuration>
<scanIntervalSeconds>0</scanIntervalSeconds>
<daemon>true</daemon>
</configuration>
</execution>
<execution>
<id>stop-jetty</id>
<phase>post-integration-test</phase>
<goals>
<goal>stop</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>com.wordnik</groupId>
<artifactId>swagger-jersey-jaxrs</artifactId>
<version>${swagger-core-version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j-version}</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-core</artifactId>
<version>${jersey-version}</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-json</artifactId>
<version>${jersey-version}</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-servlet</artifactId>
<version>${jersey-version}</version>
</dependency>
<dependency>
<groupId>com.sun.jersey.contribs</groupId>
<artifactId>jersey-multipart</artifactId>
<version>${jersey-version}</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-server</artifactId>
<version>${jersey-version}</version>
</dependency>
<dependency>
<groupId>org.scalatest</groupId>
<artifactId>scalatest_2.9.1</artifactId>
<version>${scala-test-version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit-version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>${servlet-api-version}</version>
</dependency>
</dependencies>
<repositories>
<repository>
<id>sonatype-snapshots</id>
<url>https://oss.sonatype.org/content/repositories/snapshots</url>
</repository>
</repositories>
<properties>
<swagger-core-version>1.5.0-SNAPSHOT</swagger-core-version>
<jetty-version>8.1.11.v20130520</jetty-version>
<jersey-version>1.13</jersey-version>
<slf4j-version>1.6.3</slf4j-version>
<scala-test-version>1.6.1</scala-test-version>
<junit-version>4.8.1</junit-version>
<servlet-api-version>2.5</servlet-api-version>
</properties>
</project>

View File

@ -0,0 +1 @@
sbt.version=0.12.0

View File

@ -0,0 +1,9 @@
addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "0.8.4")
libraryDependencies <+= sbtVersion(v => v match {
case "0.11.0" => "com.github.siasia" %% "xsbt-web-plugin" % "0.11.0-0.2.8"
case "0.11.1" => "com.github.siasia" %% "xsbt-web-plugin" % "0.11.1-0.2.10"
case "0.11.2" => "com.github.siasia" %% "xsbt-web-plugin" % "0.11.2-0.2.11"
case "0.11.3" => "com.github.siasia" %% "xsbt-web-plugin" % "0.11.3-0.2.11.1"
case x if (x.startsWith("0.12")) => "com.github.siasia" %% "xsbt-web-plugin" % "0.12.0-0.2.11.1"
})

View File

@ -0,0 +1 @@
{{#isQueryParam}}@ApiParam(value = "{{{description}}}"{{#required}},required=true{{/required}}{{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) @QueryParam("{{paramName}}") {{{dataType}}} {{paramName}}{{/isQueryParam}}

View File

@ -0,0 +1,54 @@
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:j2ee="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<servlet>
<servlet-name>jersey</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>com.wordnik.swagger.jaxrs.json;com.wordnik.swagger.jaxrs.listing;{{apiPackage}}</param-value>
</init-param>
<init-param>
<param-name>com.sun.jersey.spi.container.ContainerRequestFilters</param-name>
<param-value>com.sun.jersey.api.container.filter.PostReplaceFilter</param-value>
</init-param>
<init-param>
<param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
<param-value>true</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet>
<servlet-name>DefaultJaxrsConfig</servlet-name>
<servlet-class>com.wordnik.swagger.jaxrs.config.DefaultJaxrsConfig</servlet-class>
<init-param>
<param-name>api.version</param-name>
<param-value>1.0.0</param-value>
</init-param>
<init-param>
<param-name>swagger.api.title</param-name>
<param-value>{{{title}}}</param-value>
</init-param>
<init-param>
<param-name>swagger.api.basepath</param-name>
<param-value>http://localhost:8002</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>jersey</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<filter>
<filter-name>ApiOriginFilter</filter-name>
<filter-class>com.wordnik.api.ApiOriginFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>ApiOriginFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>

View File

@ -0,0 +1,13 @@
com.wordnik.swagger.codegen.languages.AndroidClientCodegen
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.ScalatraServerCodegen
com.wordnik.swagger.codegen.languages.ScalaClientCodegen
com.wordnik.swagger.codegen.languages.StaticDocCodegen
com.wordnik.swagger.codegen.languages.StaticHtmlGenerator
com.wordnik.swagger.codegen.languages.SwaggerGenerator
com.wordnik.swagger.codegen.languages.TizenClientCodegen
com.wordnik.swagger.codegen.languages.PhpClientCodegen
com.wordnik.swagger.codegen.languages.PythonClientCodegen

View File

@ -0,0 +1,88 @@
package {{package}};
import {{invokerPackage}}.ApiException;
import {{invokerPackage}}.ApiInvoker;
import {{modelPackage}}.*;
import java.util.*;
{{#imports}}import {{import}};
{{/imports}}
import java.util.Map;
import java.util.HashMap;
import java.io.File;
{{#operations}}
public class {{classname}} {
String basePath = "{{basePath}}";
ApiInvoker apiInvoker = ApiInvoker.getInstance();
public void addHeader(String key, String value) {
getInvoker().addDefaultHeader(key, value);
}
public ApiInvoker getInvoker() {
return apiInvoker;
}
public void setBasePath(String basePath) {
this.basePath = basePath;
}
public String getBasePath() {
return basePath;
}
{{#operation}}
{{#errorList}} //error info- code: {{code}} reason: "{{reason}}" model: {{#responseModel}}{{responseModel}}
{{/responseModel}}{{^responseModel}}<none>
{{/responseModel}}
{{/errorList}}
public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}} {{nickname}} ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws ApiException {
Object postBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}};
{{#requiredParamCount}}
// verify required params are set
if({{/requiredParamCount}}{{#requiredParams}} {{paramName}} == null {{#hasMore}}|| {{/hasMore}}{{/requiredParams}}{{#requiredParamCount}}) {
throw new ApiException(400, "missing required params");
}
{{/requiredParamCount}}
// create path and map variables
String path = "{{path}}".replaceAll("\\{format\\}","json"){{#pathParams}}.replaceAll("\\{" + "{{paramName}}" + "\\}", apiInvoker.escapeString({{{paramName}}}.toString())){{/pathParams}};
// query params
Map<String, String> queryParams = new HashMap<String, String>();
Map<String, String> headerParams = new HashMap<String, String>();
{{#queryParams}}if(!"null".equals(String.valueOf({{paramName}})))
queryParams.put("{{baseName}}", String.valueOf({{paramName}}));
{{/queryParams}}
{{#headerParams}}headerParams.put("{{baseName}}", {{paramName}});
{{/headerParams}}
String contentType = "application/json";
try {
String response = apiInvoker.invokeAPI(basePath, path, "{{httpMethod}}", queryParams, postBody, headerParams, contentType);
if(response != null){
return {{#returnType}}({{{returnType}}}) ApiInvoker.deserialize(response, "{{returnContainer}}", {{returnBaseType}}.class){{/returnType}};
}
else {
return {{#returnType}}null{{/returnType}};
}
} catch (ApiException ex) {
if(ex.getCode() == 404) {
return {{#returnType}} null{{/returnType}};
}
else {
throw ex;
}
}
}
{{/operation}}
}
{{/operations}}

View File

@ -0,0 +1,29 @@
package {{invokerPackage}};
public class ApiException extends Exception {
int code = 0;
String message = null;
public ApiException() {}
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;
}
}

View File

@ -0,0 +1,283 @@
package {{invokerPackage}};
import com.fasterxml.jackson.core.JsonGenerator.Feature;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import org.apache.http.*;
import org.apache.http.client.*;
import org.apache.http.client.methods.*;
import org.apache.http.conn.*;
import org.apache.http.conn.scheme.*;
import org.apache.http.conn.ssl.*;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.*;
import org.apache.http.impl.conn.*;
import org.apache.http.params.*;
import org.apache.http.util.EntityUtils;
import java.io.File;
import java.net.Socket;
import java.net.UnknownHostException;
import java.net.URLEncoder;
import java.util.Map;
import java.util.HashMap;
import java.util.List;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
public class ApiInvoker {
private static ApiInvoker INSTANCE = new ApiInvoker();
private Map<String, String> defaultHeaderMap = new HashMap<String, String>();
private HttpClient client = null;
private boolean ignoreSSLCertificates = false;
private ClientConnectionManager ignoreSSLConnectionManager;
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".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());
}
}
public static 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());
}
}
public String invokeAPI(String host, String path, String method, Map<String, String> queryParams, Object body, Map<String, String> headerParams, 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<String, String> headers = new HashMap<String, String>();
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");
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 (body != null) {
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(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 (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);
}
}
else {
if(response.getEntity() != null) {
HttpEntity resEntity = response.getEntity();
responseString = EntityUtils.toString(resEntity);
}
else
responseString = "no data";
throw new ApiException(code, responseString);
}
return 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 SingleClientConnManager(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.
}
}
}

View File

@ -0,0 +1,16 @@
package {{invokerPackage}};
import org.apache.http.client.methods.*;
public class HttpPatch extends HttpPost {
public static final String METHOD_PATCH = "PATCH";
public HttpPatch(final String url) {
super(url);
}
@Override
public String getMethod() {
return METHOD_PATCH;
}
}

View File

@ -0,0 +1,20 @@
package {{invokerPackage}};
import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.core.JsonGenerator.Feature;
public class JsonUtil {
public static ObjectMapper mapper;
static {
mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
}
public static ObjectMapper getJsonMapper() {
return mapper;
}
}

View File

@ -0,0 +1,47 @@
package {{package}};
{{#imports}}import {{import}};
{{/imports}}
import com.wordnik.swagger.annotations.*;
{{#models}}
{{#model}}{{#description}}
/**
* {{description}}
**/{{/description}}
@ApiModel(description = "{{{description}}}")
public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} { {{#vars}}
private {{{datatype}}} {{name}} = {{{defaultValue}}};{{#allowableValues}}
//{{^min}}public enum {{name}}Enum { {{#values}} {{.}}, {{/values}} };
{{/min}}{{/allowableValues}}{{/vars}}
{{#vars}}
/**{{#description}}
* {{{description}}}{{/description}}{{#minimum}}
* minimum: {{minimum}}{{/minimum}}{{#maximum}}
* maximum: {{maximum}}{{/maximum}}
**/
@ApiModelProperty(required = {{required}}, value = "{{{description}}}")
public {{{datatype}}} {{getter}}() {
return {{name}};
}
public void {{setter}}({{{datatype}}} {{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();
}
}
{{/model}}
{{/models}}

View File

@ -0,0 +1,162 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>{{groupId}}</groupId>
<artifactId>{{artifactId}}</artifactId>
<packaging>jar</packaging>
<name>{{artifactId}}</name>
<version>{{artifactVersion}}</version>
<scm>
<connection>scm:git:git@github.com:wordnik/swagger-mustache.git</connection>
<developerConnection>scm:git:git@github.com:wordnik/swagger-codegen.git</developerConnection>
<url>https://github.com/wordnik/swagger-codegen</url>
</scm>
<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>
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/lib</outputDirectory>
</configuration>
</execution>
</executions>
</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-annotations</artifactId>
<version>${swagger-annotations-version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${jackson-version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>${jackson-version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson-version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>${httpclient-version}</version>
<scope>compile</scope>
</dependency>
<!-- test dependencies -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit-version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<repositories>
<repository>
<id>sonatype-snapshots</id>
<url>https://oss.sonatype.org/content/repositories/snapshots</url>
</repository>
</repositories>
<properties>
<swagger-annotations-version>1.5.0-SNAPSHOT</swagger-annotations-version>
<jackson-version>2.1.4</jackson-version>
<junit-version>4.8.1</junit-version>
<maven-plugin-version>1.0.0</maven-plugin-version>
<junit-version>4.8.1</junit-version>
<httpclient-version>4.0</httpclient-version>
</properties>
</project>

View File

@ -0,0 +1,59 @@
package {{package}}
{{#imports}}import {{import}}
{{/imports}}
import com.wordnik.swagger.client._
import scala.concurrent.{ Future, Await }
import scala.concurrent.duration._
import collection.mutable
{{#operations}}
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}})
// 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}}
{{#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}}
val resFuture = client.submit("{{httpMethod}}", path, queryParams.toMap, headerParams.toMap, {{#bodyParam}}writer.write({{bodyParam}}){{/bodyParam}}{{^bodyParam}}"{{emptyBodyParam}}"{{/bodyParam}})
resFuture flatMap { resp =>
process(reader.read(resp))
}
}
{{/operation}}
}
{{/operations}}

View File

@ -0,0 +1,26 @@
package {{package}}
{{#imports}}import {{import}}
{{/imports}}
import com.wordnik.swagger.client._
import apis._
import java.io.Closeable
class {{clientName}}(config: SwaggerConfig) extends Closeable {
val locator = config.locator
val name = config.name
private[this] val client = transportClient
protected def transportClient: TransportClient = new RestClient(config)
{{#apiInfo}}
{{#apis}}
val {{name}} = new {{className}}(client, config)
{{/apis}}
{{/apiInfo}}
def close() {
client.close()
}
}

View File

@ -0,0 +1,15 @@
package {{package}}
import org.joda.time.DateTime
{{#models}}
{{#model}}
case class {{classname}} (
{{#vars}}
{{name}}: {{#isNotRequired}}Option[{{/isNotRequired}}{{datatype}}{{#isNotRequired}}]{{/isNotRequired}} {{#hasMore}},{{/hasMore}}{{#description}} // {{description}}{{/description}}{{newline}}
{{/vars}}
)
{{/model}}
{{/models}}

View File

@ -0,0 +1,11 @@
organization := "{{package}}"
name := "{{projectName}}-client"
libraryDependencies += "com.wordnik.swagger" %% "swagger-async-httpclient" % "0.3.0-WN5"
libraryDependencies += "joda-time" % "joda-time" % "2.3"
libraryDependencies += "org.joda" % "joda-convert" % "1.3.1"
libraryDependencies += "ch.qos.logback" % "logback-classic" % "1.0.13" % "provided"

View File

@ -0,0 +1,101 @@
using System;
using System.Collections.Generic;
using {{invokerPackage}};
using {{modelPackage}};
{{#imports}}
{{/imports}}
namespace {{package}} {
{{#operations}}
public class {{classname}} {
string basePath;
private readonly ApiInvoker apiInvoker = ApiInvoker.GetInstance();
public {{classname}}(String basePath = "{{basePath}}")
{
this.basePath = basePath;
}
public ApiInvoker getInvoker() {
return apiInvoker;
}
// Sets the endpoint base url for the services being accessed
public void setBasePath(string basePath) {
this.basePath = basePath;
}
// Gets the endpoint base url for the services being accessed
public String getBasePath() {
return basePath;
}
{{#operation}}
/// <summary>
/// {{summary}} {{notes}}
/// </summary>
{{#allParams}}/// <param name="{{paramName}}">{{description}}</param>
{{#hasMore}} {{/hasMore}}{{/allParams}}
/// <returns></returns>
public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}} {{nickname}} ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) {
// create path and map variables
var path = "{{path}}".Replace("{format}","json"){{#pathParams}}.Replace("{" + "{{paramName}}" + "}", apiInvoker.escapeString({{{paramName}}}.ToString())){{/pathParams}};
// query params
var queryParams = new Dictionary<String, String>();
var headerParams = new Dictionary<String, String>();
var formParams = new Dictionary<String, object>();
{{#requiredParamCount}}
// verify required params are set
if ({{/requiredParamCount}}{{#requiredParams}} {{paramName}} == null {{#hasMore}}|| {{/hasMore}}{{/requiredParams}}{{#requiredParamCount}}) {
throw new ApiException(400, "missing required params");
}
{{/requiredParamCount}}
{{#queryParams}}if ({{paramName}} != null){
string paramStr = ({{paramName}} is DateTime) ? ((DateTime)(object){{paramName}}).ToString("u") : Convert.ToString({{paramName}});
queryParams.Add("{{paramName}}", paramStr);
}
{{/queryParams}}
{{#headerParams}}headerParams.Add("{{paramName}}", {{paramName}});
{{/headerParams}}
{{#formParams}}if ({{paramName}} != null){
if({{paramName}} is byte[]) {
formParams.Add("{{paramName}}", {{paramName}});
} else {
string paramStr = ({{paramName}} is DateTime) ? ((DateTime)(object){{paramName}}).ToString("u") : Convert.ToString({{paramName}});
formParams.Add("{{paramName}}", paramStr);
}
}
{{/formParams}}
try {
if (typeof({{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}}) == typeof(byte[])) {
var response = apiInvoker.invokeBinaryAPI(basePath, path, "GET", queryParams, null, headerParams, formParams);
return {{#returnType}}((object)response) as {{{returnType}}}{{/returnType}};
} else {
var response = apiInvoker.invokeAPI(basePath, path, "{{httpMethod}}", queryParams, {{#bodyParam}}{{bodyParam}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}, headerParams, formParams);
if(response != null){
return {{#returnType}}({{{returnType}}}) ApiInvoker.deserialize(response, typeof({{{returnType}}})){{/returnType}};
}
else {
return {{#returnType}}null{{/returnType}};
}
}
} catch (ApiException ex) {
if(ex.ErrorCode == 404) {
return {{#returnType}}null{{/returnType}};
}
else {
throw ex;
}
}
}
{{/operation}}
}
{{/operations}}
}

View File

@ -0,0 +1,21 @@
using System;
namespace {{invokerPackage}} {
public class ApiException : Exception {
private int errorCode = 0;
public ApiException() {}
public int ErrorCode {
get
{
return errorCode;
}
}
public ApiException(int errorCode, string message) : base(message) {
this.errorCode = errorCode;
}
}
}

View File

@ -0,0 +1,207 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using Newtonsoft.Json;
namespace {{invokerPackage}} {
public class ApiInvoker {
private static readonly ApiInvoker _instance = new ApiInvoker();
private Dictionary<String, String> defaultHeaderMap = new Dictionary<String, String>();
public static ApiInvoker GetInstance() {
return _instance;
}
public void addDefaultHeader(string key, string value) {
defaultHeaderMap.Add(key, value);
}
public string escapeString(string str) {
return str;
}
public static object deserialize(string json, Type type) {
try
{
return JsonConvert.DeserializeObject(json, type);
}
catch (IOException e) {
throw new ApiException(500, e.Message);
}
}
public static string serialize(object obj) {
try
{
return obj != null ? JsonConvert.SerializeObject(obj) : null;
}
catch (Exception e) {
throw new ApiException(500, e.Message);
}
}
public string invokeAPI(string host, string path, string method, Dictionary<String, String> queryParams, object body, Dictionary<String, String> headerParams, Dictionary<String, object> formParams)
{
return invokeAPIInternal(host, path, method, false, queryParams, body, headerParams, formParams) as string;
}
public byte[] invokeBinaryAPI(string host, string path, string method, Dictionary<String, String> queryParams, object body, Dictionary<String, String> headerParams, Dictionary<String, object> formParams)
{
return invokeAPIInternal(host, path, method, true, queryParams, body, headerParams, formParams) as byte[];
}
private object invokeAPIInternal(string host, string path, string method, bool binaryResponse, Dictionary<String, String> queryParams, object body, Dictionary<String, String> headerParams, Dictionary<String, object> formParams) {
var b = new StringBuilder();
foreach (var queryParamItem in queryParams)
{
var value = queryParamItem.Value;
if (value == null) continue;
b.Append(b.ToString().Length == 0 ? "?" : "&");
b.Append(escapeString(queryParamItem.Key)).Append("=").Append(escapeString(value));
}
var querystring = b.ToString();
host = host.EndsWith("/") ? host.Substring(0, host.Length - 1) : host;
var client = WebRequest.Create(host + path + querystring);
client.Method = method;
byte[] formData = null;
if (formParams.Count > 0)
{
string formDataBoundary = String.Format("----------{0:N}", Guid.NewGuid());
client.ContentType = "multipart/form-data; boundary=" + formDataBoundary;
formData = GetMultipartFormData(formParams, formDataBoundary);
client.ContentLength = formData.Length;
}
else
{
client.ContentType = "application/json";
}
foreach (var headerParamsItem in headerParams)
{
client.Headers.Add(headerParamsItem.Key, headerParamsItem.Value);
}
foreach (var defaultHeaderMapItem in defaultHeaderMap.Where(defaultHeaderMapItem => !headerParams.ContainsKey(defaultHeaderMapItem.Key)))
{
client.Headers.Add(defaultHeaderMapItem.Key, defaultHeaderMapItem.Value);
}
switch (method)
{
case "GET":
break;
case "POST":
case "PUT":
case "DELETE":
using (Stream requestStream = client.GetRequestStream())
{
if (formData != null)
{
requestStream.Write(formData, 0, formData.Length);
}
var swRequestWriter = new StreamWriter(requestStream);
swRequestWriter.Write(serialize(body));
swRequestWriter.Close();
}
break;
default:
throw new ApiException(500, "unknown method type " + method);
}
try
{
var webResponse = (HttpWebResponse)client.GetResponse();
if (webResponse.StatusCode != HttpStatusCode.OK)
{
webResponse.Close();
throw new ApiException((int)webResponse.StatusCode, webResponse.StatusDescription);
}
if (binaryResponse)
{
using (var memoryStream = new MemoryStream())
{
webResponse.GetResponseStream().CopyTo(memoryStream);
return memoryStream.ToArray();
}
}
else
{
using (var responseReader = new StreamReader(webResponse.GetResponseStream()))
{
var responseData = responseReader.ReadToEnd();
return responseData;
}
}
}
catch(WebException ex)
{
var response = ex.Response as HttpWebResponse;
int statusCode = 0;
if (response != null)
{
statusCode = (int)response.StatusCode;
response.Close();
}
throw new ApiException(statusCode, ex.Message);
}
}
private static byte[] GetMultipartFormData(Dictionary<string, object> postParameters, string boundary)
{
Stream formDataStream = new System.IO.MemoryStream();
bool needsCLRF = false;
foreach (var param in postParameters)
{
// Thanks to feedback from commenters, add a CRLF to allow multiple parameters to be added.
// Skip it on the first parameter, add it to subsequent parameters.
if (needsCLRF)
formDataStream.Write(Encoding.UTF8.GetBytes("\r\n"), 0, Encoding.UTF8.GetByteCount("\r\n"));
needsCLRF = true;
if (param.Value is byte[])
{
string postData = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n",
boundary,
param.Key,
"application/octet-stream");
formDataStream.Write(Encoding.UTF8.GetBytes(postData), 0, Encoding.UTF8.GetByteCount(postData));
// Write the file data directly to the Stream, rather than serializing it to a string.
formDataStream.Write((param.Value as byte[]), 0, (param.Value as byte[]).Length);
}
else
{
string postData = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}",
boundary,
param.Key,
param.Value);
formDataStream.Write(Encoding.UTF8.GetBytes(postData), 0, Encoding.UTF8.GetByteCount(postData));
}
}
// Add the end of the request. Start with a newline
string footer = "\r\n--" + boundary + "--\r\n";
formDataStream.Write(Encoding.UTF8.GetBytes(footer), 0, Encoding.UTF8.GetByteCount(footer));
// Dump the Stream into a byte[]
formDataStream.Position = 0;
byte[] formData = new byte[formDataStream.Length];
formDataStream.Read(formData, 0, formData.Length);
formDataStream.Close();
return formData;
}
}
}

View File

@ -0,0 +1,2 @@
SET CSCPATH=%SYSTEMROOT%\Microsoft.NET\Framework\v4.0.30319
%CSCPATH%\csc /reference:bin/Newtonsoft.Json.dll /target:library /out:bin/{{invokerPackage}}.dll /recurse:src\*.cs /doc:bin/{{invokerPackage}}.xml

View File

@ -0,0 +1,30 @@
using System;
using System.Text;
using System.Collections;
using System.Collections.Generic;
{{#models}}
{{#model}}
namespace {{package}} {
public class {{classname}} {
{{#vars}}
{{#description}}/* {{{description}}} */
{{/description}}
public {{{datatype}}} {{name}} { get; set; }
{{/vars}}
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();
}
}
{{/model}}
{{/models}}
}

View File

@ -0,0 +1,146 @@
<?xml version="1.0" encoding="utf-8" standalone="no"?>
<application xmlns="http://ns.adobe.com/air/application/2.0">
<!-- Adobe AIR Application Descriptor File Template.
Specifies parameters for identifying, installing, and launching AIR applications.
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.
minimumPatchLevel - The minimum patch level of the AIR runtime required to run
the application. Optional.
-->
<!-- A universally unique application identifier. Must be unique across all AIR applications.
Using a reverse DNS-style name as the id is recommended. (Eg. com.example.ExampleApplication.) Required. -->
<id>AirExecutorApp</id>
<!-- Used as the filename for the application. Required. -->
<filename>AirExecutorApp</filename>
<!-- The name that is displayed in the AIR application installer.
May have multiple values for each language. See samples or xsd schema file. Optional. -->
<name>AirExecutorApp</name>
<!-- An application version designator (such as "v1", "2.5", or "Alpha 1"). Required. -->
<version>v1</version>
<!-- Description, displayed in the AIR application installer.
May have multiple values for each language. See samples or xsd schema file. Optional. -->
<!-- <description></description> -->
<!-- Copyright information. Optional -->
<!-- <copyright></copyright> -->
<!-- Publisher ID. Used if you're updating an application created prior to 1.5.3 -->
<!-- <publisherID></publisherID> -->
<!-- Settings for the application's initial window. Required. -->
<initialWindow>
<!-- The main SWF or HTML file of the application. Required. -->
<!-- Note: In Flash Builder, the SWF reference is set automatically. -->
<content>AirExecutorApp.swf</content>
<!-- The title of the main window. Optional. -->
<!-- <title></title> -->
<!-- The type of system chrome to use (either "standard" or "none"). Optional. Default standard. -->
<!-- <systemChrome></systemChrome> -->
<!-- Whether the window is transparent. Only applicable when systemChrome is none. Optional. Default false. -->
<!-- <transparent></transparent> -->
<!-- Whether the window is initially visible. Optional. Default false. -->
<!-- <visible></visible> -->
<!-- Whether the user can minimize the window. Optional. Default true. -->
<!-- <minimizable></minimizable> -->
<!-- Whether the user can maximize the window. Optional. Default true. -->
<!-- <maximizable></maximizable> -->
<!-- Whether the user can resize the window. Optional. Default true. -->
<!-- <resizable></resizable> -->
<!-- The window's initial width in pixels. Optional. -->
<!-- <width></width> -->
<!-- The window's initial height in pixels. Optional. -->
<!-- <height></height> -->
<!-- The window's initial x position. Optional. -->
<!-- <x></x> -->
<!-- The window's initial y position. Optional. -->
<!-- <y></y> -->
<!-- The window's minimum size, specified as a width/height pair in pixels, such as "400 200". Optional. -->
<!-- <minSize></minSize> -->
<!-- The window's initial maximum size, specified as a width/height pair in pixels, such as "1600 1200". Optional. -->
<!-- <maxSize></maxSize> -->
</initialWindow>
<!-- We recommend omitting the supportedProfiles element, -->
<!-- which in turn permits your application to be deployed to all -->
<!-- devices supported by AIR. If you wish to restrict deployment -->
<!-- (i.e., to only mobile devices) then add this element and list -->
<!-- only the profiles which your application does support. -->
<!-- <supportedProfiles>desktop extendedDesktop mobileDevice extendedMobileDevice</supportedProfiles> -->
<!-- The subpath of the standard default installation location to use. Optional. -->
<!-- <installFolder></installFolder> -->
<!-- The subpath of the Programs menu to use. (Ignored on operating systems without a Programs menu.) Optional. -->
<!-- <programMenuFolder></programMenuFolder> -->
<!-- The icon the system uses for the application. For at least one resolution,
specify the path to a PNG file included in the AIR package. Optional. -->
<!-- <icon>
<image16x16></image16x16>
<image32x32></image32x32>
<image48x48></image48x48>
<image128x128></image128x128>
</icon> -->
<!-- Whether the application handles the update when a user double-clicks an update version
of the AIR file (true), or the default AIR application installer handles the update (false).
Optional. Default false. -->
<!-- <customUpdateUI></customUpdateUI> -->
<!-- Whether the application can be launched when the user clicks a link in a web browser.
Optional. Default false. -->
<!-- <allowBrowserInvocation></allowBrowserInvocation> -->
<!-- Listing of file types for which the application can register. Optional. -->
<!-- <fileTypes> -->
<!-- Defines one file type. Optional. -->
<!-- <fileType> -->
<!-- The name that the system displays for the registered file type. Required. -->
<!-- <name></name> -->
<!-- The extension to register. Required. -->
<!-- <extension></extension> -->
<!-- The description of the file type. Optional. -->
<!-- <description></description> -->
<!-- The MIME content type. -->
<!-- <contentType></contentType> -->
<!-- The icon to display for the file type. Optional. -->
<!-- <icon>
<image16x16></image16x16>
<image32x32></image32x32>
<image48x48></image48x48>
<image128x128></image128x128>
</icon> -->
<!-- </fileType> -->
<!-- </fileTypes> -->
</application>

View File

@ -0,0 +1,36 @@
package com.wordnik.swagger.event {
import com.wordnik.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{
/**
* Event type to indicate a unsuccessful invocation
*/
public static const FAILURE_EVENT:String = "unsuccesfulInvocation";
/**
* Event type to indicate a successful invocation
*/
public static const SUCCESS_EVENT:String = "successfulInvocation";
/**
* The Response object which contains response info
*/
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);
}
}
}

View File

@ -0,0 +1,10 @@
package com.wordnik.swagger.exception
{
public class ApiError extends Error
{
public function ApiError(id:*=0, message:*="")
{
super(message,id);
}
}
}

View File

@ -0,0 +1,34 @@
package com.wordnik.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;
}
}

View File

@ -0,0 +1,289 @@
package com.wordnik.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 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 "";
}
}
}

View File

@ -0,0 +1,41 @@
package com.wordnik.swagger.common {
import com.wordnik.swagger.common.ApiUserCredentials;
/**
* @private
* Internal class for the Rest client
*/
internal class ApiUrlHelper {
private static const API_URL_KEY:String = "api_key";
private static const AUTH_TOKEN_URL_KEY:String = "auth_token";
private static const HTTP_URL_PREFIX:String = "http://";
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){
restUrl += ( "?" + API_URL_KEY + "=" + credentials.apiToken );
}
else{
restUrl += ( "&" + API_URL_KEY + "=" + credentials.apiToken );
}
requestHeader.api_key = credentials.apiToken;
if(credentials.authToken != null && credentials.authToken != ""){
restUrl += ( "&" + AUTH_TOKEN_URL_KEY + "=" + credentials.authToken );
requestHeader.auth_token = credentials.authToken;
}
return restUrl;
}
internal static function getProxyUrl(hostName: String, proxyPath: String): String{
if (hostName(hostName.length - 1) == "/") //remove trailing slash
{
hostName = hostName.substring(0, hostName.length - 1);
}
return HTTP_URL_PREFIX + hostName + proxyPath;
}
}
}

View File

@ -0,0 +1,63 @@
package com.wordnik.swagger.common {
/**
* Api account credentials.
*
*/
public class ApiUserCredentials {
/**
* An apitoken that is passed along with the requests
*/
public var apiToken:String;
/**
* A valid auth_token which could be necessary for certain operations
*/
public var authToken:String;
/**
* The userId which could be required for certain operations
*/
public var userId:Number;
/**
* 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
*/
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;
}
}
}

View File

@ -0,0 +1,9 @@
package com.wordnik.swagger.common
{
public interface ListWrapper
{
function getList(): Array;
}
}

View File

@ -0,0 +1,56 @@
package com.wordnik.swagger.event {
/**
* Response contains info on the result of an API invocation.
* A completion listener will expect this Response object.
*/
public class Response {
/**
* Indicates whether the invoked operation failed or succeeded
*/
public var isSuccess:Boolean;
/**
* The payload of the succesful operation eg. a Word in a WordRequest
*/
public var payload:Object;
/**
* Error message in case of failure
*/
public var errorMessage:String;
/**
* A request Id that was passed in by the user as a param when invoking the operation
*/
public var requestId:String;
private static const API_ERROR_MSG:String = "Api error response: ";
public function Response(isSuccessful: Boolean, payload: Object = null, errorMessage: String = null, requestId: String = null) {
this.isSuccess = isSuccessful;
this.payload = payload;
this.errorMessage = getFriendlyMessage(errorMessage);
}
private static function getFriendlyMessage(errorMessage: String): String{
var result: String = errorMessage;
if(errorMessage == null)
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 {
return "Response (requestId:" + requestId + "; isSuccess:" + isSuccess + "; errorMessage:" + errorMessage + "; payload:" + payload + ")";
}
}
}

View File

@ -0,0 +1,75 @@
package com.wordnik.swagger.common
{
import com.wordnik.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;
/**
* 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(",");
}
}
}

View File

@ -0,0 +1,28 @@
package com.wordnik.swagger.common
{
public class XMLWriter
{
public var xml:XML;
public function XMLWriter()
{
xml=<obj/>;
}
public function reset():void {
xml=new XML();
}
public function addProperty(propertyName:String, propertyValue:String):XML {
var xmlProperty:XML=<new/>
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;
}
}
}

View File

@ -0,0 +1,73 @@
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;
{{#imports}}import {{import}};
{{/imports}}
import mx.rpc.AsyncToken;
import mx.utils.UIDUtil;
import flash.utils.Dictionary;
import flash.events.EventDispatcher;
{{#operations}}
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);
}
{{#operation}}
public static const event_{{nickname}}: String = "{{nickname}}";
{{/operation}}
{{#operation}}
/*
* 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}};
// query params
var queryParams: Dictionary = new Dictionary();
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");
}
{{/requiredParamCount}}
{{#queryParams}}if("null" != String({{paramName}}))
queryParams["{{paramName}}"] = toPathValue({{paramName}});
{{/queryParams}}
{{#headerParams}}headerParams["{{paramName}}"] = toPathValue({{paramName}});
{{/headerParams}}
var token:AsyncToken = getApiInvoker().invokeAPI(path, "{{httpMethod}}", queryParams, {{#bodyParam}}{{bodyParam}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}, headerParams);
var requestId: String = getUniqueId();
token.requestId = requestId;
token.completionEventType = "{{nickname}}";
token.returnType = {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}null {{/returnType}};
return requestId;
}
{{/operation}}
}
{{/operations}}
}

View File

@ -0,0 +1,29 @@
# Window and document title for the documentation
title=Sample app AS3 SDK API Documentation
#Path to the source folder where the .as files are located
sourcepath = ./src/main/flex
# Class-folders you want to search for classes to be included in the docs, seperated by spaces (for example ../com/ ../net/ )
# to include every .as and .mxml file within your project, just state ../
domainextensions = ./src/main/flex
# The Location of deployment library on your Computer (PC/Mac) for compiled SWC file
liboutputfolder = bin
liboutputfile = as3-sample-sdk.swc
libpath = lib
# The Location of the output folder for your generated documents
docsoutputfolder = asdoc
# The location of the test sources
testsourcepath = ./src/test/flex
# Home directory for flex sdk, change this to build for Mac or PC using # as comment
FLEX4_SDK_HOME = /usr/local/flex_sdk_4.1.0/
#FLEX4_SDK_HOME = /Applications/Adobe Flash Builder 4/sdks/4.1.0/
# The location of your asdoc.exe, change this to build for Mac or PC using # as comment
#asdoc.exe = C:/Program Files/Adobe/Flash Builder 4/sdks/3.5.0/bin/asdoc.exe
#asdoc.exe = /Applications/Adobe Flash Builder 4/sdks/3.5.0/bin/asdoc

View File

@ -0,0 +1,192 @@
<!-- Flex Library Project ASDocs -->
<project name="AS3SDKCompile" default="compile" basedir=".">
<!-- import our build properties file -->
<property file="./build.properties"/>
<property environment="env"/>
<property name="FLEX_HOME" value="${FLEX4_SDK_HOME}"/>
<property name="FLEX4_HOME" value="${FLEX4_SDK_HOME}"/>
<!--<property name="flexunit.swc" value="../lib/ext/flexunit-4.1.0_RC2-28-flex_3.5.0.12683.swc" />
<property name="flexunit-uilistener.swc" value="../lib/ext/flexunit-uilistener-4.1.0_RC2-28-flex_3.5.0.12683.swc" />
<property name="flexunit-cilistener.swc" value="../lib/ext/flexunit-cilistener-4.1.0_RC2-28-flex_3.5.0.12683.swc" />-->
<!-- Flex Ant Tasks used to perform compc and mxml compiling more info at http://labs.adobe.com/wiki/index.php/Flex_Ant_Tasks -->
<taskdef resource="flexTasks.tasks" classpath="${FLEX_HOME}/ant/lib/flexTasks.jar"/>
<target name="setup" description="perform an setup operations"/>
<!-- Execute the ASDoc Compile wich runs 3 seperate tasks in a series -->
<target name="compile" description="series of tasks to create docs and swc">
<!--<antcall target="cleanDir" description="clean the docs directory"/>-->
<!--<antcall target="asDocs" description="full build of asdocs"/>-->
<antcall target="buildSWC" description="build the SWC file"/>
</target>
<target name="deploy" description="perform an deployment operations"/>
<target name="install" description="perform an installation operations"/>
<!--
DELETE the existing output folder and files and then re-generate the output folder
-->
<target name="clean"
description="DELETE the existing output folder and files and then re-generate the output folder">
<delete dir="${basedir}/${docsoutputfolder}" failonerror="true" includeemptydirs="true"/>
<delete file="${basedir}/${liboutputfolder}/${liboutputfile}"/>
<delete dir="${basedir}/dist" failonerror="true" includeemptydirs="true"/>
<mkdir dir="${basedir}/${docsoutputfolder}"/>
</target>
<!--
Run the ASDoc executable and generate the ASDocs to the new output folder
-->
<target name="docs" description="Run the ASDoc executable and generate the ASDocs to the new output folder">
<exec executable="${FLEX_HOME}/bin/asdoc" failonerror="true">
<arg line="-doc-sources ${sourcepath}"/>
<arg line="-source-path ${sourcepath}"/>
<arg line="-footer 'Copyright Wordnik'"/>
<arg line="-package com.wordnik.swagger.api 'Contains the apis which are used by clients to make calls to the services deployed'"/>
<arg line="-package com.wordnik.swagger.codegen.model 'Contains common classes which encapsulate data elements required'"/>
<arg line="-package com.wordnik.swagger.common 'Contains classes which are used by the api classes to invoke the deployed api like SwaggerApi - a base class, ApiUserCredentials, etc.'"/>
<arg line="-package com.wordnik.swagger.event 'Results of calls made to Wordnik are returned via dispatched events. This package contains such event classes. Right now thats just ApiClientEvent and Response.'"/>
<arg line="-package com.wordnik.swagger.exception 'Contains classes that encapsulate the errors generated'"/>
<arg value="-window-title"/>
<arg value="${title}"/>
<arg value="-main-title"/>
<arg value="${title}"/>
<arg value="-output"/>
<arg value="${basedir}/${docsoutputfolder}"/>
<arg value="-external-library-path"/>
<arg value="${basedir}/${libpath}"/>
</exec>
<echo>docs created</echo>
</target>
<!--
Compile the SWC file library including lib folder and the path to our classes, we use compc for library,
check the docs for Flex Ant Tasks, http://labs.adobe.com/wiki/index.php/Flex_Ant_Tasks.
-->
<target name="buildSWC" description="Compile the SWC file for the Librayr Project">
<compc output="${basedir}/${liboutputfolder}/${liboutputfile}">
<!--
Include the path to any external SWC files used in the sdk, you may have to place name of SWC (ASAXB-0.1.1.swc) at end of path.
So file path would be file="${basedir}/${libpath}/ASAXB-0.1.1.swc"
-->
<include-libraries file="${basedir}/${libpath}/"/>
<source-path path-element="${sourcepath}"/>
<keep-as3-metadata name="XmlRootNode"/>
<keep-as3-metadata name="XmlElement"/>
<keep-as3-metadata name="XmlElements"/>
<!-- include our Class packages into the build (com folder) -->
<include-sources dir="${sourcepath}" includes="*"/>
</compc>
<echo>SWC created</echo>
</target>
<target name="dist" depends="clean, buildSWC, docs">
<mkdir dir="${basedir}/dist/lib"/>
<mkdir dir="${basedir}/dist/docs"/>
<mkdir dir="${basedir}/dist/sample"/>
<copy file="${basedir}/${liboutputfolder}/${liboutputfile}" todir="${basedir}/dist/lib/">
</copy>
<copy todir="${basedir}/dist/docs/">
<fileset dir="${basedir}/asdoc"/>
</copy>
<zip destfile="sample-as3-sdk.zip" basedir="${basedir}/dist"/>
</target>
<!-- Compiles and creates a test app that can be run using the adl - AIR Debug Launcher from command line
Note: For the output file to be executed an xml file is needed which points to this output swf - this is not
generated here
-->
<target name="compile-test" depends="buildSWC">
<property name="FLEX_HOME" value="${FLEX4_SDK_HOME}"/>
<mxmlc
static-rsls="false"
fork="true"
maxmemory="512m"
file="${testsourcepath}/AirExecutorApp.mxml"
output="${basedir}/${liboutputfolder}/AirExecutorApp.swf"
warnings="false"
configname="air"
locale="en_US">
<load-config filename="${FLEX4_HOME}/frameworks/air-config.xml"/>
<source-path path-element="${FLEX_HOME}/frameworks"/>
<compiler.debug>true</compiler.debug>
<source-path path-element="${testsourcepath}"/>
<!--<source-path path-element="${APP_ROOT}/locale/{locale}" />-->
<library-path dir="${FLEX_HOME}/frameworks/libs" append="true">
<include name="*.swc"/>
</library-path>
<library-path dir="${FLEX_HOME}/frameworks/libs/air" append="true">
<include name="*.swc"/>
</library-path>
<library-path dir="${FLEX_HOME}/frameworks/locale" append="true">
<include name="{locale}"/>
</library-path>
<library-path dir="${basedir}/${libpath}" append="true">
<include name="*.swc"/>
</library-path>
<library-path dir="${basedir}/${liboutputfolder}" append="true">
<include name="*.swc"/>
</library-path>
<library-path dir="${basedir}/${libpath}/ext" append="true">
<include name="*.swc"/>
</library-path>
<verbose-stacktraces>true</verbose-stacktraces>
</mxmlc>
</target>
<target name="do-test">
<exec executable="${FLEX_HOME}/bin/adl" failonerror="true">
<arg value="${basedir}/bin/AirExecutorApp-app.xml"/>
</exec>
</target>
<target name="test" depends="compile-test, do-test">
</target>
</project>

View File

@ -0,0 +1,8 @@
package com.wordnik.client.model {
public class FacetValue {
public var value: String = null;
public var count: Number = 0;
}
}

View File

@ -0,0 +1,40 @@
package {{package}} {
{{#imports}}import {{import}};
{{/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}}
public function toString(): String {
var str: String = "{{classname}}: ";
{{#vars}}
str += " ({{name}}: " + {{name}} + ")";
{{/vars}}
return str;
}
}
{{/model}}
{{/models}}
}

View File

@ -0,0 +1,23 @@
package {{package}} {
import com.wordnik.swagger.common.ListWrapper;
{{#imports}}import {{import}};
{{/imports}}
{{#models}}
{{#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}};
}
}
{{/model}}
{{/models}}
}

View File

@ -0,0 +1,3 @@
{{#isBodyParam}}<div class="param">{{paramName}} {{^required}}(optional){{/required}}{{#required}}(required){{/required}}</div>
<div class="param-desc"><span class="param-type">Body Parameter</span> &mdash; {{description}} {{#defaultValue}}default: {{{defaultValue}}}{{/defaultValue}}</div>{{/isBodyParam}}

Some files were not shown because too many files have changed in this diff Show More