Code reformatting

This commit is contained in:
Ron 2015-06-07 11:56:08 -04:00
parent 22d7db2cb4
commit 1c2d0656b0
732 changed files with 61242 additions and 55773 deletions

View File

@ -1,4 +1,4 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" <project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent> <parent>
<groupId>io.swagger</groupId> <groupId>io.swagger</groupId>
@ -16,12 +16,12 @@
<build> <build>
<finalName>swagger-codegen-cli</finalName> <finalName>swagger-codegen-cli</finalName>
<resources> <resources>
<resource> <resource>
<directory>src/main/resources</directory> <directory>src/main/resources</directory>
<excludes> <excludes>
<exclude>logback.xml</exclude> <exclude>logback.xml</exclude>
</excludes> </excludes>
</resource> </resource>
</resources> </resources>
<plugins> <plugins>
<plugin> <plugin>
@ -62,7 +62,8 @@
</goals> </goals>
<configuration> <configuration>
<transformers> <transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/> <transformer
implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/>
</transformers> </transformers>
</configuration> </configuration>
</execution> </execution>

View File

@ -1,17 +1,17 @@
package io.swagger.codegen; package io.swagger.codegen;
import io.airlift.airline.Cli;
import io.airlift.airline.Help;
import io.swagger.codegen.cmd.ConfigHelp; import io.swagger.codegen.cmd.ConfigHelp;
import io.swagger.codegen.cmd.Generate; import io.swagger.codegen.cmd.Generate;
import io.swagger.codegen.cmd.Langs; import io.swagger.codegen.cmd.Langs;
import io.swagger.codegen.cmd.Meta; import io.swagger.codegen.cmd.Meta;
import io.airlift.airline.Cli;
import io.airlift.airline.Help;
/** /**
* User: lanwen * User: lanwen
* Date: 24.03.15 * Date: 24.03.15
* Time: 17:56 * Time: 17:56
* * <p/>
* Command line interface for swagger codegen * Command line interface for swagger codegen
* use `swagger-codegen-cli.jar help` for more info * use `swagger-codegen-cli.jar help` for more info
* *

View File

@ -1,33 +1,24 @@
package io.swagger.codegen.cmd; package io.swagger.codegen.cmd;
import io.swagger.codegen.CliOption;
import io.swagger.codegen.CodegenConfig;
import io.airlift.airline.Command; import io.airlift.airline.Command;
import io.airlift.airline.Option; import io.airlift.airline.Option;
import io.swagger.codegen.CliOption;
import io.swagger.codegen.CodegenConfig;
import java.util.ServiceLoader; import java.util.ServiceLoader;
import static java.util.ServiceLoader.load; import static java.util.ServiceLoader.load;
@Command(name = "config-help", description = "Config help for chosen lang") @Command(name = "config-help", description = "Config help for chosen lang")
public class ConfigHelp implements Runnable { public class ConfigHelp implements Runnable {
@Option(name = {"-l", "--lang"}, title = "language", required = true, @Option(name = {"-l", "--lang"}, title = "language", required = true,
description = "language to get config help for") description = "language to get config help for")
private String lang; private String lang;
@Override
public void run() {
System.out.println();
CodegenConfig config = forName(lang);
System.out.println("CONFIG OPTIONS");
for (CliOption langCliOption : config.cliOptions()) {
System.out.println("\t" + langCliOption.getOpt());
System.out.println("\t " + langCliOption.getDescription());
System.out.println();
}
}
/** /**
* Tries to load config class with SPI first, then with class name directly from classpath * Tries to load config class with SPI first, then with class name directly from classpath
*
* @param name name of config, or full qualified class name in classpath * @param name name of config, or full qualified class name in classpath
* @return config class * @return config class
*/ */
@ -46,4 +37,16 @@ public class ConfigHelp implements Runnable {
throw new RuntimeException("Can't load config class with name ".concat(name), e); throw new RuntimeException("Can't load config class with name ".concat(name), e);
} }
} }
@Override
public void run() {
System.out.println();
CodegenConfig config = forName(lang);
System.out.println("CONFIG OPTIONS");
for (CliOption langCliOption : config.cliOptions()) {
System.out.println("\t" + langCliOption.getOpt());
System.out.println("\t " + langCliOption.getDescription());
System.out.println();
}
}
} }

View File

@ -1,15 +1,15 @@
package io.swagger.codegen.cmd; package io.swagger.codegen.cmd;
import config.Config;
import config.ConfigParser;
import io.airlift.airline.Command;
import io.airlift.airline.Option;
import io.swagger.codegen.CliOption; import io.swagger.codegen.CliOption;
import io.swagger.codegen.ClientOptInput; import io.swagger.codegen.ClientOptInput;
import io.swagger.codegen.ClientOpts; import io.swagger.codegen.ClientOpts;
import io.swagger.codegen.CodegenConfig; import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.DefaultGenerator; import io.swagger.codegen.DefaultGenerator;
import io.swagger.models.Swagger; import io.swagger.models.Swagger;
import config.Config;
import config.ConfigParser;
import io.airlift.airline.Command;
import io.airlift.airline.Option;
import io.swagger.parser.SwaggerParser; import io.swagger.parser.SwaggerParser;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -57,15 +57,37 @@ public class Generate implements Runnable {
"Pass in a URL-encoded string of name:header with a comma separating multiple values") "Pass in a URL-encoded string of name:header with a comma separating multiple values")
private String auth; private String auth;
@Option( name= {"-D"}, title = "system properties", description = "sets specified system properties in " + @Option(name = {"-D"}, title = "system properties", description = "sets specified system properties in " +
"the format of name=value,name=value") "the format of name=value,name=value")
private String systemProperties; private String systemProperties;
@Option( name= {"-c", "--config"}, title = "configuration file", description = "Path to json configuration file. " + @Option(name = {"-c", "--config"}, title = "configuration file", description = "Path to json configuration file. " +
"File content should be in a json format {\"optionKey\":\"optionValue\", \"optionKey1\":\"optionValue1\"...} " + "File content should be in a json format {\"optionKey\":\"optionValue\", \"optionKey1\":\"optionValue1\"...} " +
"Supported options can be different for each language. Run config-help -l {lang} command for language specific config options.") "Supported options can be different for each language. Run config-help -l {lang} command for language specific config options.")
private String configFile; private String configFile;
/**
* Tries to load config class with SPI first, then with class name directly from classpath
*
* @param name name of config, or full qualified class name in classpath
* @return config class
*/
private static CodegenConfig forName(String name) {
ServiceLoader<CodegenConfig> loader = load(CodegenConfig.class);
for (CodegenConfig config : loader) {
if (config.getName().equals(name)) {
return config;
}
}
// else try to load directly
try {
return (CodegenConfig) Class.forName(name).newInstance();
} catch (Exception e) {
throw new RuntimeException("Can't load config class with name ".concat(name), e);
}
}
@Override @Override
public void run() { public void run() {
verbosed(verbose); verbosed(verbose);
@ -84,13 +106,13 @@ public class Generate implements Runnable {
if (null != templateDir) { if (null != templateDir) {
config.additionalProperties().put(TEMPLATE_DIR_PARAM, new File(templateDir).getAbsolutePath()); config.additionalProperties().put(TEMPLATE_DIR_PARAM, new File(templateDir).getAbsolutePath());
} }
if(null != configFile){ if (null != configFile) {
Config genConfig = ConfigParser.read(configFile); Config genConfig = ConfigParser.read(configFile);
if (null != genConfig) { if (null != genConfig) {
for (CliOption langCliOption : config.cliOptions()) { for (CliOption langCliOption : config.cliOptions()) {
if (genConfig.hasOption(langCliOption.getOpt())) { if (genConfig.hasOption(langCliOption.getOpt())) {
config.additionalProperties().put(langCliOption.getOpt(), genConfig.getOption(langCliOption.getOpt())); config.additionalProperties().put(langCliOption.getOpt(), genConfig.getOption(langCliOption.getOpt()));
} }
} }
} }
@ -103,11 +125,11 @@ public class Generate implements Runnable {
} }
private void setSystemProperties() { private void setSystemProperties() {
if( systemProperties != null && systemProperties.length() > 0 ){ if (systemProperties != null && systemProperties.length() > 0) {
for( String property : systemProperties.split(",")) { for (String property : systemProperties.split(",")) {
int ix = property.indexOf('='); int ix = property.indexOf('=');
if( ix > 0 && ix < property.length()-1 ){ if (ix > 0 && ix < property.length() - 1) {
System.setProperty( property.substring(0, ix), property.substring(ix+1) ); System.setProperty(property.substring(0, ix), property.substring(ix + 1));
} }
} }
} }
@ -115,6 +137,7 @@ public class Generate implements Runnable {
/** /**
* If true parameter, adds system properties which enables debug mode in generator * If true parameter, adds system properties which enables debug mode in generator
*
* @param verbose - if true, enables debug mode * @param verbose - if true, enables debug mode
*/ */
private void verbosed(boolean verbose) { private void verbosed(boolean verbose) {
@ -132,25 +155,4 @@ public class Generate implements Runnable {
System.setProperty("debugOperations", ""); System.setProperty("debugOperations", "");
System.setProperty("debugSupportingFiles", ""); System.setProperty("debugSupportingFiles", "");
} }
/**
* Tries to load config class with SPI first, then with class name directly from classpath
* @param name name of config, or full qualified class name in classpath
* @return config class
*/
private static CodegenConfig forName(String name) {
ServiceLoader<CodegenConfig> loader = load(CodegenConfig.class);
for (CodegenConfig config : loader) {
if (config.getName().equals(name)) {
return config;
}
}
// else try to load directly
try {
return (CodegenConfig) Class.forName(name).newInstance();
} catch (Exception e) {
throw new RuntimeException("Can't load config class with name ".concat(name), e);
}
}
} }

View File

@ -1,8 +1,8 @@
package io.swagger.codegen.cmd; package io.swagger.codegen.cmd;
import ch.lambdaj.collection.LambdaIterable; import ch.lambdaj.collection.LambdaIterable;
import io.swagger.codegen.CodegenConfig;
import io.airlift.airline.Command; import io.airlift.airline.Command;
import io.swagger.codegen.CodegenConfig;
import static ch.lambdaj.Lambda.on; import static ch.lambdaj.Lambda.on;
import static ch.lambdaj.collection.LambdaCollections.with; import static ch.lambdaj.collection.LambdaCollections.with;

View File

@ -4,10 +4,10 @@ import ch.lambdaj.function.convert.Converter;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import com.samskivert.mustache.Mustache; import com.samskivert.mustache.Mustache;
import io.swagger.codegen.DefaultGenerator;
import io.swagger.codegen.SupportingFile;
import io.airlift.airline.Command; import io.airlift.airline.Command;
import io.airlift.airline.Option; import io.airlift.airline.Option;
import io.swagger.codegen.DefaultGenerator;
import io.swagger.codegen.SupportingFile;
import org.apache.commons.io.FileUtils; import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger; import org.slf4j.Logger;
@ -81,8 +81,9 @@ public class Meta implements Runnable {
/** /**
* Converter method to process supporting files: execute with mustache, * Converter method to process supporting files: execute with mustache,
* or simply copy to destination directory * or simply copy to destination directory
*
* @param targetDir - destination directory * @param targetDir - destination directory
* @param data - map with additional params needed to process templates * @param data - map with additional params needed to process templates
* @return converter object to pass to lambdaj * @return converter object to pass to lambdaj
*/ */
private Converter<SupportingFile, File> processFiles(final File targetDir, final Map<String, Object> data) { private Converter<SupportingFile, File> processFiles(final File targetDir, final Map<String, Object> data) {
@ -121,6 +122,7 @@ public class Meta implements Runnable {
/** /**
* Creates mustache loader for template using classpath loader * Creates mustache loader for template using classpath loader
*
* @param generator - class with reader getter * @param generator - class with reader getter
* @return loader for template * @return loader for template
*/ */
@ -135,6 +137,7 @@ public class Meta implements Runnable {
/** /**
* Converts package name to path on file system * Converts package name to path on file system
*
* @param packageName - package name to convert * @param packageName - package name to convert
* @return relative path * @return relative path
*/ */

View File

@ -1,12 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<configuration> <configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<layout class="ch.qos.logback.classic.PatternLayout"> <layout class="ch.qos.logback.classic.PatternLayout">
<Pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</Pattern> <Pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</Pattern>
</layout> </layout>
</appender> </appender>
<logger name="io.swagger" level="debug"/> <logger name="io.swagger" level="debug"/>
<root level="error"> <root level="error">
<appender-ref ref="STDOUT" /> <appender-ref ref="STDOUT"/>
</root> </root>
</configuration> </configuration>

View File

@ -1,356 +1,357 @@
<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"> <project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
<parent> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<groupId>io.swagger</groupId> <parent>
<artifactId>swagger-codegen-project</artifactId> <groupId>io.swagger</groupId>
<version>2.1.1</version> <artifactId>swagger-codegen-project</artifactId>
<relativePath>../..</relativePath> <version>2.1.1</version>
</parent> <relativePath>../..</relativePath>
<modelVersion>4.0.0</modelVersion> </parent>
<artifactId>swagger-codegen</artifactId> <modelVersion>4.0.0</modelVersion>
<packaging>jar</packaging> <artifactId>swagger-codegen</artifactId>
<name>swagger-codegen (core library)</name> <packaging>jar</packaging>
<build> <name>swagger-codegen (core library)</name>
<sourceDirectory>src/main/java</sourceDirectory> <build>
<defaultGoal>install</defaultGoal> <sourceDirectory>src/main/java</sourceDirectory>
<resources> <defaultGoal>install</defaultGoal>
<resource> <resources>
<directory>src/main/resources</directory> <resource>
<excludes> <directory>src/main/resources</directory>
<exclude>logback.xml</exclude> <excludes>
</excludes> <exclude>logback.xml</exclude>
</resource> </excludes>
</resources> </resource>
<extensions> </resources>
<extension> <extensions>
<groupId>org.jvnet.wagon-svn</groupId> <extension>
<artifactId>wagon-svn</artifactId> <groupId>org.jvnet.wagon-svn</groupId>
<version>1.8</version> <artifactId>wagon-svn</artifactId>
</extension> <version>1.8</version>
<extension> </extension>
<groupId>org.apache.maven.wagon</groupId> <extension>
<artifactId>wagon-ssh-external</artifactId> <groupId>org.apache.maven.wagon</groupId>
<version>1.0-alpha-6</version> <artifactId>wagon-ssh-external</artifactId>
</extension> <version>1.0-alpha-6</version>
<extension> </extension>
<groupId>org.apache.maven.wagon</groupId> <extension>
<artifactId>wagon-webdav</artifactId> <groupId>org.apache.maven.wagon</groupId>
<version>1.0-beta-1</version> <artifactId>wagon-webdav</artifactId>
</extension> <version>1.0-beta-1</version>
</extensions> </extension>
<directory>target</directory> </extensions>
<finalName>${project.artifactId}-${project.version}</finalName> <directory>target</directory>
<plugins> <finalName>${project.artifactId}-${project.version}</finalName>
<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>io.swagger.codegen.Codegen</mainClass>
</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>
<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>io.swagger</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> <plugins>
<plugin> <plugin>
<groupId>net.alchim31.maven</groupId> <groupId>org.codehaus.mojo</groupId>
<artifactId>scala-maven-plugin</artifactId> <artifactId>exec-maven-plugin</artifactId>
<executions> <version>1.3.2</version>
<execution> <executions>
<goals> <execution>
<goal>compile</goal> <goals>
<goal>testCompile</goal> <goal>java</goal>
</goals> </goals>
</execution> </execution>
</executions> </executions>
<configuration>
<scala-version>${scala-version}</scala-version>
</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> <configuration>
<sources> <mainClass>io.swagger.codegen.Codegen</mainClass>
<source>src/main/scala</source>
</sources>
</configuration> </configuration>
</execution> </plugin>
</executions> <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>
<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>io.swagger</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> </plugins>
</build> <pluginManagement>
</profile> <plugins>
<profile> <plugin>
<id>release-sign-artifacts</id> <groupId>net.alchim31.maven</groupId>
<activation> <artifactId>scala-maven-plugin</artifactId>
<property> <version>${scala-maven-plugin-version}</version>
<name>performRelease</name> </plugin>
<value>true</value> <plugin>
</property> <groupId>org.apache.maven.plugins</groupId>
</activation> <artifactId>maven-gpg-plugin</artifactId>
<build> <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>
<scala-version>${scala-version}</scala-version>
</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> <plugins>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-gpg-plugin</artifactId> <artifactId>maven-javadoc-plugin</artifactId>
<executions> <version>2.9</version>
<execution> <configuration>
<id>sign-artifacts</id> <aggregate>true</aggregate>
<phase>verify</phase> <debug>true</debug>
<goals> <links>
<goal>sign</goal> <link>http://java.sun.com/javaee/5/docs/api</link>
</goals> <link>http://java.sun.com/j2se/1.5.0/docs/api</link>
</execution> </links>
</executions> <excludePackageNames/>
</plugin> </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> </plugins>
</build> </reporting>
</profile> <dependencies>
</profiles> <dependency>
<reporting> <groupId>io.swagger</groupId>
<outputDirectory>target/site</outputDirectory> <artifactId>swagger-parser</artifactId>
<plugins> <version>${swagger-parser-version}</version>
<plugin> <scope>compile</scope>
<groupId>org.apache.maven.plugins</groupId> </dependency>
<artifactId>maven-javadoc-plugin</artifactId> <dependency>
<version>2.9</version> <groupId>io.swagger</groupId>
<configuration> <artifactId>swagger-compat-spec-parser</artifactId>
<aggregate>true</aggregate> <version>${swagger-parser-version}</version>
<debug>true</debug> </dependency>
<links> <dependency>
<link>http://java.sun.com/javaee/5/docs/api</link> <groupId>${project.groupId}</groupId>
<link>http://java.sun.com/j2se/1.5.0/docs/api</link> <artifactId>swagger-core</artifactId>
</links> <version>${swagger-core-version}</version>
<excludePackageNames /> </dependency>
</configuration> <dependency>
</plugin> <groupId>com.samskivert</groupId>
<plugin> <artifactId>jmustache</artifactId>
<groupId>net.alchim31.maven</groupId> <version>${jmustache-version}</version>
<artifactId>scala-maven-plugin</artifactId> </dependency>
<version>${scala-maven-plugin-version}</version> <dependency>
</plugin> <groupId>commons-io</groupId>
<plugin> <artifactId>commons-io</artifactId>
<groupId>org.apache.maven.plugins</groupId> <version>${commons-io-version}</version>
<artifactId>maven-jxr-plugin</artifactId> </dependency>
<version>2.3</version> <dependency>
<configuration> <groupId>org.apache.maven</groupId>
<aggregate>true</aggregate> <artifactId>maven-plugin-tools-api</artifactId>
</configuration> <version>2.0</version>
</plugin> </dependency>
<plugin> <dependency>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.felix</groupId>
<artifactId>maven-project-info-reports-plugin</artifactId> <artifactId>maven-bundle-plugin</artifactId>
<version>2.6</version> <version>${felix-version}</version>
<reportSets> </dependency>
<reportSet> <dependency>
<reports> <groupId>org.slf4j</groupId>
<report>project-team</report> <artifactId>slf4j-ext</artifactId>
</reports> <version>${slf4j-version}</version>
</reportSet> </dependency>
</reportSets> <dependency>
</plugin> <groupId>org.slf4j</groupId>
</plugins> <artifactId>slf4j-api</artifactId>
</reporting> <version>${slf4j-version}</version>
<dependencies> </dependency>
<dependency> <dependency>
<groupId>io.swagger</groupId> <groupId>commons-lang</groupId>
<artifactId>swagger-parser</artifactId> <artifactId>commons-lang</artifactId>
<version>${swagger-parser-version}</version> <version>${commons-lang-version}</version>
<scope>compile</scope> </dependency>
</dependency> <dependency>
<dependency> <groupId>commons-cli</groupId>
<groupId>io.swagger</groupId> <artifactId>commons-cli</artifactId>
<artifactId>swagger-compat-spec-parser</artifactId> <version>${commons-cli-version}</version>
<version>${swagger-parser-version}</version> </dependency>
</dependency> <dependency>
<dependency> <groupId>org.scalatest</groupId>
<groupId>${project.groupId}</groupId> <artifactId>scalatest_2.11</artifactId>
<artifactId>swagger-core</artifactId> <version>${scala-test-version}</version>
<version>${swagger-core-version}</version> <scope>test</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.samskivert</groupId> <groupId>org.scala-lang</groupId>
<artifactId>jmustache</artifactId> <artifactId>scala-library</artifactId>
<version>${jmustache-version}</version> <version>${scala-version}</version>
</dependency> <scope>test</scope>
<dependency> </dependency>
<groupId>commons-io</groupId> </dependencies>
<artifactId>commons-io</artifactId> <repositories>
<version>${commons-io-version}</version> <repository>
</dependency> <id>sonatype-snapshots</id>
<dependency> <url>https://oss.sonatype.org/content/repositories/snapshots</url>
<groupId>org.apache.maven</groupId> <snapshots>
<artifactId>maven-plugin-tools-api</artifactId> <enabled>true</enabled>
<version>2.0</version> </snapshots>
</dependency> </repository>
<dependency> </repositories>
<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>
<dependency>
<groupId>org.scala-lang</groupId>
<artifactId>scala-library</artifactId>
<version>${scala-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> </project>

View File

@ -1,33 +1,34 @@
package config; package config;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
public class Config { public class Config {
private Map<String, String> options; private Map<String, String> options;
public Config() { public Config() {
this.options = new HashMap<String, String>(); this.options = new HashMap<String, String>();
} }
public Config(Map<String, String> properties) { public Config(Map<String, String> properties) {
this.options = properties; this.options = properties;
} }
public Map<String, String> getOptions() { public Map<String, String> getOptions() {
return ImmutableMap.copyOf(options); return ImmutableMap.copyOf(options);
} }
public boolean hasOption(String opt){ public boolean hasOption(String opt) {
return options.containsKey(opt); return options.containsKey(opt);
} }
public String getOption(String opt){ public String getOption(String opt) {
return options.get(opt); return options.get(opt);
} }
public void setOption(String opt, String value){ public void setOption(String opt, String value) {
options.put(opt, value); options.put(opt, value);
} }
} }

View File

@ -2,40 +2,39 @@ package config;
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.File; import java.io.File;
import java.util.Iterator; import java.util.Iterator;
import java.util.Map; import java.util.Map;
public class ConfigParser { public class ConfigParser {
public static Config read(String location) { public static Config read(String location) {
System.out.println("reading config from " + location); System.out.println("reading config from " + location);
ObjectMapper mapper = new ObjectMapper(); ObjectMapper mapper = new ObjectMapper();
Config config = new Config(); Config config = new Config();
try { try {
JsonNode rootNode = mapper.readTree(new File(location)); JsonNode rootNode = mapper.readTree(new File(location));
Iterator<Map.Entry<String, JsonNode>> optionNodes = rootNode.fields(); Iterator<Map.Entry<String, JsonNode>> optionNodes = rootNode.fields();
while (optionNodes.hasNext()) { while (optionNodes.hasNext()) {
Map.Entry<String, JsonNode> optionNode = (Map.Entry<String, JsonNode>) optionNodes.next(); Map.Entry<String, JsonNode> optionNode = (Map.Entry<String, JsonNode>) optionNodes.next();
if(optionNode.getValue().isValueNode()){ if (optionNode.getValue().isValueNode()) {
config.setOption(optionNode.getKey(), optionNode.getValue().asText()); config.setOption(optionNode.getKey(), optionNode.getValue().asText());
} else {
System.out.println("omitting non-value node " + optionNode.getKey());
}
}
} catch (Exception e) {
System.out.println(e.getMessage());
return null;
} }
else{
System.out.println("omitting non-value node " + optionNode.getKey()); return config;
}
}
} }
catch (Exception e) {
System.out.println(e.getMessage());
return null;
}
return config;
}
} }

View File

@ -1,60 +1,69 @@
package io.swagger.codegen; package io.swagger.codegen;
import com.samskivert.mustache.*; import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import java.io.*;
public abstract class AbstractGenerator { public abstract class AbstractGenerator {
public File writeToFile(String filename, String contents) throws IOException { public File writeToFile(String filename, String contents) throws IOException {
System.out.println("writing file " + filename); System.out.println("writing file " + filename);
File output = new File(filename); File output = new File(filename);
if(output.getParent() != null && !new File(output.getParent()).exists()) { if (output.getParent() != null && !new File(output.getParent()).exists()) {
File parent = new File(output.getParent()); File parent = new File(output.getParent());
parent.mkdirs(); parent.mkdirs();
} }
Writer out = new BufferedWriter(new OutputStreamWriter( Writer out = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(output), "UTF-8")); new FileOutputStream(output), "UTF-8"));
out.write(contents); out.write(contents);
out.close(); out.close();
return output; return output;
} }
public String readTemplate(String name) { public String readTemplate(String name) {
try{ try {
Reader reader = getTemplateReader(name); Reader reader = getTemplateReader(name);
if(reader == null) if (reader == null) {
throw new RuntimeException("no file found"); throw new RuntimeException("no file found");
java.util.Scanner s = new java.util.Scanner(reader).useDelimiter("\\A"); }
return s.hasNext() ? s.next() : ""; java.util.Scanner s = new java.util.Scanner(reader).useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
} catch (Exception e) {
e.printStackTrace();
}
throw new RuntimeException("can't load template " + name);
} }
catch(Exception e) {
e.printStackTrace();
}
throw new RuntimeException("can't load template " + name);
}
public Reader getTemplateReader(String name) { public Reader getTemplateReader(String name) {
try{ try {
InputStream is = this.getClass().getClassLoader().getResourceAsStream(getCPResourcePath(name)); InputStream is = this.getClass().getClassLoader().getResourceAsStream(getCPResourcePath(name));
if(is == null) if (is == null) {
is = new FileInputStream(new File(name)); is = new FileInputStream(new File(name));
if(is == null) }
throw new RuntimeException("no file found"); if (is == null) {
return new InputStreamReader(is); throw new RuntimeException("no file found");
}
return new InputStreamReader(is);
} catch (Exception e) {
e.printStackTrace();
}
throw new RuntimeException("can't load template " + name);
} }
catch(Exception e) {
e.printStackTrace();
}
throw new RuntimeException("can't load template " + name);
}
private String getCPResourcePath(String name) { private String getCPResourcePath(String name) {
if (!"/".equals(File.separator)) if (!"/".equals(File.separator)) {
return name.replaceAll(Pattern.quote(File.separator), "/"); return name.replaceAll(Pattern.quote(File.separator), "/");
return name; }
} return name;
}
} }

View File

@ -1,23 +1,23 @@
package io.swagger.codegen; package io.swagger.codegen;
public class CliOption { public class CliOption {
private final String opt; private final String opt;
private String description; private String description;
public CliOption(String opt, String description) { public CliOption(String opt, String description) {
this.opt = opt; this.opt = opt;
this.description = description; this.description = description;
} }
public String getOpt() { public String getOpt() {
return opt; return opt;
} }
public String getDescription() { public String getDescription() {
return description; return description;
} }
public void setDescription(String description) { public void setDescription(String description) {
this.description = description; this.description = description;
} }
} }

View File

@ -1,88 +1,92 @@
package io.swagger.codegen; package io.swagger.codegen;
import io.swagger.codegen.ClientOpts; import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.*;
import io.swagger.models.Swagger; import io.swagger.models.Swagger;
import io.swagger.models.auth.AuthorizationValue; import io.swagger.models.auth.AuthorizationValue;
import java.util.*;
import java.net.URLEncoder;
import java.net.URLDecoder; import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
public class ClientOptInput { public class ClientOptInput {
private ClientOpts opts; protected CodegenConfig config;
private Swagger swagger; private ClientOpts opts;
private List<AuthorizationValue> auths; private Swagger swagger;
protected CodegenConfig config; private List<AuthorizationValue> auths;
public ClientOptInput swagger(Swagger swagger) { public ClientOptInput swagger(Swagger swagger) {
this.setSwagger(swagger); this.setSwagger(swagger);
return this; return this;
}
public ClientOptInput opts(ClientOpts opts) {
this.setOpts(opts);
return this;
}
public void setAuth(String urlEncodedAuthString) {
List<AuthorizationValue> auths = new ArrayList<AuthorizationValue>();
if(urlEncodedAuthString != null && !"".equals(urlEncodedAuthString)) {
String[] parts = urlEncodedAuthString.split(",");
for(String part : parts) {
String[] kvPair = part.split(":");
if(kvPair.length == 2) {
auths.add(new AuthorizationValue(URLDecoder.decode(kvPair[0]), URLDecoder.decode(kvPair[1]), "header"));
}
}
} }
this.auths = auths;
} public ClientOptInput opts(ClientOpts opts) {
public String getAuth() { this.setOpts(opts);
if(auths != null) { return this;
StringBuilder b = new StringBuilder();
for(AuthorizationValue v : auths) {
try {
if(b.toString().length() > 0)
b.append(",");
b.append(URLEncoder.encode(v.getKeyName(), "UTF-8"))
.append(":")
.append(URLEncoder.encode(v.getValue(), "UTF-8"));
}
catch (Exception e) {
// continue
e.printStackTrace();
}
}
return b.toString();
} }
else
return null;
}
public List<AuthorizationValue> getAuthorizationValues() {
return auths;
}
public CodegenConfig getConfig() { public String getAuth() {
return config; if (auths != null) {
} StringBuilder b = new StringBuilder();
public void setConfig(CodegenConfig config) { for (AuthorizationValue v : auths) {
this.config = config; try {
} if (b.toString().length() > 0) {
b.append(",");
}
b.append(URLEncoder.encode(v.getKeyName(), "UTF-8"))
.append(":")
.append(URLEncoder.encode(v.getValue(), "UTF-8"));
} catch (Exception e) {
// continue
e.printStackTrace();
}
}
return b.toString();
} else {
return null;
}
}
public void setOpts(ClientOpts opts) { public void setAuth(String urlEncodedAuthString) {
this.opts = opts; List<AuthorizationValue> auths = new ArrayList<AuthorizationValue>();
} if (urlEncodedAuthString != null && !"".equals(urlEncodedAuthString)) {
String[] parts = urlEncodedAuthString.split(",");
for (String part : parts) {
String[] kvPair = part.split(":");
if (kvPair.length == 2) {
auths.add(new AuthorizationValue(URLDecoder.decode(kvPair[0]), URLDecoder.decode(kvPair[1]), "header"));
}
}
}
this.auths = auths;
}
public ClientOpts getOpts() { public List<AuthorizationValue> getAuthorizationValues() {
return opts; return auths;
} }
public void setSwagger(Swagger swagger) { public CodegenConfig getConfig() {
this.swagger = swagger; return config;
} }
@ApiModelProperty(dataType="Object") public void setConfig(CodegenConfig config) {
public Swagger getSwagger() { this.config = config;
return swagger; }
}
public ClientOpts getOpts() {
return opts;
}
public void setOpts(ClientOpts opts) {
this.opts = opts;
}
@ApiModelProperty(dataType = "Object")
public Swagger getSwagger() {
return swagger;
}
public void setSwagger(Swagger swagger) {
this.swagger = swagger;
}
} }

View File

@ -1,52 +1,57 @@
package io.swagger.codegen; package io.swagger.codegen;
import io.swagger.codegen.auth.*; import io.swagger.codegen.auth.AuthMethod;
import java.util.*; import java.util.HashMap;
import java.util.Map;
public class ClientOpts { public class ClientOpts {
protected String uri; protected String uri;
protected String target; protected String target;
protected AuthMethod auth; protected AuthMethod auth;
protected Map<String, String> properties = new HashMap<String, String>(); protected Map<String, String> properties = new HashMap<String, String>();
protected String outputDirectory; protected String outputDirectory;
public String getUri() { public String getUri() {
return uri; return uri;
} }
public void setUri(String uri) {
this.uri = uri;
}
public String getTarget() { public void setUri(String uri) {
return target; this.uri = uri;
} }
public void setTarget(String target) {
this.target = target;
}
public Map<String, String> getProperties() { public String getTarget() {
return properties; return target;
} }
public void setProperties(Map<String, String> properties) {
this.properties = properties;
}
public String getOutputDirectory() { public void setTarget(String target) {
return outputDirectory; this.target = target;
} }
public void setOutputDirectory(String outputDirectory) {
this.outputDirectory = outputDirectory;
}
@Override public Map<String, String> getProperties() {
public String toString() { return properties;
StringBuilder sb = new StringBuilder(); }
sb.append("ClientOpts: {\n");
sb.append(" uri: ").append(uri).append(","); public void setProperties(Map<String, String> properties) {
sb.append(" auth: ").append(auth).append(","); this.properties = properties;
sb.append(properties); }
sb.append("}");
return sb.toString(); 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

@ -1,16 +1,19 @@
package io.swagger.codegen; package io.swagger.codegen;
import io.swagger.codegen.languages.*;
import io.swagger.models.Swagger; import io.swagger.models.Swagger;
import io.swagger.models.auth.AuthorizationValue;
import io.swagger.util.*;
import io.swagger.parser.SwaggerParser; import io.swagger.parser.SwaggerParser;
import org.apache.commons.cli.BasicParser;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.*; import java.util.ArrayList;
import java.util.HashMap;
import java.io.File; import java.util.Iterator;
import java.util.*; import java.util.List;
import java.util.Map;
import java.util.ServiceLoader;
/** /**
* @deprecated use instead {@link io.swagger.codegen.DefaultGenerator} * @deprecated use instead {@link io.swagger.codegen.DefaultGenerator}
@ -18,126 +21,128 @@ import java.util.*;
*/ */
@Deprecated @Deprecated
public class Codegen extends DefaultGenerator { public class Codegen extends DefaultGenerator {
static Map<String, CodegenConfig> configs = new HashMap<String, CodegenConfig>(); static Map<String, CodegenConfig> configs = new HashMap<String, CodegenConfig>();
static String configString; static String configString;
static { static String debugInfoOptions = "\nThe following additional debug options are available for all codegen targets:" +
List<CodegenConfig> extensions = getExtensions(); "\n -DdebugSwagger prints the swagger specification as interpreted by the codegen" +
StringBuilder sb = new StringBuilder(); "\n -DdebugModels prints models passed to the template engine" +
"\n -DdebugOperations prints operations passed to the template engine" +
"\n -DdebugSupportingFiles prints additional data passed to the template engine";
for(CodegenConfig config : extensions) { public static void main(String[] args) {
if(sb.toString().length() != 0)
sb.append(", ");
sb.append(config.getName());
configs.put(config.getName(), config);
configString = sb.toString();
}
}
static String debugInfoOptions = "\nThe following additional debug options are available for all codegen targets:" + StringBuilder sb = new StringBuilder();
"\n -DdebugSwagger prints the swagger specification as interpreted by the codegen" +
"\n -DdebugModels prints models passed to the template engine" +
"\n -DdebugOperations prints operations passed to the template engine" +
"\n -DdebugSupportingFiles prints additional data passed to the template engine";
public static void main(String[] args) {
StringBuilder sb = new StringBuilder(); Options options = new Options();
options.addOption("h", "help", false, "shows this message");
options.addOption("l", "lang", true, "client language to generate.\nAvailable languages include:\n\t[" + configString + "]");
options.addOption("o", "output", true, "where to write the generated files");
options.addOption("i", "input-spec", true, "location of the swagger spec, as URL or file");
options.addOption("t", "template-dir", true, "folder containing the template files");
options.addOption("d", "debug-info", false, "prints additional info for debugging");
options.addOption("a", "auth", true, "adds authorization headers when fetching the swagger definitions remotely. Pass in a URL-encoded string of name:header with a comma separating multiple values");
Options options = new Options(); ClientOptInput clientOptInput = new ClientOptInput();
options.addOption("h", "help", false, "shows this message"); ClientOpts clientOpts = new ClientOpts();
options.addOption("l", "lang", true, "client language to generate.\nAvailable languages include:\n\t[" + configString + "]"); Swagger swagger = null;
options.addOption("o", "output", true, "where to write the generated files");
options.addOption("i", "input-spec", true, "location of the swagger spec, as URL or file");
options.addOption("t", "template-dir", true, "folder containing the template files");
options.addOption("d", "debug-info", false, "prints additional info for debugging");
options.addOption("a", "auth", true, "adds authorization headers when fetching the swagger definitions remotely. Pass in a URL-encoded string of name:header with a comma separating multiple values");
ClientOptInput clientOptInput = new ClientOptInput(); CommandLine cmd = null;
ClientOpts clientOpts = new ClientOpts(); try {
Swagger swagger = null; CommandLineParser parser = new BasicParser();
CodegenConfig config = null;
CommandLine cmd = null; cmd = parser.parse(options, args);
try { if (cmd.hasOption("d")) {
CommandLineParser parser = new BasicParser(); usage(options);
CodegenConfig config = null; System.out.println(debugInfoOptions);
return;
cmd = parser.parse(options, args); }
if (cmd.hasOption("d")) { if (cmd.hasOption("a")) {
usage(options); clientOptInput.setAuth(cmd.getOptionValue("a"));
System.out.println(debugInfoOptions); }
return; if (cmd.hasOption("l")) {
} clientOptInput.setConfig(getConfig(cmd.getOptionValue("l")));
if (cmd.hasOption("a")) } else {
clientOptInput.setAuth(cmd.getOptionValue("a")); usage(options);
if (cmd.hasOption("l")) return;
clientOptInput.setConfig(getConfig(cmd.getOptionValue("l"))); }
else { if (cmd.hasOption("o")) {
usage(options); clientOptInput.getConfig().setOutputDir(cmd.getOptionValue("o"));
return; }
} if (cmd.hasOption("h")) {
if (cmd.hasOption("o")) if (cmd.hasOption("l")) {
clientOptInput.getConfig().setOutputDir(cmd.getOptionValue("o")); config = getConfig(String.valueOf(cmd.getOptionValue("l")));
if (cmd.hasOption("h")) { if (config != null) {
if(cmd.hasOption("l")) { options.addOption("h", "help", true, config.getHelp());
config = getConfig(String.valueOf(cmd.getOptionValue("l"))); usage(options);
if(config != null) { return;
options.addOption("h", "help", true, config.getHelp()); }
}
usage(options);
return;
}
if (cmd.hasOption("i")) {
swagger = new SwaggerParser().read(cmd.getOptionValue("i"), clientOptInput.getAuthorizationValues(), true);
}
if (cmd.hasOption("t")) {
clientOpts.getProperties().put("templateDir", String.valueOf(cmd.getOptionValue("t")));
}
} catch (Exception e) {
usage(options); usage(options);
return; return;
}
} }
usage(options); try {
return; clientOptInput
} .opts(clientOpts)
if (cmd.hasOption("i")) .swagger(swagger);
swagger = new SwaggerParser().read(cmd.getOptionValue("i"), clientOptInput.getAuthorizationValues(), true); new Codegen().opts(clientOptInput).generate();
if (cmd.hasOption("t")) } catch (Exception e) {
clientOpts.getProperties().put("templateDir", String.valueOf(cmd.getOptionValue("t"))); e.printStackTrace();
}
} }
catch (Exception e) {
usage(options);
return;
}
try{
clientOptInput
.opts(clientOpts)
.swagger(swagger);
new Codegen().opts(clientOptInput).generate();
}
catch (Exception e) {
e.printStackTrace();
}
}
public static List<CodegenConfig> getExtensions() { public static List<CodegenConfig> getExtensions() {
ServiceLoader<CodegenConfig> loader = ServiceLoader.load(CodegenConfig.class); ServiceLoader<CodegenConfig> loader = ServiceLoader.load(CodegenConfig.class);
List<CodegenConfig> output = new ArrayList<CodegenConfig>(); List<CodegenConfig> output = new ArrayList<CodegenConfig>();
Iterator<CodegenConfig> itr = loader.iterator(); Iterator<CodegenConfig> itr = loader.iterator();
while(itr.hasNext()) { while (itr.hasNext()) {
output.add(itr.next()); output.add(itr.next());
}
return output;
} }
return output;
}
static void usage(Options options) { static void usage(Options options) {
HelpFormatter formatter = new HelpFormatter(); HelpFormatter formatter = new HelpFormatter();
formatter.printHelp( "Codegen", options ); formatter.printHelp("Codegen", options);
} }
public static CodegenConfig getConfig(String name) { public static CodegenConfig getConfig(String name) {
if(configs.containsKey(name)) { if (configs.containsKey(name)) {
return configs.get(name); return configs.get(name);
} else {
// see if it's a class
try {
System.out.println("loading class " + name);
Class customClass = Class.forName(name);
System.out.println("loaded");
return (CodegenConfig) customClass.newInstance();
} catch (Exception e) {
throw new RuntimeException("can't load class " + name);
}
}
} }
else {
// see if it's a class static {
try { List<CodegenConfig> extensions = getExtensions();
System.out.println("loading class " + name); StringBuilder sb = new StringBuilder();
Class customClass = Class.forName(name);
System.out.println("loaded"); for (CodegenConfig config : extensions) {
return (CodegenConfig)customClass.newInstance(); if (sb.toString().length() != 0) {
} sb.append(", ");
catch (Exception e) { }
throw new RuntimeException("can't load class " + name); sb.append(config.getName());
} configs.put(config.getName(), config);
configString = sb.toString();
}
} }
}
} }

View File

@ -1,64 +1,105 @@
package io.swagger.codegen; package io.swagger.codegen;
import io.swagger.models.*; import io.swagger.models.Model;
import io.swagger.models.Operation;
import io.swagger.models.Swagger;
import io.swagger.models.auth.SecuritySchemeDefinition; import io.swagger.models.auth.SecuritySchemeDefinition;
import io.swagger.models.properties.*; import io.swagger.models.properties.Property;
import java.util.*; import java.util.List;
import java.util.Map;
import java.util.Set;
public interface CodegenConfig { public interface CodegenConfig {
CodegenType getTag(); CodegenType getTag();
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 toApiVarName(String name);
String toModelName(String name);
String toParamName(String name);
String escapeText(String text);
String escapeReservedWord(String name);
String getTypeDeclaration(Property p);
String getTypeDeclaration(String name);
void processOpts();
List<CliOption> cliOptions();
String generateExamplePath(String path, Operation operation);
Set<String> reservedWords(); String getName();
List<SupportingFile> supportingFiles(); String getHelp();
void setOutputDir(String dir); Map<String, Object> additionalProperties();
String getOutputDir();
CodegenModel fromModel(String name, Model model); String apiPackage();
CodegenOperation fromOperation(String resourcePath, String httpMethod, Operation operation, Map<String, Model> definitions);
List<CodegenSecurity> fromSecurity(Map<String, SecuritySchemeDefinition> schemes);
Set<String> defaultIncludes(); String apiFileFolder();
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 fileSuffix();
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);
Map<String, Object> postProcessSupportingFileData(Map<String, Object> objs);
String apiFilename(String templateName, String tag); String outputFolder();
boolean shouldOverwrite(String filename); String templateDir();
String modelFileFolder();
String modelPackage();
String toApiName(String name);
String toApiVarName(String name);
String toModelName(String name);
String toParamName(String name);
String escapeText(String text);
String escapeReservedWord(String name);
String getTypeDeclaration(Property p);
String getTypeDeclaration(String name);
void processOpts();
List<CliOption> cliOptions();
String generateExamplePath(String path, Operation operation);
Set<String> reservedWords();
List<SupportingFile> supportingFiles();
String getOutputDir();
void setOutputDir(String dir);
CodegenModel fromModel(String name, Model model);
CodegenOperation fromOperation(String resourcePath, String httpMethod, Operation operation, Map<String, Model> definitions);
List<CodegenSecurity> fromSecurity(Map<String, SecuritySchemeDefinition> schemes);
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);
Map<String, Object> postProcessSupportingFileData(Map<String, Object> objs);
String apiFilename(String templateName, String tag);
boolean shouldOverwrite(String filename);
} }

View File

@ -1,16 +1,18 @@
package io.swagger.codegen; package io.swagger.codegen;
import io.swagger.models.*; import io.swagger.models.ExternalDocs;
import io.swagger.models.properties.*;
import java.util.*; import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class CodegenModel { public class CodegenModel {
public String parent; public String parent;
public String name, classname, description, classVarName, modelJson; public String name, classname, description, classVarName, modelJson;
public String defaultValue; public String defaultValue;
public List<CodegenProperty> vars = new ArrayList<CodegenProperty>(); public List<CodegenProperty> vars = new ArrayList<CodegenProperty>();
public Set<String> imports = new HashSet<String>(); public Set<String> imports = new HashSet<String>();
public Boolean hasVars, emptyVars, hasMoreModels, hasEnums; public Boolean hasVars, emptyVars, hasMoreModels, hasEnums;
public ExternalDocs externalDocs; public ExternalDocs externalDocs;
} }

View File

@ -5,34 +5,35 @@ import java.util.Map;
public final class CodegenModelFactory { public final class CodegenModelFactory {
private static final Map<CodegenModelType, Class<?>> typeMapping = new HashMap<CodegenModelType, Class<?>>(); private static final Map<CodegenModelType, Class<?>> typeMapping = new HashMap<CodegenModelType, Class<?>>();
/** /**
* Configure a different implementation 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 * @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)) { public static void setTypeMapping(CodegenModelType type, Class<?> implementation) {
throw new IllegalArgumentException(implementation.getSimpleName() + " doesn't extend " + type.getDefaultImplementation().getSimpleName()); if (!type.getDefaultImplementation().isAssignableFrom(implementation)) {
throw new IllegalArgumentException(implementation.getSimpleName() + " doesn't extend " + type.getDefaultImplementation().getSimpleName());
}
try {
implementation.newInstance();
} catch (Exception e) {
throw new IllegalArgumentException(e);
}
typeMapping.put(type, implementation);
} }
try {
implementation.newInstance();
} catch (Exception e) {
throw new IllegalArgumentException(e);
}
typeMapping.put(type, implementation);
}
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public static <T> T newInstance(CodegenModelType type) { public static <T> T newInstance(CodegenModelType type) {
Class<?> classType = typeMapping.get(type); Class<?> classType = typeMapping.get(type);
try { try {
return (T) (classType != null ? classType : type.getDefaultImplementation()).newInstance(); return (T) (classType != null ? classType : type.getDefaultImplementation()).newInstance();
} catch (InstantiationException e) { } catch (InstantiationException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} catch (IllegalAccessException e) { } catch (IllegalAccessException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
}
} }
}
} }

View File

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

View File

@ -1,32 +1,35 @@
package io.swagger.codegen; package io.swagger.codegen;
import io.swagger.models.*; import io.swagger.models.ExternalDocs;
import java.util.*; import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class CodegenOperation { public class CodegenOperation {
public Boolean hasConsumes, hasProduces, hasParams, returnTypeIsPrimitive, public final List<CodegenProperty> responseHeaders = new ArrayList<CodegenProperty>();
returnSimpleType, subresourceOperation, isMapContainer, isListContainer, public Boolean hasConsumes, hasProduces, hasParams, returnTypeIsPrimitive,
hasMore = Boolean.TRUE, isMultipart; returnSimpleType, subresourceOperation, isMapContainer, isListContainer,
public String path, operationId, returnType, httpMethod, returnBaseType, hasMore = Boolean.TRUE, isMultipart;
returnContainer, summary, notes, baseName, defaultResponse; 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<CodegenSecurity> authMethods;
public List<String> tags;
public List<CodegenResponse> responses = new ArrayList<CodegenResponse>();
public Set<String> imports = new HashSet<String>();
public List<Map<String, String>> examples;
public ExternalDocs externalDocs;
public List<Map<String, String>> consumes, produces; // legacy support
public CodegenParameter bodyParam; public String nickname;
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<CodegenSecurity> authMethods;
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

@ -1,41 +1,41 @@
package io.swagger.codegen; package io.swagger.codegen;
public class CodegenParameter { public class CodegenParameter {
public Boolean isFormParam, isQueryParam, isPathParam, isHeaderParam, public Boolean isFormParam, isQueryParam, isPathParam, isHeaderParam,
isCookieParam, isBodyParam, isFile, notFile, hasMore, isContainer, secondaryParam; isCookieParam, isBodyParam, isFile, notFile, hasMore, isContainer, secondaryParam;
public String baseName, paramName, dataType, collectionFormat, description, baseType, defaultValue; public String baseName, paramName, dataType, collectionFormat, description, baseType, defaultValue;
public String jsonSchema; public String jsonSchema;
/** /**
* Determines whether this parameter is mandatory. If the parameter is in "path", * 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 * this property is required and its value MUST be true. Otherwise, the property
* MAY be included and its default value is false. * MAY be included and its default value is false.
*/ */
public Boolean required; public Boolean required;
public CodegenParameter copy() { public CodegenParameter copy() {
CodegenParameter output = new CodegenParameter(); CodegenParameter output = new CodegenParameter();
output.isFile = this.isFile; output.isFile = this.isFile;
output.notFile = this.notFile; output.notFile = this.notFile;
output.hasMore = this.hasMore; output.hasMore = this.hasMore;
output.isContainer = this.isContainer; output.isContainer = this.isContainer;
output.secondaryParam = this.secondaryParam; output.secondaryParam = this.secondaryParam;
output.baseName = this.baseName; output.baseName = this.baseName;
output.paramName = this.paramName; output.paramName = this.paramName;
output.dataType = this.dataType; output.dataType = this.dataType;
output.collectionFormat = this.collectionFormat; output.collectionFormat = this.collectionFormat;
output.description = this.description; output.description = this.description;
output.baseType = this.baseType; output.baseType = this.baseType;
output.isFormParam = this.isFormParam; output.isFormParam = this.isFormParam;
output.isQueryParam = this.isQueryParam; output.isQueryParam = this.isQueryParam;
output.isPathParam = this.isPathParam; output.isPathParam = this.isPathParam;
output.isHeaderParam = this.isHeaderParam; output.isHeaderParam = this.isHeaderParam;
output.isCookieParam = this.isCookieParam; output.isCookieParam = this.isCookieParam;
output.isBodyParam = this.isBodyParam; output.isBodyParam = this.isBodyParam;
output.required = this.required; output.required = this.required;
output.jsonSchema = this.jsonSchema; output.jsonSchema = this.jsonSchema;
output.defaultValue = this.defaultValue; output.defaultValue = this.defaultValue;
return output; return output;
} }
} }

View File

@ -1,28 +1,37 @@
package io.swagger.codegen; package io.swagger.codegen;
import java.util.*; import java.util.List;
import java.util.Map;
public class CodegenProperty { public class CodegenProperty {
public String baseName, complexType, getter, setter, description, datatype, datatypeWithEnum, public String baseName, complexType, getter, setter, description, datatype, datatypeWithEnum,
name, min, max, defaultValue, baseType, containerType; 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; * maxLength validation for strings, see http://json-schema.org/latest/json-schema-validation.html#rfc.section.5.2.1
/** minLength validation for strings, see http://json-schema.org/latest/json-schema-validation.html#rfc.section.5.2.2 */ */
public Integer minLength; public Integer maxLength;
/** pattern validation for strings, see http://json-schema.org/latest/json-schema-validation.html#rfc.section.5.2.3 */ /**
public String pattern; * minLength validation for strings, see http://json-schema.org/latest/json-schema-validation.html#rfc.section.5.2.2
/** A free-form property to include an example of an instance for this schema. */ */
public String example; public Integer minLength;
/**
* pattern validation for strings, see http://json-schema.org/latest/json-schema-validation.html#rfc.section.5.2.3
*/
public String pattern;
/**
* A free-form property to include an example of an instance for this schema.
*/
public String example;
public String jsonSchema; public String jsonSchema;
public Double minimum; public Double minimum;
public Double maximum; public Double maximum;
public Boolean exclusiveMinimum; public Boolean exclusiveMinimum;
public Boolean exclusiveMaximum; public Boolean exclusiveMaximum;
public Boolean hasMore = null, required = null, secondaryParam = null; public Boolean hasMore = null, required = null, secondaryParam = null;
public Boolean isPrimitiveType, isContainer, isNotContainer; public Boolean isPrimitiveType, isContainer, isNotContainer;
public boolean isEnum; public boolean isEnum;
public List<String> _enum; public List<String> _enum;
public Map<String, Object> allowableValues; public Map<String, Object> allowableValues;
} }

View File

@ -5,17 +5,20 @@ import java.util.List;
import java.util.Map; import java.util.Map;
public class CodegenResponse { public class CodegenResponse {
public String code, message; public final List<CodegenProperty> headers = new ArrayList<CodegenProperty>();
public Boolean hasMore; public String code, message;
public List<Map<String, Object>> examples; public Boolean hasMore;
public final List<CodegenProperty> headers = new ArrayList<CodegenProperty>(); public List<Map<String, Object>> examples;
public String dataType, baseType, containerType; public String dataType, baseType, containerType;
public Boolean isDefault; public Boolean isDefault;
public Boolean simpleType; public Boolean simpleType;
public Boolean primitiveType; public Boolean primitiveType;
public Boolean isMapContainer; public Boolean isMapContainer;
public Boolean isListContainer; public Boolean isListContainer;
public Object schema; public Object schema;
public String jsonSchema; public String jsonSchema;
public boolean isWildcard() { return "0".equals(code) || "default".equals(code); }
public boolean isWildcard() {
return "0".equals(code) || "default".equals(code);
}
} }

View File

@ -1,10 +1,10 @@
package io.swagger.codegen; package io.swagger.codegen;
public class CodegenSecurity { public class CodegenSecurity {
public String name; public String name;
public String type; public String type;
public Boolean hasMore, isBasic, isOAuth, isApiKey; public Boolean hasMore, isBasic, isOAuth, isApiKey;
// ApiKey specific // ApiKey specific
public String keyParamName; public String keyParamName;
public Boolean isKeyInQuery, isKeyInHeader; public Boolean isKeyInQuery, isKeyInHeader;
} }

View File

@ -1,34 +1,36 @@
package io.swagger.codegen; package io.swagger.codegen;
import com.fasterxml.jackson.annotation.*; import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;
import java.util.Map;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map;
public enum CodegenType { public enum CodegenType {
CLIENT, SERVER, DOCUMENTATION, OTHER; CLIENT, SERVER, DOCUMENTATION, OTHER;
private static Map<String, CodegenType> names = new HashMap<String, CodegenType>(); private static Map<String, CodegenType> names = new HashMap<String, CodegenType>();
static { @JsonCreator
names.put("client", CLIENT); public static CodegenType forValue(String value) {
names.put("server", SERVER); return names.get(value.toLowerCase());
names.put("documentation", DOCUMENTATION);
names.put("other", OTHER);
}
@JsonCreator
public static CodegenType forValue(String value) {
return names.get(value.toLowerCase());
}
@JsonValue
public String toValue() {
for (Map.Entry<String, CodegenType> entry : names.entrySet()) {
if (entry.getValue() == this)
return entry.getKey();
} }
return null; // or fail @JsonValue
} public String toValue() {
for (Map.Entry<String, CodegenType> entry : names.entrySet()) {
if (entry.getValue() == this) {
return entry.getKey();
}
}
return null; // or fail
}
static {
names.put("client", CLIENT);
names.put("server", SERVER);
names.put("documentation", DOCUMENTATION);
names.put("other", OTHER);
}
} }

View File

@ -11,17 +11,14 @@ import io.swagger.models.Path;
import io.swagger.models.Swagger; import io.swagger.models.Swagger;
import io.swagger.models.auth.SecuritySchemeDefinition; import io.swagger.models.auth.SecuritySchemeDefinition;
import io.swagger.util.Json; import io.swagger.util.Json;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils; import org.apache.commons.io.IOUtils;
import java.io.File; import java.io.File;
import java.io.Reader;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
@ -35,453 +32,453 @@ import static org.apache.commons.lang3.StringUtils.capitalize;
import static org.apache.commons.lang3.StringUtils.isNotEmpty; import static org.apache.commons.lang3.StringUtils.isNotEmpty;
public class DefaultGenerator extends AbstractGenerator implements Generator { public class DefaultGenerator extends AbstractGenerator implements Generator {
protected CodegenConfig config; protected CodegenConfig config;
protected ClientOptInput opts = null; protected ClientOptInput opts = null;
protected Swagger swagger = null; protected Swagger swagger = null;
public Generator opts(ClientOptInput opts) { public Generator opts(ClientOptInput opts) {
this.opts = opts; this.opts = opts;
this.swagger = opts.getSwagger(); this.swagger = opts.getSwagger();
this.config = opts.getConfig(); this.config = opts.getConfig();
this.config.additionalProperties().putAll(opts.getOpts().getProperties()); this.config.additionalProperties().putAll(opts.getOpts().getProperties());
return this; return this;
}
public List<File> generate() {
if (swagger == null || config == null) {
throw new RuntimeException("missing swagger input or config!");
} }
if (System.getProperty("debugSwagger") != null) {
Json.prettyPrint(swagger); public List<File> generate() {
} if (swagger == null || config == null) {
List<File> files = new ArrayList<File>(); throw new RuntimeException("missing swagger input or config!");
try {
config.processOpts();
if (swagger.getInfo() != null) {
Info info = swagger.getInfo();
if (info.getTitle() != null) {
config.additionalProperties().put("appName", info.getTitle());
} }
if (info.getVersion() != null) { if (System.getProperty("debugSwagger") != null) {
config.additionalProperties().put("appVersion", info.getVersion()); Json.prettyPrint(swagger);
} }
if (info.getDescription() != null) { List<File> files = new ArrayList<File>();
config.additionalProperties().put("appDescription", try {
config.escapeText(info.getDescription())); config.processOpts();
} if (swagger.getInfo() != null) {
if (info.getContact() != null) { Info info = swagger.getInfo();
Contact contact = info.getContact(); if (info.getTitle() != null) {
config.additionalProperties().put("infoUrl", contact.getUrl()); config.additionalProperties().put("appName", info.getTitle());
if (contact.getEmail() != null) { }
config.additionalProperties().put("infoEmail", contact.getEmail()); if (info.getVersion() != null) {
} config.additionalProperties().put("appVersion", info.getVersion());
} }
if (info.getLicense() != null) { if (info.getDescription() != null) {
License license = info.getLicense(); config.additionalProperties().put("appDescription",
if (license.getName() != null) { config.escapeText(info.getDescription()));
config.additionalProperties().put("licenseInfo", license.getName()); }
} if (info.getContact() != null) {
if (license.getUrl() != null) { Contact contact = info.getContact();
config.additionalProperties().put("licenseUrl", license.getUrl()); config.additionalProperties().put("infoUrl", contact.getUrl());
} if (contact.getEmail() != null) {
} config.additionalProperties().put("infoEmail", contact.getEmail());
if (info.getVersion() != null) {
config.additionalProperties().put("version", info.getVersion());
}
}
StringBuilder hostBuilder = new StringBuilder();
String scheme;
if (swagger.getSchemes() != null && swagger.getSchemes().size() > 0) {
scheme = swagger.getSchemes().get(0).toValue();
} else {
scheme = "https";
}
hostBuilder.append(scheme);
hostBuilder.append("://");
if (swagger.getHost() != null) {
hostBuilder.append(swagger.getHost());
} else {
hostBuilder.append("localhost");
}
if (swagger.getBasePath() != null) {
hostBuilder.append(swagger.getBasePath());
} else {
hostBuilder.append("/");
}
String contextPath = swagger.getBasePath() == null ? "/" : swagger.getBasePath();
String basePath = hostBuilder.toString();
List<Object> allOperations = new ArrayList<Object>();
List<Object> allModels = new ArrayList<Object>();
// models
Map<String, Model> definitions = swagger.getDefinitions();
if (definitions != null) {
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));
files.add(new File(filename));
}
}
}
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("contextPath", contextPath);
operation.put("baseName", tag);
operation.put("modelPackage", config.modelPackage());
operation.putAll(config.additionalProperties());
operation.put("classname", config.toApiName(tag));
operation.put("classVarName", config.toApiVarName(tag));
operation.put("importPath", config.toApiImport(tag));
processMimeTypes(swagger.getConsumes(), operation, "consumes");
processMimeTypes(swagger.getProduces(), operation, "produces");
allOperations.add(new HashMap<String, Object>(operation));
for (int i = 0; i < allOperations.size(); i++) {
Map<String, Object> oo = (Map<String, Object>) allOperations.get(i);
if (i < (allOperations.size() - 1)) {
oo.put("hasMore", "true");
}
}
for (String templateName : config.apiTemplateFiles().keySet()) {
String filename = config.apiFilename( templateName, tag );
if( new File( filename ).exists() && !config.shouldOverwrite( filename )){
continue;
}
String template = readTemplate(config.templateDir() + File.separator + templateName);
Template tmpl = Mustache.compiler()
.withLoader(new Mustache.TemplateLoader() {
public Reader getTemplate(String name) {
return getTemplateReader(config.templateDir() + File.separator + name + ".mustache");
} }
}) }
.defaultValue("") if (info.getLicense() != null) {
.compile(template); License license = info.getLicense();
if (license.getName() != null) {
writeToFile(filename, tmpl.execute(operation)); config.additionalProperties().put("licenseInfo", license.getName());
files.add(new File(filename));
}
}
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.getHost() != null) {
bundle.put("host", swagger.getHost());
}
bundle.put("basePath", basePath);
bundle.put("scheme", scheme);
bundle.put("contextPath", contextPath);
bundle.put("apiInfo", apis);
bundle.put("models", allModels);
bundle.put("apiFolder", config.apiPackage().replace('.', File.separatorChar));
bundle.put("modelPackage", config.modelPackage());
bundle.put("authMethods", config.fromSecurity(swagger.getSecurityDefinitions()));
if (swagger.getExternalDocs() != null) {
bundle.put("externalDocs", swagger.getExternalDocs());
}
for (int i = 0; i < allModels.size() - 1; i++) {
HashMap<String, CodegenModel> cm = (HashMap<String, CodegenModel>) allModels.get(i);
CodegenModel m = cm.get("model");
m.hasMoreModels = true;
}
config.postProcessSupportingFileData(bundle);
if (System.getProperty("debugSupportingFiles") != null) {
System.out.println("############ Supporting file info ############");
Json.prettyPrint(bundle);
}
for (SupportingFile support : config.supportingFiles()) {
String outputFolder = config.outputFolder();
if (isNotEmpty(support.folder)) {
outputFolder += File.separator + support.folder;
}
File of = new File(outputFolder);
if (!of.isDirectory()) {
of.mkdirs();
}
String outputFilename = outputFolder + File.separator + support.destinationFilename;
if (support.templateFile.endsWith("mustache")) {
String template = readTemplate(config.templateDir() + File.separator + support.templateFile);
Template tmpl = Mustache.compiler()
.withLoader(new Mustache.TemplateLoader() {
public Reader getTemplate(String name) {
return getTemplateReader(config.templateDir() + File.separator + name + ".mustache");
} }
}) if (license.getUrl() != null) {
.defaultValue("") config.additionalProperties().put("licenseUrl", license.getUrl());
.compile(template); }
}
if (info.getVersion() != null) {
config.additionalProperties().put("version", info.getVersion());
}
}
writeToFile(outputFilename, tmpl.execute(bundle)); StringBuilder hostBuilder = new StringBuilder();
files.add(new File(outputFilename)); String scheme;
} else { if (swagger.getSchemes() != null && swagger.getSchemes().size() > 0) {
InputStream in = null; scheme = swagger.getSchemes().get(0).toValue();
} else {
scheme = "https";
}
hostBuilder.append(scheme);
hostBuilder.append("://");
if (swagger.getHost() != null) {
hostBuilder.append(swagger.getHost());
} else {
hostBuilder.append("localhost");
}
if (swagger.getBasePath() != null) {
hostBuilder.append(swagger.getBasePath());
} else {
hostBuilder.append("/");
}
String contextPath = swagger.getBasePath() == null ? "/" : swagger.getBasePath();
String basePath = hostBuilder.toString();
try {
in = new FileInputStream(config.templateDir() + File.separator + support.templateFile);
}
catch (Exception e) {
// continue
}
if(in == null) {
in = this.getClass().getClassLoader().getResourceAsStream(config.templateDir() + File.separator + support.templateFile);
}
File outputFile = new File(outputFilename);
OutputStream out = new FileOutputStream(outputFile, false);
if(in != null && out != null)
IOUtils.copy(in,out);
else {
if(in == null)
System.out.println("can't open " + config.templateDir() + File.separator + support.templateFile + " for input");
if(out == null)
System.out.println("can't open " + outputFile + " for output");
}
files.add(outputFile); List<Object> allOperations = new ArrayList<Object>();
List<Object> allModels = new ArrayList<Object>();
// models
Map<String, Model> definitions = swagger.getDefinitions();
if (definitions != null) {
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));
files.add(new File(filename));
}
}
}
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("contextPath", contextPath);
operation.put("baseName", tag);
operation.put("modelPackage", config.modelPackage());
operation.putAll(config.additionalProperties());
operation.put("classname", config.toApiName(tag));
operation.put("classVarName", config.toApiVarName(tag));
operation.put("importPath", config.toApiImport(tag));
processMimeTypes(swagger.getConsumes(), operation, "consumes");
processMimeTypes(swagger.getProduces(), operation, "produces");
allOperations.add(new HashMap<String, Object>(operation));
for (int i = 0; i < allOperations.size(); i++) {
Map<String, Object> oo = (Map<String, Object>) allOperations.get(i);
if (i < (allOperations.size() - 1)) {
oo.put("hasMore", "true");
}
}
for (String templateName : config.apiTemplateFiles().keySet()) {
String filename = config.apiFilename(templateName, tag);
if (new File(filename).exists() && !config.shouldOverwrite(filename)) {
continue;
}
String template = readTemplate(config.templateDir() + File.separator + templateName);
Template tmpl = Mustache.compiler()
.withLoader(new Mustache.TemplateLoader() {
public Reader getTemplate(String name) {
return getTemplateReader(config.templateDir() + File.separator + name + ".mustache");
}
})
.defaultValue("")
.compile(template);
writeToFile(filename, tmpl.execute(operation));
files.add(new File(filename));
}
}
if (System.getProperty("debugOperations") != null) {
System.out.println("############ Operation info ############");
Json.prettyPrint(allOperations);
}
// supporting files
Map<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.getHost() != null) {
bundle.put("host", swagger.getHost());
}
bundle.put("basePath", basePath);
bundle.put("scheme", scheme);
bundle.put("contextPath", contextPath);
bundle.put("apiInfo", apis);
bundle.put("models", allModels);
bundle.put("apiFolder", config.apiPackage().replace('.', File.separatorChar));
bundle.put("modelPackage", config.modelPackage());
bundle.put("authMethods", config.fromSecurity(swagger.getSecurityDefinitions()));
if (swagger.getExternalDocs() != null) {
bundle.put("externalDocs", swagger.getExternalDocs());
}
for (int i = 0; i < allModels.size() - 1; i++) {
HashMap<String, CodegenModel> cm = (HashMap<String, CodegenModel>) allModels.get(i);
CodegenModel m = cm.get("model");
m.hasMoreModels = true;
}
config.postProcessSupportingFileData(bundle);
if (System.getProperty("debugSupportingFiles") != null) {
System.out.println("############ Supporting file info ############");
Json.prettyPrint(bundle);
}
for (SupportingFile support : config.supportingFiles()) {
String outputFolder = config.outputFolder();
if (isNotEmpty(support.folder)) {
outputFolder += File.separator + support.folder;
}
File of = new File(outputFolder);
if (!of.isDirectory()) {
of.mkdirs();
}
String outputFilename = outputFolder + File.separator + support.destinationFilename;
if (support.templateFile.endsWith("mustache")) {
String template = readTemplate(config.templateDir() + File.separator + support.templateFile);
Template tmpl = Mustache.compiler()
.withLoader(new Mustache.TemplateLoader() {
public Reader getTemplate(String name) {
return getTemplateReader(config.templateDir() + File.separator + name + ".mustache");
}
})
.defaultValue("")
.compile(template);
writeToFile(outputFilename, tmpl.execute(bundle));
files.add(new File(outputFilename));
} else {
InputStream in = null;
try {
in = new FileInputStream(config.templateDir() + File.separator + support.templateFile);
} catch (Exception e) {
// continue
}
if (in == null) {
in = this.getClass().getClassLoader().getResourceAsStream(config.templateDir() + File.separator + support.templateFile);
}
File outputFile = new File(outputFilename);
OutputStream out = new FileOutputStream(outputFile, false);
if (in != null && out != null) {
IOUtils.copy(in, out);
} else {
if (in == null) {
System.out.println("can't open " + config.templateDir() + File.separator + support.templateFile + " for input");
}
if (out == null) {
System.out.println("can't open " + outputFile + " for output");
}
}
files.add(outputFile);
}
}
config.processSwagger(swagger);
} catch (Exception e) {
e.printStackTrace();
} }
} return files;
config.processSwagger(swagger);
} catch (Exception e) {
e.printStackTrace();
} }
return files;
}
private void processMimeTypes(List<String> mimeTypeList, Map<String, Object> operation, String source) { private void processMimeTypes(List<String> mimeTypeList, Map<String, Object> operation, String source) {
if(mimeTypeList != null && mimeTypeList.size() > 0) { if (mimeTypeList != null && mimeTypeList.size() > 0) {
List<Map<String, String>> c = new ArrayList<Map<String, String>>(); List<Map<String, String>> c = new ArrayList<Map<String, String>>();
int count = 0; int count = 0;
for(String key: mimeTypeList) { for (String key : mimeTypeList) {
Map<String, String> mediaType = new HashMap<String, String>(); Map<String, String> mediaType = new HashMap<String, String>();
mediaType.put("mediaType", key); mediaType.put("mediaType", key);
count += 1; count += 1;
if (count < mimeTypeList.size()) { if (count < mimeTypeList.size()) {
mediaType.put("hasMore", "true"); mediaType.put("hasMore", "true");
} else {
mediaType.put("hasMore", null);
}
c.add(mediaType);
}
operation.put(source, c);
String flagFieldName = "has" + source.substring(0, 1).toUpperCase() + source.substring(1);
operation.put(flagFieldName, true);
} }
else { }
mediaType.put("hasMore", null);
public Map<String, List<CodegenOperation>> processPaths(Map<String, Path> paths) {
Map<String, List<CodegenOperation>> ops = new HashMap<String, List<CodegenOperation>>();
for (String resourcePath : paths.keySet()) {
Path path = paths.get(resourcePath);
processOperation(resourcePath, "get", path.getGet(), ops);
processOperation(resourcePath, "put", path.getPut(), ops);
processOperation(resourcePath, "post", path.getPost(), ops);
processOperation(resourcePath, "delete", path.getDelete(), ops);
processOperation(resourcePath, "patch", path.getPatch(), ops);
processOperation(resourcePath, "options", path.getOptions(), ops);
} }
c.add(mediaType); return ops;
}
operation.put(source, c);
String flagFieldName = "has" + source.substring(0, 1).toUpperCase() + source.substring(1);
operation.put(flagFieldName, true);
} }
}
public Map<String, List<CodegenOperation>> processPaths(Map<String, Path> paths) { public SecuritySchemeDefinition fromSecurity(String name) {
Map<String, List<CodegenOperation>> ops = new HashMap<String, List<CodegenOperation>>(); Map<String, SecuritySchemeDefinition> map = swagger.getSecurityDefinitions();
if (map == null) {
for (String resourcePath : paths.keySet()) { return null;
Path path = paths.get(resourcePath);
processOperation(resourcePath, "get", path.getGet(), ops);
processOperation(resourcePath, "put", path.getPut(), ops);
processOperation(resourcePath, "post", path.getPost(), ops);
processOperation(resourcePath, "delete", path.getDelete(), ops);
processOperation(resourcePath, "patch", path.getPatch(), ops);
processOperation(resourcePath, "options", path.getOptions(), ops);
}
return ops;
}
public SecuritySchemeDefinition fromSecurity(String name) {
Map<String, SecuritySchemeDefinition> map = swagger.getSecurityDefinitions();
if (map == null) {
return null;
}
return map.get(name);
}
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, swagger.getDefinitions());
co.tags = new ArrayList<String>();
co.tags.add(sanitizeTag(tag));
config.addOperationToGroup(sanitizeTag(tag), resourcePath, operation, co, operations);
List<Map<String, List<String>>> securities = operation.getSecurity();
if (securities == null) {
continue;
} }
Map<String, SecuritySchemeDefinition> authMethods = new HashMap<String, SecuritySchemeDefinition>(); return map.get(name);
for (Map<String, List<String>> security : securities) { }
if (security.size() != 1) {
//Not sure what to do
continue; public void processOperation(String resourcePath, String httpMethod, Operation operation, Map<String, List<CodegenOperation>> operations) {
} if (operation != null) {
String securityName = security.keySet().iterator().next(); List<String> tags = operation.getTags();
SecuritySchemeDefinition securityDefinition = fromSecurity(securityName); if (tags == null) {
if (securityDefinition != null) { tags = new ArrayList<String>();
authMethods.put(securityName, securityDefinition); tags.add("default");
} }
for (String tag : tags) {
CodegenOperation co = config.fromOperation(resourcePath, httpMethod, operation, swagger.getDefinitions());
co.tags = new ArrayList<String>();
co.tags.add(sanitizeTag(tag));
config.addOperationToGroup(sanitizeTag(tag), resourcePath, operation, co, operations);
List<Map<String, List<String>>> securities = operation.getSecurity();
if (securities == null) {
continue;
}
Map<String, SecuritySchemeDefinition> authMethods = new HashMap<String, SecuritySchemeDefinition>();
for (Map<String, List<String>> security : securities) {
if (security.size() != 1) {
//Not sure what to do
continue;
}
String securityName = security.keySet().iterator().next();
SecuritySchemeDefinition securityDefinition = fromSecurity(securityName);
if (securityDefinition != null) {
authMethods.put(securityName, securityDefinition);
}
}
if (!authMethods.isEmpty()) {
co.authMethods = config.fromSecurity(authMethods);
}
}
} }
if (!authMethods.isEmpty()) { }
co.authMethods = config.fromSecurity(authMethods);
protected String sanitizeTag(String tag) {
// remove spaces and make strong case
String[] parts = tag.split(" ");
StringBuilder buf = new StringBuilder();
for (String part : parts) {
if (isNotEmpty(part)) {
buf.append(capitalize(part));
}
} }
} return buf.toString().replaceAll("[^a-zA-Z ]", "");
}
}
protected String sanitizeTag(String tag) {
// remove spaces and make strong case
String[] parts = tag.split(" ");
StringBuilder buf = new StringBuilder();
for (String part : parts) {
if (isNotEmpty(part)) {
buf.append(capitalize(part));
}
}
return buf.toString().replaceAll("[^a-zA-Z ]", "");
}
public Map<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));
// check for operationId uniqueness
Set<String> opIds = new HashSet<String>();
int counter = 0;
for(CodegenOperation op : ops) {
String opId = op.nickname;
if(opIds.contains(opId)) {
counter ++;
op.nickname += "_" + counter;
}
opIds.add(opId);
}
objs.put("operation", ops);
operations.put("operations", objs);
operations.put("package", config.apiPackage());
Set<String> allImports = new LinkedHashSet<String>();
for (CodegenOperation op : ops) {
allImports.addAll(op.imports);
} }
List<Map<String, String>> imports = new ArrayList<Map<String, String>>(); public Map<String, Object> processOperations(CodegenConfig config, String tag, List<CodegenOperation> ops) {
for (String nextImport : allImports) { Map<String, Object> operations = new HashMap<String, Object>();
Map<String, String> im = new LinkedHashMap<String, String>(); Map<String, Object> objs = new HashMap<String, Object>();
String mapping = config.importMapping().get(nextImport); objs.put("classname", config.toApiName(tag));
if (mapping == null) {
mapping = config.toModelImport(nextImport); // check for operationId uniqueness
} Set<String> opIds = new HashSet<String>();
if (mapping != null) { int counter = 0;
im.put("import", mapping); for (CodegenOperation op : ops) {
imports.add(im); String opId = op.nickname;
} if (opIds.contains(opId)) {
counter++;
op.nickname += "_" + counter;
}
opIds.add(opId);
}
objs.put("operation", ops);
operations.put("operations", objs);
operations.put("package", config.apiPackage());
Set<String> allImports = new LinkedHashSet<String>();
for (CodegenOperation op : ops) {
allImports.addAll(op.imports);
}
List<Map<String, String>> imports = new ArrayList<Map<String, String>>();
for (String nextImport : allImports) {
Map<String, String> im = new LinkedHashMap<String, String>();
String mapping = config.importMapping().get(nextImport);
if (mapping == null) {
mapping = config.toModelImport(nextImport);
}
if (mapping != null) {
im.put("import", mapping);
imports.add(im);
}
}
operations.put("imports", imports);
config.postProcessOperations(operations);
if (objs.size() > 0) {
List<CodegenOperation> os = (List<CodegenOperation>) objs.get("operation");
if (os != null && os.size() > 0) {
CodegenOperation op = os.get(os.size() - 1);
op.hasMore = null;
}
}
return operations;
} }
operations.put("imports", imports); public Map<String, Object> processModels(CodegenConfig config, Map<String, Model> definitions) {
config.postProcessOperations(operations); Map<String, Object> objs = new HashMap<String, Object>();
if (objs.size() > 0) { objs.put("package", config.modelPackage());
List<CodegenOperation> os = (List<CodegenOperation>) objs.get("operation"); List<Object> models = new ArrayList<Object>();
Set<String> allImports = new LinkedHashSet<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);
mo.put("importPath", config.toModelImport(key));
models.add(mo);
allImports.addAll(cm.imports);
}
objs.put("models", models);
if (os != null && os.size() > 0) { List<Map<String, String>> imports = new ArrayList<Map<String, String>>();
CodegenOperation op = os.get(os.size() - 1); for (String nextImport : allImports) {
op.hasMore = null; Map<String, String> im = new LinkedHashMap<String, String>();
} String mapping = config.importMapping().get(nextImport);
if (mapping == null) {
mapping = config.toModelImport(nextImport);
}
if (mapping != null && !config.defaultIncludes().contains(mapping)) {
im.put("import", mapping);
imports.add(im);
}
// add instantiation types
mapping = config.instantiationTypes().get(nextImport);
if (mapping != null && !config.defaultIncludes().contains(mapping)) {
im.put("import", mapping);
imports.add(im);
}
}
objs.put("imports", imports);
config.postProcessModels(objs);
return objs;
} }
return operations;
}
public Map<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>();
Set<String> allImports = new LinkedHashSet<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);
mo.put("importPath", config.toModelImport(key));
models.add(mo);
allImports.addAll(cm.imports);
}
objs.put("models", models);
List<Map<String, String>> imports = new ArrayList<Map<String, String>>();
for (String nextImport : allImports) {
Map<String, String> im = new LinkedHashMap<String, String>();
String mapping = config.importMapping().get(nextImport);
if (mapping == null) {
mapping = config.toModelImport(nextImport);
}
if (mapping != null && !config.defaultIncludes().contains(mapping)) {
im.put("import", mapping);
imports.add(im);
}
// add instantiation types
mapping = config.instantiationTypes().get(nextImport);
if (mapping != null && !config.defaultIncludes().contains(mapping)) {
im.put("import", mapping);
imports.add(im);
}
}
objs.put("imports", imports);
config.postProcessModels(objs);
return objs;
}
} }

View File

@ -1,11 +1,10 @@
package io.swagger.codegen; package io.swagger.codegen;
import io.swagger.models.Swagger;
import java.io.File; import java.io.File;
import java.util.List; import java.util.List;
public interface Generator { public interface Generator {
Generator opts(ClientOptInput opts); Generator opts(ClientOptInput opts);
List<File> generate();
List<File> generate();
} }

View File

@ -1,20 +1,23 @@
package io.swagger.codegen; package io.swagger.codegen;
import io.swagger.codegen.languages.*; import com.samskivert.mustache.Mustache;
import com.samskivert.mustache.Template;
import io.swagger.models.Swagger; import io.swagger.models.Swagger;
import io.swagger.models.auth.AuthorizationValue; import org.apache.commons.cli.BasicParser;
import io.swagger.util.*; import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import io.swagger.parser.SwaggerParser; import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import com.samskivert.mustache.*;
import org.apache.commons.cli.*;
import org.apache.commons.io.FileUtils; import org.apache.commons.io.FileUtils;
import java.io.File; import java.io.File;
import java.io.Reader; import java.io.Reader;
import java.util.*; import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.ServiceLoader;
/** /**
* @deprecated use instead {@link io.swagger.codegen.DefaultGenerator} * @deprecated use instead {@link io.swagger.codegen.DefaultGenerator}
@ -22,164 +25,172 @@ import java.util.*;
*/ */
@Deprecated @Deprecated
public class MetaGenerator extends AbstractGenerator { public class MetaGenerator extends AbstractGenerator {
static Map<String, CodegenConfig> configs = new HashMap<String, CodegenConfig>(); static Map<String, CodegenConfig> configs = new HashMap<String, CodegenConfig>();
static String configString; static String configString;
static {
List<CodegenConfig> extensions = getExtensions();
StringBuilder sb = new StringBuilder();
for(CodegenConfig config : extensions) { public static void main(String[] args) {
if(sb.toString().length() != 0) new MetaGenerator().generate(args);
sb.append(", ");
sb.append(config.getName());
configs.put(config.getName(), config);
configString = sb.toString();
} }
}
public static void main(String[] args) { public static List<CodegenConfig> getExtensions() {
new MetaGenerator().generate(args); ServiceLoader<CodegenConfig> loader = ServiceLoader.load(CodegenConfig.class);
} List<CodegenConfig> output = new ArrayList<CodegenConfig>();
Iterator<CodegenConfig> itr = loader.iterator();
protected void generate(String[] args) { while (itr.hasNext()) {
StringBuilder sb = new StringBuilder(); output.add(itr.next());
String targetLanguage = null;
String outputFolder = null;
String name = null;
String targetPackage = "io.swagger.codegen";
final String templateDir = "codegen";
Options options = new Options();
options.addOption("h", "help", false, "shows this message");
options.addOption("l", "lang", false, "client language to generate.\nAvailable languages include:\n\t[" + configString + "]");
options.addOption("o", "output", true, "where to write the generated files");
options.addOption("n", "name", true, "the human-readable name of the generator");
options.addOption("p", "package", true, "the package to put the main class into (defaults to io.swagger.codegen");
ClientOptInput clientOptInput = new ClientOptInput();
Swagger swagger = null;
CommandLine cmd = null;
try {
CommandLineParser parser = new BasicParser();
cmd = parser.parse(options, args);
if (cmd.hasOption("h")) {
usage(options);
return;
}
if (cmd.hasOption("n"))
name = cmd.getOptionValue("n");
else {
System.out.println("name is required");
usage(options);
return;
}
if (cmd.hasOption("l"))
targetLanguage = cmd.getOptionValue("l");
if (cmd.hasOption("p"))
targetPackage = cmd.getOptionValue("p");
if (cmd.hasOption("o"))
outputFolder = cmd.getOptionValue("o");
else {
System.out.println("output folder is required");
usage(options);
return;
}
}
catch (Exception e) {
usage(options);
return;
}
System.out.println("writing to folder " + outputFolder);
File outputFolderLocation = new File(outputFolder);
if(!outputFolderLocation.exists())
outputFolderLocation.mkdirs();
File sourceFolder = new File(outputFolder + File.separator + "src/main/java/" + targetPackage.replace('.', File.separatorChar));
if(!sourceFolder.exists())
sourceFolder.mkdirs();
File resourcesFolder = new File(outputFolder + File.separator + "src/main/resources/META-INF/services");
if(!resourcesFolder.exists())
resourcesFolder.mkdirs();
String mainClass = Character.toUpperCase(name.charAt(0)) + name.substring(1) + "Generator";
List<SupportingFile> supportingFiles = new ArrayList<SupportingFile>();
supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml"));
supportingFiles.add(new SupportingFile("generatorClass.mustache",
"src/main/java/" + File.separator + targetPackage.replace('.', File.separatorChar),
mainClass + ".java"));
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
supportingFiles.add(new SupportingFile("api.template", "src/main/resources" + File.separator + name, "api.mustache"));
supportingFiles.add(new SupportingFile("model.template", "src/main/resources" + File.separator + name, "model.mustache"));
supportingFiles.add(new SupportingFile("services.mustache", "src/main/resources/META-INF/services", "io.swagger.codegen.CodegenConfig"));
List<File> files = new ArrayList<File>();
Map<String, Object> data = new HashMap<String, Object>();
data.put("generatorPackage", targetPackage);
data.put("generatorClass", mainClass);
data.put("name", name);
data.put("fullyQualifiedGeneratorClass", targetPackage + "." + mainClass);
for(SupportingFile support : supportingFiles) {
try {
String destinationFolder = outputFolder;
if(support.folder != null && !"".equals(support.folder))
destinationFolder += File.separator + support.folder;
File of = new File(destinationFolder);
if(!of.isDirectory())
of.mkdirs();
String outputFilename = destinationFolder + File.separator + support.destinationFilename;
if(support.templateFile.endsWith("mustache")) {
String template = readTemplate(templateDir + File.separator + support.templateFile);
Template tmpl = Mustache.compiler()
.withLoader(new Mustache.TemplateLoader() {
public Reader getTemplate (String name) {
return getTemplateReader(templateDir + File.separator + name + ".mustache");
};
})
.defaultValue("")
.compile(template);
writeToFile(outputFilename, tmpl.execute(data));
files.add(new File(outputFilename));
} }
else { return output;
String template = readTemplate(templateDir + File.separator + support.templateFile); }
FileUtils.writeStringToFile(new File(outputFilename), template);
System.out.println("copying file to " + outputFilename); static void usage(Options options) {
files.add(new File(outputFilename)); HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("MetaGenerator. Generator for creating a new template set " +
"and configuration for Codegen. The output will be based on the language you " +
"specify, and includes default templates to include.", options);
}
public static CodegenConfig getConfig(String name) {
if (configs.containsKey(name)) {
return configs.get(name);
} }
} return null;
catch (java.io.IOException e) {
e.printStackTrace();
}
} }
}
public static List<CodegenConfig> getExtensions() { protected void generate(String[] args) {
ServiceLoader<CodegenConfig> loader = ServiceLoader.load(CodegenConfig.class); StringBuilder sb = new StringBuilder();
List<CodegenConfig> output = new ArrayList<CodegenConfig>(); String targetLanguage = null;
Iterator<CodegenConfig> itr = loader.iterator(); String outputFolder = null;
while(itr.hasNext()) { String name = null;
output.add(itr.next()); String targetPackage = "io.swagger.codegen";
final String templateDir = "codegen";
Options options = new Options();
options.addOption("h", "help", false, "shows this message");
options.addOption("l", "lang", false, "client language to generate.\nAvailable languages include:\n\t[" + configString + "]");
options.addOption("o", "output", true, "where to write the generated files");
options.addOption("n", "name", true, "the human-readable name of the generator");
options.addOption("p", "package", true, "the package to put the main class into (defaults to io.swagger.codegen");
ClientOptInput clientOptInput = new ClientOptInput();
Swagger swagger = null;
CommandLine cmd = null;
try {
CommandLineParser parser = new BasicParser();
cmd = parser.parse(options, args);
if (cmd.hasOption("h")) {
usage(options);
return;
}
if (cmd.hasOption("n")) {
name = cmd.getOptionValue("n");
} else {
System.out.println("name is required");
usage(options);
return;
}
if (cmd.hasOption("l")) {
targetLanguage = cmd.getOptionValue("l");
}
if (cmd.hasOption("p")) {
targetPackage = cmd.getOptionValue("p");
}
if (cmd.hasOption("o")) {
outputFolder = cmd.getOptionValue("o");
} else {
System.out.println("output folder is required");
usage(options);
return;
}
} catch (Exception e) {
usage(options);
return;
}
System.out.println("writing to folder " + outputFolder);
File outputFolderLocation = new File(outputFolder);
if (!outputFolderLocation.exists()) {
outputFolderLocation.mkdirs();
}
File sourceFolder = new File(outputFolder + File.separator + "src/main/java/" + targetPackage.replace('.', File.separatorChar));
if (!sourceFolder.exists()) {
sourceFolder.mkdirs();
}
File resourcesFolder = new File(outputFolder + File.separator + "src/main/resources/META-INF/services");
if (!resourcesFolder.exists()) {
resourcesFolder.mkdirs();
}
String mainClass = Character.toUpperCase(name.charAt(0)) + name.substring(1) + "Generator";
List<SupportingFile> supportingFiles = new ArrayList<SupportingFile>();
supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml"));
supportingFiles.add(new SupportingFile("generatorClass.mustache",
"src/main/java/" + File.separator + targetPackage.replace('.', File.separatorChar),
mainClass + ".java"));
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
supportingFiles.add(new SupportingFile("api.template", "src/main/resources" + File.separator + name, "api.mustache"));
supportingFiles.add(new SupportingFile("model.template", "src/main/resources" + File.separator + name, "model.mustache"));
supportingFiles.add(new SupportingFile("services.mustache", "src/main/resources/META-INF/services", "io.swagger.codegen.CodegenConfig"));
List<File> files = new ArrayList<File>();
Map<String, Object> data = new HashMap<String, Object>();
data.put("generatorPackage", targetPackage);
data.put("generatorClass", mainClass);
data.put("name", name);
data.put("fullyQualifiedGeneratorClass", targetPackage + "." + mainClass);
for (SupportingFile support : supportingFiles) {
try {
String destinationFolder = outputFolder;
if (support.folder != null && !"".equals(support.folder)) {
destinationFolder += File.separator + support.folder;
}
File of = new File(destinationFolder);
if (!of.isDirectory()) {
of.mkdirs();
}
String outputFilename = destinationFolder + File.separator + support.destinationFilename;
if (support.templateFile.endsWith("mustache")) {
String template = readTemplate(templateDir + File.separator + support.templateFile);
Template tmpl = Mustache.compiler()
.withLoader(new Mustache.TemplateLoader() {
public Reader getTemplate(String name) {
return getTemplateReader(templateDir + File.separator + name + ".mustache");
}
;
})
.defaultValue("")
.compile(template);
writeToFile(outputFilename, tmpl.execute(data));
files.add(new File(outputFilename));
} else {
String template = readTemplate(templateDir + File.separator + support.templateFile);
FileUtils.writeStringToFile(new File(outputFilename), template);
System.out.println("copying file to " + outputFilename);
files.add(new File(outputFilename));
}
} catch (java.io.IOException e) {
e.printStackTrace();
}
}
} }
return output;
}
static void usage(Options options) { static {
HelpFormatter formatter = new HelpFormatter(); List<CodegenConfig> extensions = getExtensions();
formatter.printHelp( "MetaGenerator. Generator for creating a new template set " + StringBuilder sb = new StringBuilder();
"and configuration for Codegen. The output will be based on the language you " +
"specify, and includes default templates to include.", options );
}
public static CodegenConfig getConfig(String name) { for (CodegenConfig config : extensions) {
if(configs.containsKey(name)) { if (sb.toString().length() != 0) {
return configs.get(name); sb.append(", ");
}
sb.append(config.getName());
configs.put(config.getName(), config);
configString = sb.toString();
}
} }
return null;
}
} }

View File

@ -1,13 +1,13 @@
package io.swagger.codegen; package io.swagger.codegen;
public class SupportingFile { public class SupportingFile {
public String templateFile; public String templateFile;
public String folder; public String folder;
public String destinationFilename; public String destinationFilename;
public SupportingFile(String templateFile, String folder, String destinationFilename) { public SupportingFile(String templateFile, String folder, String destinationFilename) {
this.templateFile = templateFile; this.templateFile = templateFile;
this.folder = folder; this.folder = folder;
this.destinationFilename = destinationFilename; this.destinationFilename = destinationFilename;
} }
} }

View File

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

View File

@ -1,14 +1,5 @@
package io.swagger.codegen.examples; package io.swagger.codegen.examples;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import io.swagger.models.Model; import io.swagger.models.Model;
import io.swagger.models.ModelImpl; import io.swagger.models.ModelImpl;
import io.swagger.models.properties.ArrayProperty; import io.swagger.models.properties.ArrayProperty;
@ -29,147 +20,139 @@ import io.swagger.models.properties.StringProperty;
import io.swagger.models.properties.UUIDProperty; import io.swagger.models.properties.UUIDProperty;
import io.swagger.util.Json; import io.swagger.util.Json;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class ExampleGenerator { public class ExampleGenerator {
protected Map<String, Model> examples; protected Map<String, Model> examples;
public ExampleGenerator(Map<String, Model> examples) { public ExampleGenerator(Map<String, Model> examples) {
this.examples = examples; this.examples = examples;
} }
public List<Map<String, String>> generate(Map<String, Object> examples, List<String> mediaTypes, Property property) { public List<Map<String, String>> generate(Map<String, Object> examples, List<String> mediaTypes, Property property) {
List<Map<String, String>> output = new ArrayList<Map<String, String>>(); List<Map<String, String>> output = new ArrayList<Map<String, String>>();
Set<String> processedModels = new HashSet<String>(); Set<String> processedModels = new HashSet<String>();
if(examples == null ) { if (examples == null) {
if(mediaTypes == null) { if (mediaTypes == null) {
// assume application/json for this // assume application/json for this
mediaTypes = Arrays.asList("application/json"); mediaTypes = Arrays.asList("application/json");
} }
for(String mediaType : mediaTypes) { for (String mediaType : mediaTypes) {
Map<String, String> kv = new HashMap<String, String>(); Map<String, String> kv = new HashMap<String, String>();
kv.put("contentType", mediaType); kv.put("contentType", mediaType);
if(property != null && mediaType.startsWith("application/json")) { if (property != null && mediaType.startsWith("application/json")) {
String example = Json.pretty(resolvePropertyToExample(mediaType, property, processedModels)); String example = Json.pretty(resolvePropertyToExample(mediaType, property, processedModels));
if(example != null) { if (example != null) {
kv.put("example", example); kv.put("example", example);
output.add(kv); output.add(kv);
} }
} else if (property != null && mediaType.startsWith("application/xml")) {
String example = new XmlExampleGenerator(this.examples).toXml(property);
if (example != null) {
kv.put("example", example);
output.add(kv);
}
}
}
} else {
for (Map.Entry<String, Object> entry : examples.entrySet()) {
final Map<String, String> kv = new HashMap<String, String>();
kv.put("contentType", entry.getKey());
kv.put("example", Json.pretty(entry.getValue()));
output.add(kv);
}
} }
else if(property != null && mediaType.startsWith("application/xml")) { if (output.size() == 0) {
String example = new XmlExampleGenerator(this.examples).toXml(property); Map<String, String> kv = new HashMap<String, String>();
if(example != null) { kv.put("output", "none");
kv.put("example", example);
output.add(kv); output.add(kv);
}
} }
}
}
else {
for(Map.Entry<String, Object> entry: examples.entrySet()) {
final Map<String, String> kv = new HashMap<String, String>();
kv.put("contentType", entry.getKey());
kv.put("example", Json.pretty(entry.getValue()));
output.add(kv);
}
}
if(output.size() == 0) {
Map<String, String> kv = new HashMap<String, String>();
kv.put("output", "none");
output.add(kv);
}
return output;
}
protected Object resolvePropertyToExample(String mediaType, Property property, Set<String> processedModels) {
if(property.getExample() != null) {
return property.getExample();
}
else if(property instanceof StringProperty) {
return "aeiou";
}
else if(property instanceof BooleanProperty) {
return Boolean.TRUE;
}
else if(property instanceof ArrayProperty) {
Property innerType = ((ArrayProperty)property).getItems();
if(innerType != null) {
Object[] output = new Object[]{
resolvePropertyToExample(mediaType, innerType, processedModels)
};
return output; return output;
}
}
else if(property instanceof DateProperty) {
return new java.util.Date(System.currentTimeMillis());
}
else if(property instanceof DateTimeProperty) {
return new java.util.Date(System.currentTimeMillis());
}
else if(property instanceof DecimalProperty) {
return new BigDecimal(1.3579);
}
else if(property instanceof DoubleProperty) {
return new Double(3.149);
}
else if(property instanceof FileProperty) {
return ""; // TODO
}
else if(property instanceof FloatProperty) {
return new Float(1.23);
}
else if(property instanceof IntegerProperty) {
return new Integer(123);
}
else if(property instanceof LongProperty) {
return new Long(123456789);
}
else if(property instanceof MapProperty) {
Map<String, Object> mp = new HashMap<String, Object>();
if(property.getName() != null) {
mp.put(property.getName(),
resolvePropertyToExample(mediaType, ((MapProperty)property).getAdditionalProperties(), processedModels));
}
else {
mp.put("key",
resolvePropertyToExample(mediaType, ((MapProperty)property).getAdditionalProperties(), processedModels));
}
return mp;
}
else if(property instanceof ObjectProperty) {
return "{}";
}
else if(property instanceof RefProperty) {
String simpleName = ((RefProperty)property).getSimpleRef();
Model model = examples.get(simpleName);
if(model != null)
return resolveModelToExample(simpleName, mediaType, model, processedModels);
}
else if(property instanceof UUIDProperty) {
return "046b6c7f-0b8a-43b9-b35d-6489e6daee91";
} }
return ""; protected Object resolvePropertyToExample(String mediaType, Property property, Set<String> processedModels) {
} if (property.getExample() != null) {
return property.getExample();
public Object resolveModelToExample(String name, String mediaType, Model model, Set<String> processedModels) { } else if (property instanceof StringProperty) {
if(processedModels.contains(name)) { return "aeiou";
return ""; } else if (property instanceof BooleanProperty) {
} return Boolean.TRUE;
if(model instanceof ModelImpl) { } else if (property instanceof ArrayProperty) {
processedModels.add(name); Property innerType = ((ArrayProperty) property).getItems();
ModelImpl impl = (ModelImpl) model; if (innerType != null) {
Map<String, Object> values = new HashMap<String, Object>(); Object[] output = new Object[]{
resolvePropertyToExample(mediaType, innerType, processedModels)
if(impl != null && impl.getProperties() != null) { };
for(String propertyName : impl.getProperties().keySet()) { return output;
Property property = impl.getProperties().get(propertyName); }
values.put(propertyName, resolvePropertyToExample(mediaType, property, processedModels)); } else if (property instanceof DateProperty) {
return new java.util.Date(System.currentTimeMillis());
} else if (property instanceof DateTimeProperty) {
return new java.util.Date(System.currentTimeMillis());
} else if (property instanceof DecimalProperty) {
return new BigDecimal(1.3579);
} else if (property instanceof DoubleProperty) {
return new Double(3.149);
} else if (property instanceof FileProperty) {
return ""; // TODO
} else if (property instanceof FloatProperty) {
return new Float(1.23);
} else if (property instanceof IntegerProperty) {
return new Integer(123);
} else if (property instanceof LongProperty) {
return new Long(123456789);
} else if (property instanceof MapProperty) {
Map<String, Object> mp = new HashMap<String, Object>();
if (property.getName() != null) {
mp.put(property.getName(),
resolvePropertyToExample(mediaType, ((MapProperty) property).getAdditionalProperties(), processedModels));
} else {
mp.put("key",
resolvePropertyToExample(mediaType, ((MapProperty) property).getAdditionalProperties(), processedModels));
}
return mp;
} else if (property instanceof ObjectProperty) {
return "{}";
} else if (property instanceof RefProperty) {
String simpleName = ((RefProperty) property).getSimpleRef();
Model model = examples.get(simpleName);
if (model != null) {
return resolveModelToExample(simpleName, mediaType, model, processedModels);
}
} else if (property instanceof UUIDProperty) {
return "046b6c7f-0b8a-43b9-b35d-6489e6daee91";
} }
}
return values; return "";
} }
return ""; public Object resolveModelToExample(String name, String mediaType, Model model, Set<String> processedModels) {
} if (processedModels.contains(name)) {
return "";
}
if (model instanceof ModelImpl) {
processedModels.add(name);
ModelImpl impl = (ModelImpl) model;
Map<String, Object> values = new HashMap<String, Object>();
if (impl != null && impl.getProperties() != null) {
for (String propertyName : impl.getProperties().keySet()) {
Property property = impl.getProperties().get(propertyName);
values.put(propertyName, resolvePropertyToExample(mediaType, property, processedModels));
}
}
return values;
}
return "";
}
} }

View File

@ -1,206 +1,226 @@
package io.swagger.codegen.examples; package io.swagger.codegen.examples;
import io.swagger.util.Json; import io.swagger.models.Model;
import io.swagger.models.*; import io.swagger.models.ModelImpl;
import io.swagger.models.properties.*; import io.swagger.models.RefModel;
import io.swagger.models.Xml;
import java.text.SimpleDateFormat; import io.swagger.models.properties.ArrayProperty;
import java.util.*; import io.swagger.models.properties.BooleanProperty;
import io.swagger.models.properties.DateProperty;
import io.swagger.models.properties.DateTimeProperty;
import io.swagger.models.properties.IntegerProperty;
import io.swagger.models.properties.LongProperty;
import io.swagger.models.properties.Property;
import io.swagger.models.properties.RefProperty;
import io.swagger.models.properties.StringProperty;
import org.codehaus.plexus.util.StringUtils; import org.codehaus.plexus.util.StringUtils;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
public class XmlExampleGenerator { public class XmlExampleGenerator {
public static String NEWLINE = "\n"; public static String NEWLINE = "\n";
public static String TAG_START = "<"; public static String TAG_START = "<";
public static String CLOSE_TAG = ">"; public static String CLOSE_TAG = ">";
public static String TAG_END = "</"; public static String TAG_END = "</";
protected Map<String, Model> examples; private static String EMPTY = "";
protected SimpleDateFormat dtFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); protected Map<String, Model> examples;
protected SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); protected SimpleDateFormat dtFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
private static String EMPTY = ""; protected SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
public XmlExampleGenerator(Map<String, Model> examples) { public XmlExampleGenerator(Map<String, Model> examples) {
this.examples = examples; this.examples = examples;
if(examples == null) if (examples == null) {
examples = new HashMap<String, Model>(); examples = new HashMap<String, Model>();
}
public String toXml(Property property) {
return toXml(null, property, 0, Collections.<String>emptySet());
}
protected String toXml(Model model, int indent, Collection<String> path) {
if(model instanceof RefModel) {
RefModel ref = (RefModel) model;
Model actualModel = examples.get(ref.getSimpleRef());
if(actualModel instanceof ModelImpl)
return modelImplToXml((ModelImpl) actualModel, indent, path);
}
else if(model instanceof ModelImpl) {
return modelImplToXml((ModelImpl) model, indent, path);
}
return null;
}
protected String modelImplToXml(ModelImpl model, int indent, Collection<String> path) {
final String modelName = model.getName();
if (path.contains(modelName)) {
return EMPTY;
}
final Set<String> selfPath = new HashSet<String>(path);
selfPath.add(modelName);
StringBuilder sb = new StringBuilder();
// attributes
Map<String, Property> attributes = new LinkedHashMap<String, Property>();
Map<String, Property> elements = new LinkedHashMap<String, Property>();
String name = modelName;
String namespace;
String prefix;
Boolean wrapped;
Xml xml = model.getXml();
if(xml != null) {
if(xml.getName() != null)
name = xml.getName();
}
for(String pName : model.getProperties().keySet()) {
Property p = model.getProperties().get(pName);
if(p != null && p.getXml() != null && p.getXml().getAttribute() != null && p.getXml().getAttribute())
attributes.put(pName, p);
else
elements.put(pName, p);
}
sb.append(indent(indent)).append(TAG_START);
sb.append(name);
for(String pName : attributes.keySet()) {
Property p = attributes.get(pName);
sb.append(" ").append(pName).append("=").append(quote(toXml(null, p, 0, selfPath)));
}
sb.append(CLOSE_TAG);
sb.append(NEWLINE);
for(String pName : elements.keySet()) {
Property p = elements.get(pName);
final String asXml = toXml(pName, p, indent + 1, selfPath);
if (StringUtils.isEmpty(asXml)) {
continue;
}
sb.append(asXml);
sb.append(NEWLINE);
}
sb.append(indent(indent)).append(TAG_END).append(name).append(CLOSE_TAG);
return sb.toString();
}
protected String quote(String string) {
return "\"" + string + "\"";
}
protected String toXml(String name, Property property, int indent, Collection<String> path) {
if(property == null) {
return "";
}
StringBuilder sb = new StringBuilder();
if(property instanceof ArrayProperty) {
ArrayProperty p = (ArrayProperty) property;
Property inner = p.getItems();
boolean wrapped = false;
if(property.getXml() != null && property.getXml().getWrapped())
wrapped = true;
if(wrapped) {
String prefix = EMPTY;
if(name != null) {
sb.append(indent(indent));
sb.append(openTag(name));
prefix = NEWLINE;
} }
final String asXml = toXml(name, inner, indent + 1, path); }
if (StringUtils.isNotEmpty(asXml)) {
sb.append(prefix).append(asXml); public String toXml(Property property) {
return toXml(null, property, 0, Collections.<String>emptySet());
}
protected String toXml(Model model, int indent, Collection<String> path) {
if (model instanceof RefModel) {
RefModel ref = (RefModel) model;
Model actualModel = examples.get(ref.getSimpleRef());
if (actualModel instanceof ModelImpl) {
return modelImplToXml((ModelImpl) actualModel, indent, path);
}
} else if (model instanceof ModelImpl) {
return modelImplToXml((ModelImpl) model, indent, path);
} }
if(name != null) { return null;
sb.append(NEWLINE); }
sb.append(indent(indent));
sb.append(closeTag(name)); protected String modelImplToXml(ModelImpl model, int indent, Collection<String> path) {
final String modelName = model.getName();
if (path.contains(modelName)) {
return EMPTY;
} }
} final Set<String> selfPath = new HashSet<String>(path);
else selfPath.add(modelName);
sb.append(toXml(name, inner, indent, path));
}
else if(property instanceof RefProperty) {
RefProperty ref = (RefProperty) property;
Model actualModel = examples.get(ref.getSimpleRef());
sb.append(toXml(actualModel, indent, path));
}
else {
if(name != null) {
sb.append(indent(indent));
sb.append(openTag(name));
}
sb.append(getExample(property));
if(name != null)
sb.append(closeTag(name));
}
return sb.toString();
}
protected String getExample(Property property) { StringBuilder sb = new StringBuilder();
if(property instanceof DateTimeProperty) { // attributes
if(property.getExample() != null) Map<String, Property> attributes = new LinkedHashMap<String, Property>();
return property.getExample(); Map<String, Property> elements = new LinkedHashMap<String, Property>();
else
return dtFormat.format(new Date());
}
else if(property instanceof StringProperty) {
if(property.getExample() != null)
return property.getExample();
else
return "string";
}
else if(property instanceof DateProperty) {
if(property.getExample() != null)
return property.getExample();
else
return dateFormat.format(new Date());
}
else if(property instanceof IntegerProperty) {
if(property.getExample() != null)
return property.getExample();
else
return "0";
}
else if(property instanceof BooleanProperty) {
if(property.getExample() != null)
return property.getExample();
else
return "true";
}
else if(property instanceof LongProperty) {
if(property.getExample() != null)
return property.getExample();
else
return "123456";
}
return "not implemented " + property;
}
protected String openTag(String name) { String name = modelName;
return "<" + name + ">"; String namespace;
} String prefix;
Boolean wrapped;
protected String closeTag(String name) { Xml xml = model.getXml();
return "</" + name + ">"; if (xml != null) {
} if (xml.getName() != null) {
name = xml.getName();
}
}
for (String pName : model.getProperties().keySet()) {
Property p = model.getProperties().get(pName);
if (p != null && p.getXml() != null && p.getXml().getAttribute() != null && p.getXml().getAttribute()) {
attributes.put(pName, p);
} else {
elements.put(pName, p);
}
}
sb.append(indent(indent)).append(TAG_START);
sb.append(name);
for (String pName : attributes.keySet()) {
Property p = attributes.get(pName);
sb.append(" ").append(pName).append("=").append(quote(toXml(null, p, 0, selfPath)));
}
sb.append(CLOSE_TAG);
sb.append(NEWLINE);
for (String pName : elements.keySet()) {
Property p = elements.get(pName);
final String asXml = toXml(pName, p, indent + 1, selfPath);
if (StringUtils.isEmpty(asXml)) {
continue;
}
sb.append(asXml);
sb.append(NEWLINE);
}
sb.append(indent(indent)).append(TAG_END).append(name).append(CLOSE_TAG);
protected String indent(int indent) { return sb.toString();
StringBuffer sb = new StringBuffer(); }
for(int i = 0; i < indent; i++) {
sb.append(" "); protected String quote(String string) {
return "\"" + string + "\"";
}
protected String toXml(String name, Property property, int indent, Collection<String> path) {
if (property == null) {
return "";
}
StringBuilder sb = new StringBuilder();
if (property instanceof ArrayProperty) {
ArrayProperty p = (ArrayProperty) property;
Property inner = p.getItems();
boolean wrapped = false;
if (property.getXml() != null && property.getXml().getWrapped()) {
wrapped = true;
}
if (wrapped) {
String prefix = EMPTY;
if (name != null) {
sb.append(indent(indent));
sb.append(openTag(name));
prefix = NEWLINE;
}
final String asXml = toXml(name, inner, indent + 1, path);
if (StringUtils.isNotEmpty(asXml)) {
sb.append(prefix).append(asXml);
}
if (name != null) {
sb.append(NEWLINE);
sb.append(indent(indent));
sb.append(closeTag(name));
}
} else {
sb.append(toXml(name, inner, indent, path));
}
} else if (property instanceof RefProperty) {
RefProperty ref = (RefProperty) property;
Model actualModel = examples.get(ref.getSimpleRef());
sb.append(toXml(actualModel, indent, path));
} else {
if (name != null) {
sb.append(indent(indent));
sb.append(openTag(name));
}
sb.append(getExample(property));
if (name != null) {
sb.append(closeTag(name));
}
}
return sb.toString();
}
protected String getExample(Property property) {
if (property instanceof DateTimeProperty) {
if (property.getExample() != null) {
return property.getExample();
} else {
return dtFormat.format(new Date());
}
} else if (property instanceof StringProperty) {
if (property.getExample() != null) {
return property.getExample();
} else {
return "string";
}
} else if (property instanceof DateProperty) {
if (property.getExample() != null) {
return property.getExample();
} else {
return dateFormat.format(new Date());
}
} else if (property instanceof IntegerProperty) {
if (property.getExample() != null) {
return property.getExample();
} else {
return "0";
}
} else if (property instanceof BooleanProperty) {
if (property.getExample() != null) {
return property.getExample();
} else {
return "true";
}
} else if (property instanceof LongProperty) {
if (property.getExample() != null) {
return property.getExample();
} else {
return "123456";
}
}
return "not implemented " + property;
}
protected String openTag(String name) {
return "<" + name + ">";
}
protected String closeTag(String name) {
return "</" + name + ">";
}
protected String indent(int indent) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < indent; i++) {
sb.append(" ");
}
return sb.toString();
} }
return sb.toString();
}
} }

View File

@ -3,9 +3,26 @@ package io.swagger.codegen.languages;
import com.google.common.base.CaseFormat; import com.google.common.base.CaseFormat;
import com.samskivert.mustache.Mustache; import com.samskivert.mustache.Mustache;
import com.samskivert.mustache.Template; import com.samskivert.mustache.Template;
import io.swagger.codegen.*; import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenOperation;
import io.swagger.codegen.CodegenProperty;
import io.swagger.codegen.CodegenResponse;
import io.swagger.codegen.CodegenSecurity;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile;
import io.swagger.models.auth.SecuritySchemeDefinition; import io.swagger.models.auth.SecuritySchemeDefinition;
import io.swagger.models.properties.*; import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.BooleanProperty;
import io.swagger.models.properties.DateProperty;
import io.swagger.models.properties.DateTimeProperty;
import io.swagger.models.properties.DoubleProperty;
import io.swagger.models.properties.FloatProperty;
import io.swagger.models.properties.IntegerProperty;
import io.swagger.models.properties.LongProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
import io.swagger.models.properties.StringProperty;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -14,352 +31,369 @@ import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.io.StringWriter; import java.io.StringWriter;
import java.io.Writer; import java.io.Writer;
import java.util.*; import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class AkkaScalaClientCodegen extends DefaultCodegen implements CodegenConfig { public class AkkaScalaClientCodegen extends DefaultCodegen implements CodegenConfig {
Logger LOGGER = LoggerFactory.getLogger(AkkaScalaClientCodegen.class); protected String mainPackage = "io.swagger.client";
protected String invokerPackage = mainPackage + ".core";
protected String groupId = "io.swagger";
protected String artifactId = "swagger-client";
protected String artifactVersion = "1.0.0";
protected String sourceFolder = "src/main/scala";
protected String resourcesFolder = "src/main/resources";
protected String configKey = "apiRequest";
protected int defaultTimeoutInMs = 5000;
protected String configKeyPath = mainPackage;
protected boolean registerNonStandardStatusCodes = true;
protected boolean renderJavadoc = true;
protected boolean removeOAuthSecurities = true;
/**
* If set to true, only the default response (the one with le lowest 2XX code) will be considered as a success, and all
* others as ApiErrors.
* If set to false, all responses defined in the model will be considered as a success upon reception. Only http errors,
* unmarshalling problems and any other RuntimeException will be considered as ApiErrors.
*/
protected boolean onlyOneSuccess = true;
Logger LOGGER = LoggerFactory.getLogger(AkkaScalaClientCodegen.class);
protected String mainPackage = "io.swagger.client"; public AkkaScalaClientCodegen() {
super();
outputFolder = "generated-code/scala";
modelTemplateFiles.put("model.mustache", ".scala");
apiTemplateFiles.put("api.mustache", ".scala");
templateDir = "akka-scala";
apiPackage = mainPackage + ".api";
modelPackage = mainPackage + ".model";
protected String invokerPackage = mainPackage + ".core"; reservedWords = new HashSet<String>(
protected String groupId = "io.swagger"; Arrays.asList(
protected String artifactId = "swagger-client"; "abstract", "case", "catch", "class", "def", "do", "else", "extends",
protected String artifactVersion = "1.0.0"; "false", "final", "finally", "for", "forSome", "if", "implicit",
protected String sourceFolder = "src/main/scala"; "import", "lazy", "match", "new", "null", "object", "override", "package",
protected String resourcesFolder = "src/main/resources"; "private", "protected", "return", "sealed", "super", "this", "throw",
protected String configKey = "apiRequest"; "trait", "try", "true", "type", "val", "var", "while", "with", "yield")
protected int defaultTimeoutInMs = 5000; );
protected String configKeyPath = mainPackage;
protected boolean registerNonStandardStatusCodes = true; additionalProperties.put("invokerPackage", invokerPackage);
protected boolean renderJavadoc = true; additionalProperties.put("groupId", groupId);
protected boolean removeOAuthSecurities = true; additionalProperties.put("artifactId", artifactId);
/** additionalProperties.put("artifactVersion", artifactVersion);
* If set to true, only the default response (the one with le lowest 2XX code) will be considered as a success, and all additionalProperties.put("configKey", configKey);
* others as ApiErrors. additionalProperties.put("configKeyPath", configKeyPath);
* If set to false, all responses defined in the model will be considered as a success upon reception. Only http errors, additionalProperties.put("defaultTimeout", defaultTimeoutInMs);
* unmarshalling problems and any other RuntimeException will be considered as ApiErrors. if (renderJavadoc) {
*/ additionalProperties.put("javadocRenderer", new JavadocLambda());
protected boolean onlyOneSuccess = true; }
additionalProperties.put("fnCapitalize", new CapitalizeLambda());
additionalProperties.put("fnCamelize", new CamelizeLambda(false));
additionalProperties.put("fnEnumEntry", new EnumEntryLambda());
additionalProperties.put("onlyOneSuccess", onlyOneSuccess);
public CodegenType getTag() { supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml"));
return CodegenType.CLIENT; supportingFiles.add(new SupportingFile("reference.mustache", resourcesFolder, "reference.conf"));
} final String invokerFolder = (sourceFolder + File.separator + invokerPackage).replace(".", File.separator);
supportingFiles.add(new SupportingFile("apiRequest.mustache", invokerFolder, "ApiRequest.scala"));
supportingFiles.add(new SupportingFile("apiInvoker.mustache", invokerFolder, "ApiInvoker.scala"));
supportingFiles.add(new SupportingFile("requests.mustache", invokerFolder, "requests.scala"));
supportingFiles.add(new SupportingFile("apiSettings.mustache", invokerFolder, "ApiSettings.scala"));
final String apiFolder = (sourceFolder + File.separator + apiPackage).replace(".", File.separator);
supportingFiles.add(new SupportingFile("enumsSerializers.mustache", apiFolder, "EnumsSerializers.scala"));
public String getName() { importMapping.remove("Seq");
return "akka-scala"; importMapping.remove("List");
} importMapping.remove("Set");
importMapping.remove("Map");
public String getHelp() { importMapping.put("DateTime", "org.joda.time.DateTime");
return "Generates a Scala client library base on Akka/Spray.";
}
public AkkaScalaClientCodegen() { typeMapping = new HashMap<String, String>();
super(); typeMapping.put("array", "Seq");
outputFolder = "generated-code/scala"; typeMapping.put("set", "Set");
modelTemplateFiles.put("model.mustache", ".scala"); typeMapping.put("boolean", "Boolean");
apiTemplateFiles.put("api.mustache", ".scala"); typeMapping.put("string", "String");
templateDir = "akka-scala"; typeMapping.put("int", "Int");
apiPackage = mainPackage + ".api"; typeMapping.put("integer", "Int");
modelPackage = mainPackage + ".model"; typeMapping.put("long", "Long");
typeMapping.put("float", "Float");
typeMapping.put("byte", "Byte");
typeMapping.put("short", "Short");
typeMapping.put("char", "Char");
typeMapping.put("long", "Long");
typeMapping.put("double", "Double");
typeMapping.put("object", "Any");
typeMapping.put("file", "File");
typeMapping.put("number", "Double");
reservedWords = new HashSet<String>( languageSpecificPrimitives = new HashSet<String>(
Arrays.asList( Arrays.asList(
"abstract", "case", "catch", "class", "def", "do", "else", "extends", "String",
"false", "final", "finally", "for", "forSome", "if", "implicit", "boolean",
"import", "lazy", "match", "new", "null", "object", "override", "package", "Boolean",
"private", "protected", "return", "sealed", "super", "this", "throw", "Double",
"trait", "try", "true", "type", "val", "var", "while", "with", "yield") "Int",
); "Long",
"Float",
"Object",
"List",
"Seq",
"Map")
);
instantiationTypes.put("array", "ListBuffer");
instantiationTypes.put("map", "Map");
}
additionalProperties.put("invokerPackage", invokerPackage); public CodegenType getTag() {
additionalProperties.put("groupId", groupId); return CodegenType.CLIENT;
additionalProperties.put("artifactId", artifactId); }
additionalProperties.put("artifactVersion", artifactVersion);
additionalProperties.put("configKey", configKey);
additionalProperties.put("configKeyPath", configKeyPath);
additionalProperties.put("defaultTimeout", defaultTimeoutInMs);
if (renderJavadoc)
additionalProperties.put("javadocRenderer", new JavadocLambda());
additionalProperties.put("fnCapitalize", new CapitalizeLambda());
additionalProperties.put("fnCamelize", new CamelizeLambda(false));
additionalProperties.put("fnEnumEntry", new EnumEntryLambda());
additionalProperties.put("onlyOneSuccess", onlyOneSuccess);
supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml")); public String getName() {
supportingFiles.add(new SupportingFile("reference.mustache", resourcesFolder, "reference.conf")); return "akka-scala";
final String invokerFolder = (sourceFolder + File.separator + invokerPackage).replace(".", File.separator); }
supportingFiles.add(new SupportingFile("apiRequest.mustache", invokerFolder, "ApiRequest.scala"));
supportingFiles.add(new SupportingFile("apiInvoker.mustache", invokerFolder, "ApiInvoker.scala"));
supportingFiles.add(new SupportingFile("requests.mustache", invokerFolder, "requests.scala"));
supportingFiles.add(new SupportingFile("apiSettings.mustache", invokerFolder, "ApiSettings.scala"));
final String apiFolder = (sourceFolder + File.separator + apiPackage).replace(".", File.separator);
supportingFiles.add(new SupportingFile("enumsSerializers.mustache", apiFolder, "EnumsSerializers.scala"));
importMapping.remove("Seq"); public String getHelp() {
importMapping.remove("List"); return "Generates a Scala client library base on Akka/Spray.";
importMapping.remove("Set"); }
importMapping.remove("Map");
importMapping.put("DateTime", "org.joda.time.DateTime"); @Override
public String escapeReservedWord(String name) {
return "`" + name + "`";
}
typeMapping = new HashMap<String, String>(); @Override
typeMapping.put("array", "Seq"); public String apiFileFolder() {
typeMapping.put("set", "Set"); return outputFolder + "/" + sourceFolder + "/" + apiPackage().replace('.', File.separatorChar);
typeMapping.put("boolean", "Boolean"); }
typeMapping.put("string", "String");
typeMapping.put("int", "Int");
typeMapping.put("integer", "Int");
typeMapping.put("long", "Long");
typeMapping.put("float", "Float");
typeMapping.put("byte", "Byte");
typeMapping.put("short", "Short");
typeMapping.put("char", "Char");
typeMapping.put("long", "Long");
typeMapping.put("double", "Double");
typeMapping.put("object", "Any");
typeMapping.put("file", "File");
typeMapping.put("number", "Double");
languageSpecificPrimitives = new HashSet<String>( public String modelFileFolder() {
Arrays.asList( return outputFolder + "/" + sourceFolder + "/" + modelPackage().replace('.', File.separatorChar);
"String", }
"boolean",
"Boolean",
"Double",
"Int",
"Long",
"Float",
"Object",
"List",
"Seq",
"Map")
);
instantiationTypes.put("array", "ListBuffer");
instantiationTypes.put("map", "Map");
}
@Override @Override
public String escapeReservedWord(String name) { public Map<String, Object> postProcessOperations(Map<String, Object> objs) {
return "`" + name + "`"; if (registerNonStandardStatusCodes) {
}
@Override
public String apiFileFolder() {
return outputFolder + "/" + sourceFolder + "/" + apiPackage().replace('.', File.separatorChar);
}
public String modelFileFolder() {
return outputFolder + "/" + sourceFolder + "/" + modelPackage().replace('.', File.separatorChar);
}
@Override
public Map<String, Object> postProcessOperations(Map<String, Object> objs) {
if (registerNonStandardStatusCodes) {
try {
@SuppressWarnings("unchecked")
Map<String, ArrayList<CodegenOperation>> opsMap = (Map<String, ArrayList<CodegenOperation>>) objs.get("operations");
HashSet<Integer> unknownCodes = new HashSet<Integer>();
for (CodegenOperation operation : opsMap.get("operation")) {
for (CodegenResponse response : operation.responses) {
if ("default".equals(response.code))
continue;
try { try {
int code = Integer.parseInt(response.code); @SuppressWarnings("unchecked")
if (code >= 600) { Map<String, ArrayList<CodegenOperation>> opsMap = (Map<String, ArrayList<CodegenOperation>>) objs.get("operations");
unknownCodes.add(code); HashSet<Integer> unknownCodes = new HashSet<Integer>();
} for (CodegenOperation operation : opsMap.get("operation")) {
} catch (NumberFormatException e) { for (CodegenResponse response : operation.responses) {
LOGGER.error("Status code is not an integer : response.code", e); if ("default".equals(response.code)) {
continue;
}
try {
int code = Integer.parseInt(response.code);
if (code >= 600) {
unknownCodes.add(code);
}
} catch (NumberFormatException e) {
LOGGER.error("Status code is not an integer : response.code", e);
}
}
}
if (!unknownCodes.isEmpty()) {
additionalProperties.put("unknownStatusCodes", unknownCodes);
}
} catch (Exception e) {
LOGGER.error("Unable to find operations List", e);
} }
}
} }
if (!unknownCodes.isEmpty()) { return super.postProcessOperations(objs);
additionalProperties.put("unknownStatusCodes", unknownCodes); }
@Override
public String getTypeDeclaration(Property p) {
if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]";
} else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
return getSwaggerType(p) + "[String, " + getTypeDeclaration(inner) + "]";
} }
} catch (Exception e) { return super.getTypeDeclaration(p);
LOGGER.error("Unable to find operations List", e);
}
}
return super.postProcessOperations(objs);
}
@Override
public String getTypeDeclaration(Property p) {
if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]";
} else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
return getSwaggerType(p) + "[String, " + getTypeDeclaration(inner) + "]";
}
return super.getTypeDeclaration(p);
}
@Override
public List<CodegenSecurity> fromSecurity(Map<String, SecuritySchemeDefinition> schemes) {
final List<CodegenSecurity> codegenSecurities = super.fromSecurity(schemes);
if (!removeOAuthSecurities)
return codegenSecurities;
// Remove OAuth securities
Iterator<CodegenSecurity> it = codegenSecurities.iterator();
while (it.hasNext()) {
final CodegenSecurity security = it.next();
if (security.isOAuth)
it.remove();
}
// Adapt 'hasMore'
it = codegenSecurities.iterator();
while (it.hasNext()) {
final CodegenSecurity security = it.next();
security.hasMore = it.hasNext();
} }
if (codegenSecurities.isEmpty()) @Override
return null; public List<CodegenSecurity> fromSecurity(Map<String, SecuritySchemeDefinition> schemes) {
return codegenSecurities; final List<CodegenSecurity> codegenSecurities = super.fromSecurity(schemes);
} if (!removeOAuthSecurities) {
return codegenSecurities;
}
@Override // Remove OAuth securities
public String toOperationId(String operationId) { Iterator<CodegenSecurity> it = codegenSecurities.iterator();
return super.toOperationId(CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, operationId)); while (it.hasNext()) {
} final CodegenSecurity security = it.next();
if (security.isOAuth) {
it.remove();
}
}
// Adapt 'hasMore'
it = codegenSecurities.iterator();
while (it.hasNext()) {
final CodegenSecurity security = it.next();
security.hasMore = it.hasNext();
}
private String formatIdentifier(String name, boolean capitalized) { if (codegenSecurities.isEmpty()) {
String identifier = camelize(name, true); return null;
if (capitalized) }
identifier = StringUtils.capitalize(identifier); return codegenSecurities;
if (identifier.matches("[a-zA-Z_$][\\w_$]+") && !reservedWords.contains(identifier)) }
return identifier;
return escapeReservedWord(identifier);
}
@Override @Override
public String toParamName(String name) { return formatIdentifier(name, false); } public String toOperationId(String operationId) {
return super.toOperationId(CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, operationId));
}
@Override private String formatIdentifier(String name, boolean capitalized) {
public String toVarName(String name) { String identifier = camelize(name, true);
return formatIdentifier(name, false); if (capitalized) {
} identifier = StringUtils.capitalize(identifier);
}
if (identifier.matches("[a-zA-Z_$][\\w_$]+") && !reservedWords.contains(identifier)) {
return identifier;
}
return escapeReservedWord(identifier);
}
@Override @Override
public String toEnumName(CodegenProperty property) public String toParamName(String name) {
{ return formatIdentifier(name, false);
return formatIdentifier(property.baseName, true); }
}
@Override @Override
public String getSwaggerType(Property p) { public String toVarName(String name) {
String swaggerType = super.getSwaggerType(p); return formatIdentifier(name, false);
String type; }
if (typeMapping.containsKey(swaggerType)) {
type = typeMapping.get(swaggerType); @Override
if (languageSpecificPrimitives.contains(type)) public String toEnumName(CodegenProperty property) {
return formatIdentifier(property.baseName, true);
}
@Override
public String getSwaggerType(Property p) {
String swaggerType = super.getSwaggerType(p);
String type;
if (typeMapping.containsKey(swaggerType)) {
type = typeMapping.get(swaggerType);
if (languageSpecificPrimitives.contains(type)) {
return toModelName(type);
}
} else {
type = swaggerType;
}
return toModelName(type); return toModelName(type);
} else
type = swaggerType;
return toModelName(type);
}
@Override
public String toInstantiationType(Property p) {
if (p instanceof MapProperty) {
MapProperty ap = (MapProperty) p;
String inner = getSwaggerType(ap.getAdditionalProperties());
return instantiationTypes.get("map") + "[String, " + inner + "]";
} else if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
String inner = getSwaggerType(ap.getItems());
return instantiationTypes.get("array") + "[" + inner + "]";
} else
return null;
}
public String toDefaultValue(Property p) {
if (!p.getRequired())
return "None";
if (p instanceof StringProperty)
return "null";
else if (p instanceof BooleanProperty)
return "null";
else if (p instanceof DateProperty)
return "null";
else if (p instanceof DateTimeProperty)
return "null";
else if (p instanceof DoubleProperty)
return "null";
else if (p instanceof FloatProperty)
return "null";
else if (p instanceof IntegerProperty)
return "null";
else if (p instanceof LongProperty)
return "null";
else if (p instanceof MapProperty) {
MapProperty ap = (MapProperty) p;
String inner = getSwaggerType(ap.getAdditionalProperties());
return "Map[String, " + inner + "].empty ";
} else if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
String inner = getSwaggerType(ap.getItems());
return "Seq[" + inner + "].empty ";
} else
return "null";
}
private static abstract class CustomLambda implements Mustache.Lambda {
@Override
public void execute(Template.Fragment frag, Writer out) throws IOException {
final StringWriter tempWriter = new StringWriter();
frag.execute(tempWriter);
out.write(formatFragment(tempWriter.toString()));
}
public abstract String formatFragment(String fragment);
}
private static class JavadocLambda extends CustomLambda {
@Override
public String formatFragment(String fragment) {
final String[] lines = fragment.split("\\r?\\n");
final StringBuilder sb = new StringBuilder();
sb.append(" /**\n");
for (String line : lines) {
sb.append(" * ").append(line).append("\n");
}
sb.append(" */\n");
return sb.toString();
}
}
private static class CapitalizeLambda extends CustomLambda {
@Override
public String formatFragment(String fragment) {
return StringUtils.capitalize(fragment);
}
}
private static class CamelizeLambda extends CustomLambda {
private final boolean capitalizeFirst;
public CamelizeLambda(boolean capitalizeFirst) {
this.capitalizeFirst = capitalizeFirst;
} }
@Override @Override
public String formatFragment(String fragment) { public String toInstantiationType(Property p) {
return camelize(fragment, !capitalizeFirst); if (p instanceof MapProperty) {
MapProperty ap = (MapProperty) p;
String inner = getSwaggerType(ap.getAdditionalProperties());
return instantiationTypes.get("map") + "[String, " + inner + "]";
} else if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
String inner = getSwaggerType(ap.getItems());
return instantiationTypes.get("array") + "[" + inner + "]";
} else {
return null;
}
} }
}
private class EnumEntryLambda extends CustomLambda { public String toDefaultValue(Property p) {
@Override if (!p.getRequired()) {
public String formatFragment(String fragment) { return "None";
return formatIdentifier(fragment, true); }
if (p instanceof StringProperty) {
return "null";
} else if (p instanceof BooleanProperty) {
return "null";
} else if (p instanceof DateProperty) {
return "null";
} else if (p instanceof DateTimeProperty) {
return "null";
} else if (p instanceof DoubleProperty) {
return "null";
} else if (p instanceof FloatProperty) {
return "null";
} else if (p instanceof IntegerProperty) {
return "null";
} else if (p instanceof LongProperty) {
return "null";
} else if (p instanceof MapProperty) {
MapProperty ap = (MapProperty) p;
String inner = getSwaggerType(ap.getAdditionalProperties());
return "Map[String, " + inner + "].empty ";
} else if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
String inner = getSwaggerType(ap.getItems());
return "Seq[" + inner + "].empty ";
} else {
return "null";
}
}
private static abstract class CustomLambda implements Mustache.Lambda {
@Override
public void execute(Template.Fragment frag, Writer out) throws IOException {
final StringWriter tempWriter = new StringWriter();
frag.execute(tempWriter);
out.write(formatFragment(tempWriter.toString()));
}
public abstract String formatFragment(String fragment);
}
private static class JavadocLambda extends CustomLambda {
@Override
public String formatFragment(String fragment) {
final String[] lines = fragment.split("\\r?\\n");
final StringBuilder sb = new StringBuilder();
sb.append(" /**\n");
for (String line : lines) {
sb.append(" * ").append(line).append("\n");
}
sb.append(" */\n");
return sb.toString();
}
}
private static class CapitalizeLambda extends CustomLambda {
@Override
public String formatFragment(String fragment) {
return StringUtils.capitalize(fragment);
}
}
private static class CamelizeLambda extends CustomLambda {
private final boolean capitalizeFirst;
public CamelizeLambda(boolean capitalizeFirst) {
this.capitalizeFirst = capitalizeFirst;
}
@Override
public String formatFragment(String fragment) {
return camelize(fragment, !capitalizeFirst);
}
}
private class EnumEntryLambda extends CustomLambda {
@Override
public String formatFragment(String fragment) {
return formatIdentifier(fragment, true);
}
} }
}
} }

View File

@ -1,259 +1,265 @@
package io.swagger.codegen.languages; package io.swagger.codegen.languages;
import io.swagger.codegen.*; import io.swagger.codegen.CliOption;
import io.swagger.models.properties.*; import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
import java.util.*;
import java.io.File; import java.io.File;
import java.util.Arrays;
import java.util.HashSet;
public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfig { public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfig {
protected String invokerPackage = "io.swagger.client"; protected String invokerPackage = "io.swagger.client";
protected String groupId = "io.swagger"; protected String groupId = "io.swagger";
protected String artifactId = "swagger-android-client"; protected String artifactId = "swagger-android-client";
protected String artifactVersion = "1.0.0"; protected String artifactVersion = "1.0.0";
protected String projectFolder = "src/main"; protected String projectFolder = "src/main";
protected String sourceFolder = projectFolder + "/java"; protected String sourceFolder = projectFolder + "/java";
protected Boolean useAndroidMavenGradlePlugin = true; protected Boolean useAndroidMavenGradlePlugin = true;
public CodegenType getTag() { public AndroidClientCodegen() {
return CodegenType.CLIENT; super();
} outputFolder = "generated-code/android";
modelTemplateFiles.put("model.mustache", ".java");
apiTemplateFiles.put("api.mustache", ".java");
templateDir = "android-java";
apiPackage = "io.swagger.client.api";
modelPackage = "io.swagger.client.model";
public String getName() { reservedWords = new HashSet<String>(
return "android"; Arrays.asList(
} "abstract", "continue", "for", "new", "switch", "assert",
"default", "if", "package", "synchronized", "boolean", "do", "goto", "private",
"this", "break", "double", "implements", "protected", "throw", "byte", "else",
"import", "public", "throws", "case", "enum", "instanceof", "return", "transient",
"catch", "extends", "int", "short", "try", "char", "final", "interface", "static",
"void", "class", "finally", "long", "strictfp", "volatile", "const", "float",
"native", "super", "while")
);
public String getHelp() { languageSpecificPrimitives = new HashSet<String>(
return "Generates an Android client library."; Arrays.asList(
} "String",
"boolean",
"Boolean",
"Double",
"Integer",
"Long",
"Float",
"Object")
);
instantiationTypes.put("array", "ArrayList");
instantiationTypes.put("map", "HashMap");
public AndroidClientCodegen() { cliOptions.add(new CliOption("invokerPackage", "root package to use for the generated code"));
super(); cliOptions.add(new CliOption("groupId", "groupId for use in the generated build.gradle and pom.xml"));
outputFolder = "generated-code/android"; cliOptions.add(new CliOption("artifactId", "artifactId for use in the generated build.gradle and pom.xml"));
modelTemplateFiles.put("model.mustache", ".java"); cliOptions.add(new CliOption("artifactVersion", "artifact version for use in the generated build.gradle and pom.xml"));
apiTemplateFiles.put("api.mustache", ".java"); cliOptions.add(new CliOption("sourceFolder", "source folder for generated code"));
templateDir = "android-java"; cliOptions.add(new CliOption("useAndroidMavenGradlePlugin", "A flag to toggle android-maven gradle plugin. Default is true."));
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")
);
languageSpecificPrimitives = new HashSet<String>(
Arrays.asList(
"String",
"boolean",
"Boolean",
"Double",
"Integer",
"Long",
"Float",
"Object")
);
instantiationTypes.put("array", "ArrayList");
instantiationTypes.put("map", "HashMap");
cliOptions.add(new CliOption("invokerPackage", "root package to use for the generated code"));
cliOptions.add(new CliOption("groupId", "groupId for use in the generated build.gradle and pom.xml"));
cliOptions.add(new CliOption("artifactId", "artifactId for use in the generated build.gradle and pom.xml"));
cliOptions.add(new CliOption("artifactVersion", "artifact version for use in the generated build.gradle and pom.xml"));
cliOptions.add(new CliOption("sourceFolder", "source folder for generated code"));
cliOptions.add(new CliOption("useAndroidMavenGradlePlugin", "A flag to toggle android-maven gradle plugin. Default is true."));
}
@Override
public String escapeReservedWord(String name) {
return "_" + name;
}
@Override
public String apiFileFolder() {
return outputFolder + "/" + sourceFolder + "/" + apiPackage().replace('.', File.separatorChar);
}
public String modelFileFolder() {
return outputFolder + "/" + sourceFolder + "/" + modelPackage().replace('.', File.separatorChar);
}
@Override
public String getTypeDeclaration(Property p) {
if(p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">";
} }
else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
return getSwaggerType(p) + "<String, " + getTypeDeclaration(inner) + ">"; public CodegenType getTag() {
return CodegenType.CLIENT;
} }
return super.getTypeDeclaration(p);
}
@Override public String getName() {
public String getSwaggerType(Property p) { return "android";
String swaggerType = super.getSwaggerType(p); }
String type = null;
if(typeMapping.containsKey(swaggerType)) { public String getHelp() {
type = typeMapping.get(swaggerType); return "Generates an Android client library.";
if(languageSpecificPrimitives.contains(type)) }
@Override
public String escapeReservedWord(String name) {
return "_" + name;
}
@Override
public String apiFileFolder() {
return outputFolder + "/" + sourceFolder + "/" + apiPackage().replace('.', File.separatorChar);
}
public String modelFileFolder() {
return outputFolder + "/" + sourceFolder + "/" + modelPackage().replace('.', File.separatorChar);
}
@Override
public String getTypeDeclaration(Property p) {
if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">";
} else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
return getSwaggerType(p) + "<String, " + getTypeDeclaration(inner) + ">";
}
return super.getTypeDeclaration(p);
}
@Override
public String getSwaggerType(Property p) {
String swaggerType = super.getSwaggerType(p);
String type = null;
if (typeMapping.containsKey(swaggerType)) {
type = typeMapping.get(swaggerType);
if (languageSpecificPrimitives.contains(type)) {
return toModelName(type);
}
} else {
type = swaggerType;
}
return toModelName(type); return toModelName(type);
} }
else
type = swaggerType;
return toModelName(type);
}
@Override @Override
public String toVarName(String name) { public String toVarName(String name) {
// replace - with _ e.g. created-at => created_at // replace - with _ e.g. created-at => created_at
name = name.replaceAll("-", "_"); name = name.replaceAll("-", "_");
// if it's all uppper case, do nothing // if it's all uppper case, do nothing
if (name.matches("^[A-Z_]*$")) if (name.matches("^[A-Z_]*$")) {
return name; return name;
}
// camelize (lower first character) the variable name // camelize (lower first character) the variable name
// pet_id => petId // pet_id => petId
name = camelize(name, true); name = camelize(name, true);
// for reserved word or word starting with number, append _ // for reserved word or word starting with number, append _
if(reservedWords.contains(name) || name.matches("^\\d.*")) if (reservedWords.contains(name) || name.matches("^\\d.*")) {
name = escapeReservedWord(name); name = escapeReservedWord(name);
}
return name; return name;
}
@Override
public String toParamName(String name) {
// should be the same as variable name
return toVarName(name);
}
@Override
public String toModelName(String name) {
// model name cannot use reserved keyword, e.g. return
if(reservedWords.contains(name))
throw new RuntimeException(name + " (reserved word) cannot be used as a model name");
// camelize the model name
// phone_number => PhoneNumber
return camelize(name);
}
@Override
public String toModelFilename(String name) {
// should be the same as the model name
return toModelName(name);
}
@Override
public String toOperationId(String operationId) {
// method name cannot use reserved keyword, e.g. return
if(reservedWords.contains(operationId))
throw new RuntimeException(operationId + " (reserved word) cannot be used as method name");
return camelize(operationId, true);
}
@Override
public void processOpts() {
super.processOpts();
if(additionalProperties.containsKey("invokerPackage")) {
this.setInvokerPackage((String)additionalProperties.get("invokerPackage"));
}
else{
//not set, use default to be passed to template
additionalProperties.put("invokerPackage", invokerPackage);
}
if(additionalProperties.containsKey("groupId")) {
this.setGroupId((String)additionalProperties.get("groupId"));
}
else{
//not set, use to be passed to template
additionalProperties.put("groupId", groupId);
}
if(additionalProperties.containsKey("artifactId")) {
this.setArtifactId((String)additionalProperties.get("artifactId"));
}
else{
//not set, use to be passed to template
additionalProperties.put("artifactId", artifactId);
}
if(additionalProperties.containsKey("artifactVersion")) {
this.setArtifactVersion((String)additionalProperties.get("artifactVersion"));
}
else{
//not set, use to be passed to template
additionalProperties.put("artifactVersion", artifactVersion);
}
if(additionalProperties.containsKey("sourceFolder")) {
this.setSourceFolder((String)additionalProperties.get("sourceFolder"));
} }
if(additionalProperties.containsKey("useAndroidMavenGradlePlugin")) { @Override
this.setUseAndroidMavenGradlePlugin((Boolean)additionalProperties.get("useAndroidMavenGradlePlugin")); public String toParamName(String name) {
// should be the same as variable name
return toVarName(name);
} }
else{
additionalProperties.put("useAndroidMavenGradlePlugin", useAndroidMavenGradlePlugin); @Override
public String toModelName(String name) {
// model name cannot use reserved keyword, e.g. return
if (reservedWords.contains(name)) {
throw new RuntimeException(name + " (reserved word) cannot be used as a model name");
}
// camelize the model name
// phone_number => PhoneNumber
return camelize(name);
} }
supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml"));
additionalProperties.put("useAndroidMavenGradlePlugin", useAndroidMavenGradlePlugin);
supportingFiles.add(new SupportingFile("settings.gradle.mustache", "", "settings.gradle")); @Override
supportingFiles.add(new SupportingFile("build.mustache", "", "build.gradle")); public String toModelFilename(String name) {
supportingFiles.add(new SupportingFile("manifest.mustache", projectFolder, "AndroidManifest.xml")); // should be the same as the model name
supportingFiles.add(new SupportingFile("apiInvoker.mustache", return toModelName(name);
(sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "ApiInvoker.java")); }
supportingFiles.add(new SupportingFile("httpPatch.mustache",
(sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "HttpPatch.java"));
supportingFiles.add(new SupportingFile("jsonUtil.mustache",
(sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "JsonUtil.java"));
supportingFiles.add(new SupportingFile("apiException.mustache",
(sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "ApiException.java"));
}
public Boolean getUseAndroidMavenGradlePlugin() { @Override
return useAndroidMavenGradlePlugin; public String toOperationId(String operationId) {
} // method name cannot use reserved keyword, e.g. return
if (reservedWords.contains(operationId)) {
throw new RuntimeException(operationId + " (reserved word) cannot be used as method name");
}
public void setUseAndroidMavenGradlePlugin(Boolean useAndroidMavenGradlePlugin) { return camelize(operationId, true);
this.useAndroidMavenGradlePlugin = useAndroidMavenGradlePlugin; }
}
public void setInvokerPackage(String invokerPackage) { @Override
this.invokerPackage = invokerPackage; public void processOpts() {
} super.processOpts();
public void setGroupId(String groupId) { if (additionalProperties.containsKey("invokerPackage")) {
this.groupId = groupId; this.setInvokerPackage((String) additionalProperties.get("invokerPackage"));
} } else {
//not set, use default to be passed to template
additionalProperties.put("invokerPackage", invokerPackage);
}
public void setArtifactId(String artifactId) { if (additionalProperties.containsKey("groupId")) {
this.artifactId = artifactId; this.setGroupId((String) additionalProperties.get("groupId"));
} } else {
//not set, use to be passed to template
additionalProperties.put("groupId", groupId);
}
public void setArtifactVersion(String artifactVersion) { if (additionalProperties.containsKey("artifactId")) {
this.artifactVersion = artifactVersion; this.setArtifactId((String) additionalProperties.get("artifactId"));
} } else {
//not set, use to be passed to template
additionalProperties.put("artifactId", artifactId);
}
public void setSourceFolder(String sourceFolder) { if (additionalProperties.containsKey("artifactVersion")) {
this.sourceFolder = sourceFolder; this.setArtifactVersion((String) additionalProperties.get("artifactVersion"));
} } else {
//not set, use to be passed to template
additionalProperties.put("artifactVersion", artifactVersion);
}
if (additionalProperties.containsKey("sourceFolder")) {
this.setSourceFolder((String) additionalProperties.get("sourceFolder"));
}
if (additionalProperties.containsKey("useAndroidMavenGradlePlugin")) {
this.setUseAndroidMavenGradlePlugin((Boolean) additionalProperties.get("useAndroidMavenGradlePlugin"));
} else {
additionalProperties.put("useAndroidMavenGradlePlugin", useAndroidMavenGradlePlugin);
}
supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml"));
additionalProperties.put("useAndroidMavenGradlePlugin", useAndroidMavenGradlePlugin);
supportingFiles.add(new SupportingFile("settings.gradle.mustache", "", "settings.gradle"));
supportingFiles.add(new SupportingFile("build.mustache", "", "build.gradle"));
supportingFiles.add(new SupportingFile("manifest.mustache", projectFolder, "AndroidManifest.xml"));
supportingFiles.add(new SupportingFile("apiInvoker.mustache",
(sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "ApiInvoker.java"));
supportingFiles.add(new SupportingFile("httpPatch.mustache",
(sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "HttpPatch.java"));
supportingFiles.add(new SupportingFile("jsonUtil.mustache",
(sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "JsonUtil.java"));
supportingFiles.add(new SupportingFile("apiException.mustache",
(sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "ApiException.java"));
}
public Boolean getUseAndroidMavenGradlePlugin() {
return useAndroidMavenGradlePlugin;
}
public void setUseAndroidMavenGradlePlugin(Boolean useAndroidMavenGradlePlugin) {
this.useAndroidMavenGradlePlugin = useAndroidMavenGradlePlugin;
}
public void setInvokerPackage(String invokerPackage) {
this.invokerPackage = invokerPackage;
}
public void setGroupId(String groupId) {
this.groupId = groupId;
}
public void setArtifactId(String artifactId) {
this.artifactId = artifactId;
}
public void setArtifactVersion(String artifactVersion) {
this.artifactVersion = artifactVersion;
}
public void setSourceFolder(String sourceFolder) {
this.sourceFolder = sourceFolder;
}
} }

View File

@ -1,194 +1,207 @@
package io.swagger.codegen.languages; package io.swagger.codegen.languages;
import io.swagger.codegen.*; import io.swagger.codegen.CodegenConfig;
import io.swagger.models.properties.*; import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.BooleanProperty;
import io.swagger.models.properties.DateProperty;
import io.swagger.models.properties.DateTimeProperty;
import io.swagger.models.properties.DoubleProperty;
import io.swagger.models.properties.FloatProperty;
import io.swagger.models.properties.IntegerProperty;
import io.swagger.models.properties.LongProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
import io.swagger.models.properties.StringProperty;
import java.util.*;
import java.io.File; import java.io.File;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
public class AsyncScalaClientCodegen extends DefaultCodegen implements CodegenConfig { public class AsyncScalaClientCodegen extends DefaultCodegen implements CodegenConfig {
protected String invokerPackage = "io.swagger.client"; protected String invokerPackage = "io.swagger.client";
protected String groupId = "io.swagger"; protected String groupId = "io.swagger";
protected String artifactId = "swagger-async-scala-client"; protected String artifactId = "swagger-async-scala-client";
protected String artifactVersion = "1.0.0"; protected String artifactVersion = "1.0.0";
protected String sourceFolder = "src/main/scala"; protected String sourceFolder = "src/main/scala";
protected String clientName = "SwaggerClient"; protected String clientName = "SwaggerClient";
protected String authScheme = ""; protected String authScheme = "";
protected boolean authPreemptive = false; protected boolean authPreemptive = false;
protected boolean asyncHttpClient = !authScheme.isEmpty(); protected boolean asyncHttpClient = !authScheme.isEmpty();
public CodegenType getTag() { public AsyncScalaClientCodegen() {
return CodegenType.CLIENT; super();
} outputFolder = "generated-code/async-scala";
modelTemplateFiles.put("model.mustache", ".scala");
public String getName() { apiTemplateFiles.put("api.mustache", ".scala");
return "async-scala"; templateDir = "asyncscala";
} apiPackage = "io.swagger.client.api";
modelPackage = "io.swagger.client.model";
public String getHelp() { reservedWords = new HashSet<String>(
return "Generates an Asynchronous Scala client library."; Arrays.asList(
} "abstract", "case", "catch", "class", "def", "do", "else", "extends",
"false", "final", "finally", "for", "forSome", "if", "implicit",
"import", "lazy", "match", "new", "null", "object", "override", "package",
"private", "protected", "return", "sealed", "super", "this", "throw",
"trait", "try", "true", "type", "val", "var", "while", "with", "yield")
);
public AsyncScalaClientCodegen() { additionalProperties.put("invokerPackage", invokerPackage);
super(); additionalProperties.put("groupId", groupId);
outputFolder = "generated-code/async-scala"; additionalProperties.put("artifactId", artifactId);
modelTemplateFiles.put("model.mustache", ".scala"); additionalProperties.put("artifactVersion", artifactVersion);
apiTemplateFiles.put("api.mustache", ".scala"); additionalProperties.put("asyncHttpClient", asyncHttpClient);
templateDir = "asyncscala"; additionalProperties.put("authScheme", authScheme);
apiPackage = "io.swagger.client.api"; additionalProperties.put("authPreemptive", authPreemptive);
modelPackage = "io.swagger.client.model"; additionalProperties.put("clientName", clientName);
reservedWords = new HashSet<String> ( supportingFiles.add(new SupportingFile("sbt.mustache", "", "build.sbt"));
Arrays.asList( supportingFiles.add(new SupportingFile("client.mustache",
"abstract", "case", "catch", "class", "def", "do", "else", "extends", (sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), clientName + ".scala"));
"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); importMapping.remove("List");
additionalProperties.put("groupId", groupId); importMapping.remove("Set");
additionalProperties.put("artifactId", artifactId); importMapping.remove("Map");
additionalProperties.put("artifactVersion", artifactVersion);
additionalProperties.put("asyncHttpClient", asyncHttpClient);
additionalProperties.put("authScheme", authScheme);
additionalProperties.put("authPreemptive", authPreemptive);
additionalProperties.put("clientName", clientName);
supportingFiles.add(new SupportingFile("sbt.mustache", "", "build.sbt")); importMapping.put("DateTime", "org.joda.time.DateTime");
supportingFiles.add(new SupportingFile("client.mustache", importMapping.put("ListBuffer", "scala.collections.mutable.ListBuffer");
(sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), clientName + ".scala"));
importMapping.remove("List"); typeMapping = new HashMap<String, String>();
importMapping.remove("Set"); typeMapping.put("enum", "NSString");
importMapping.remove("Map"); typeMapping.put("array", "List");
typeMapping.put("set", "Set");
typeMapping.put("boolean", "Boolean");
typeMapping.put("string", "String");
typeMapping.put("int", "Int");
typeMapping.put("long", "Long");
typeMapping.put("float", "Float");
typeMapping.put("byte", "Byte");
typeMapping.put("short", "Short");
typeMapping.put("char", "Char");
typeMapping.put("long", "Long");
typeMapping.put("double", "Double");
typeMapping.put("object", "Any");
typeMapping.put("file", "File");
importMapping.put("DateTime", "org.joda.time.DateTime"); languageSpecificPrimitives = new HashSet<String>(
importMapping.put("ListBuffer", "scala.collections.mutable.ListBuffer"); Arrays.asList(
"String",
typeMapping = new HashMap<String, String>(); "boolean",
typeMapping.put("enum", "NSString"); "Boolean",
typeMapping.put("array", "List"); "Double",
typeMapping.put("set", "Set"); "Int",
typeMapping.put("boolean", "Boolean"); "Long",
typeMapping.put("string", "String"); "Float",
typeMapping.put("int", "Int"); "Object",
typeMapping.put("long", "Long"); "List",
typeMapping.put("float", "Float"); "Map")
typeMapping.put("byte", "Byte"); );
typeMapping.put("short", "Short"); instantiationTypes.put("array", "ListBuffer");
typeMapping.put("char", "Char"); instantiationTypes.put("map", "HashMap");
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().replace('.', File.separatorChar);
}
public String modelFileFolder() {
return outputFolder + "/" + sourceFolder + "/" + modelPackage().replace('.', File.separatorChar);
}
@Override
public String getTypeDeclaration(Property p) {
if(p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]";
} }
else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
return getSwaggerType(p) + "[String, " + getTypeDeclaration(inner) + "]"; public CodegenType getTag() {
return CodegenType.CLIENT;
} }
return super.getTypeDeclaration(p);
}
@Override public String getName() {
public String getSwaggerType(Property p) { return "async-scala";
String swaggerType = super.getSwaggerType(p); }
String type = null;
if(typeMapping.containsKey(swaggerType)) { public String getHelp() {
type = typeMapping.get(swaggerType); return "Generates an Asynchronous Scala client library.";
if(languageSpecificPrimitives.contains(type)) }
@Override
public String escapeReservedWord(String name) {
return "_" + name;
}
@Override
public String apiFileFolder() {
return outputFolder + "/" + sourceFolder + "/" + apiPackage().replace('.', File.separatorChar);
}
public String modelFileFolder() {
return outputFolder + "/" + sourceFolder + "/" + modelPackage().replace('.', File.separatorChar);
}
@Override
public String getTypeDeclaration(Property p) {
if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]";
} else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
return getSwaggerType(p) + "[String, " + getTypeDeclaration(inner) + "]";
}
return super.getTypeDeclaration(p);
}
@Override
public String getSwaggerType(Property p) {
String swaggerType = super.getSwaggerType(p);
String type = null;
if (typeMapping.containsKey(swaggerType)) {
type = typeMapping.get(swaggerType);
if (languageSpecificPrimitives.contains(type)) {
return toModelName(type);
}
} else {
type = swaggerType;
}
return toModelName(type); return toModelName(type);
} }
else
type = swaggerType;
return toModelName(type);
}
@Override @Override
public String toInstantiationType(Property p) { public String toInstantiationType(Property p) {
if (p instanceof MapProperty) { if (p instanceof MapProperty) {
MapProperty ap = (MapProperty) p; MapProperty ap = (MapProperty) p;
String inner = getSwaggerType(ap.getAdditionalProperties()); String inner = getSwaggerType(ap.getAdditionalProperties());
return instantiationTypes.get("map") + "[String, " + inner + "]"; return instantiationTypes.get("map") + "[String, " + inner + "]";
} else if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
String inner = getSwaggerType(ap.getItems());
return instantiationTypes.get("array") + "[" + inner + "]";
} else {
return null;
}
} }
else if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
String inner = getSwaggerType(ap.getItems());
return instantiationTypes.get("array") + "[" + inner + "]";
}
else
return null;
}
public String toDefaultValue(Property p) { public String toDefaultValue(Property p) {
if(p instanceof StringProperty) if (p instanceof StringProperty) {
return "null"; return "null";
else if (p instanceof BooleanProperty) } else if (p instanceof BooleanProperty) {
return "null"; return "null";
else if(p instanceof DateProperty) } else if (p instanceof DateProperty) {
return "null"; return "null";
else if(p instanceof DateTimeProperty) } else if (p instanceof DateTimeProperty) {
return "null"; return "null";
else if (p instanceof DoubleProperty) } else if (p instanceof DoubleProperty) {
return "null"; return "null";
else if (p instanceof FloatProperty) } else if (p instanceof FloatProperty) {
return "null"; return "null";
else if (p instanceof IntegerProperty) } else if (p instanceof IntegerProperty) {
return "null"; return "null";
else if (p instanceof LongProperty) } else if (p instanceof LongProperty) {
return "null"; return "null";
else if (p instanceof MapProperty) { } else if (p instanceof MapProperty) {
MapProperty ap = (MapProperty) p; MapProperty ap = (MapProperty) p;
String inner = getSwaggerType(ap.getAdditionalProperties()); String inner = getSwaggerType(ap.getAdditionalProperties());
return "new HashMap[String, " + inner + "]() "; return "new HashMap[String, " + inner + "]() ";
} else if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
String inner = getSwaggerType(ap.getItems());
return "new ListBuffer[" + inner + "]() ";
} else {
return "null";
}
} }
else if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
String inner = getSwaggerType(ap.getItems());
return "new ListBuffer[" + inner + "]() ";
}
else
return "null";
}
} }

View File

@ -1,192 +1,203 @@
package io.swagger.codegen.languages; package io.swagger.codegen.languages;
import io.swagger.codegen.*; import io.swagger.codegen.CodegenConfig;
import io.swagger.models.properties.*; import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
import java.util.*;
import java.io.File; import java.io.File;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig { public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig {
protected String invokerPackage = "IO.Swagger.Client"; protected String invokerPackage = "IO.Swagger.Client";
protected String groupId = "io.swagger"; protected String groupId = "io.swagger";
protected String artifactId = "swagger-csharp-client"; protected String artifactId = "swagger-csharp-client";
protected String artifactVersion = "1.0.0"; protected String artifactVersion = "1.0.0";
protected String sourceFolder = "src/main/csharp"; protected String sourceFolder = "src/main/csharp";
public CodegenType getTag() { public CSharpClientCodegen() {
return CodegenType.CLIENT; super();
} outputFolder = "generated-code/csharp";
modelTemplateFiles.put("model.mustache", ".cs");
apiTemplateFiles.put("api.mustache", ".cs");
templateDir = "csharp";
apiPackage = "IO.Swagger.Api";
modelPackage = "IO.Swagger.Model";
public String getName() { reservedWords = new HashSet<String>(
return "csharp"; Arrays.asList(
} "abstract", "as", "base", "bool", "break", "byte", "case", "catch", "char", "checked", "class", "const", "continue", "decimal", "default", "delegate", "do", "double", "else", "enum", "event", "explicit", "extern", "false", "finally", "fixed", "float", "for", "foreach", "goto", "if", "implicit", "in", "int", "interface", "internal", "is", "lock", "long", "namespace", "new", "null", "object", "operator", "out", "override", "params", "private", "protected", "public", "readonly", "ref", "return", "sbyte", "sealed", "short", "sizeof", "stackalloc", "static", "string", "struct", "switch", "this", "throw", "true", "try", "typeof", "uint", "ulong", "unchecked", "unsafe", "ushort", "using", "virtual", "void", "volatile", "while")
);
public String getHelp() { additionalProperties.put("invokerPackage", invokerPackage);
return "Generates a CSharp client library.";
}
public CSharpClientCodegen() { supportingFiles.add(new SupportingFile("Configuration.mustache",
super(); (sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "Configuration.cs"));
outputFolder = "generated-code/csharp"; supportingFiles.add(new SupportingFile("ApiClient.mustache",
modelTemplateFiles.put("model.mustache", ".cs"); (sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "ApiClient.cs"));
apiTemplateFiles.put("api.mustache", ".cs"); supportingFiles.add(new SupportingFile("ApiException.mustache",
templateDir = "csharp"; (sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "ApiException.cs"));
apiPackage = "IO.Swagger.Api"; supportingFiles.add(new SupportingFile("Newtonsoft.Json.dll", "bin", "Newtonsoft.Json.dll"));
modelPackage = "IO.Swagger.Model"; supportingFiles.add(new SupportingFile("RestSharp.dll", "bin", "RestSharp.dll"));
supportingFiles.add(new SupportingFile("compile.mustache", "", "compile.bat"));
reservedWords = new HashSet<String> ( languageSpecificPrimitives = new HashSet<String>(
Arrays.asList( Arrays.asList(
"abstract", "as", "base", "bool", "break", "byte", "case", "catch", "char", "checked", "class", "const", "continue", "decimal", "default", "delegate", "do", "double", "else", "enum", "event", "explicit", "extern", "false", "finally", "fixed", "float", "for", "foreach", "goto", "if", "implicit", "in", "int", "interface", "internal", "is", "lock", "long", "namespace", "new", "null", "object", "operator", "out", "override", "params", "private", "protected", "public", "readonly", "ref", "return", "sbyte", "sealed", "short", "sizeof", "stackalloc", "static", "string", "struct", "switch", "this", "throw", "true", "try", "typeof", "uint", "ulong", "unchecked", "unsafe", "ushort", "using", "virtual", "void", "volatile", "while") "string",
); "bool?",
"double?",
"int?",
"long?",
"float?",
"byte[]",
"List",
"Dictionary",
"DateTime?",
"String",
"Boolean",
"Double",
"Integer",
"Long",
"Float",
"Object")
);
instantiationTypes.put("array", "List");
instantiationTypes.put("map", "Dictionary");
additionalProperties.put("invokerPackage", invokerPackage); typeMapping = new HashMap<String, String>();
typeMapping.put("string", "string");
typeMapping.put("boolean", "bool?");
typeMapping.put("integer", "int?");
typeMapping.put("float", "float?");
typeMapping.put("long", "long?");
typeMapping.put("double", "double?");
typeMapping.put("number", "double?");
typeMapping.put("datetime", "DateTime?");
typeMapping.put("date", "DateTime?");
typeMapping.put("file", "string"); // path to file
typeMapping.put("array", "List");
typeMapping.put("list", "List");
typeMapping.put("map", "Dictionary");
typeMapping.put("object", "Object");
supportingFiles.add(new SupportingFile("Configuration.mustache",
(sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "Configuration.cs"));
supportingFiles.add(new SupportingFile("ApiClient.mustache",
(sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "ApiClient.cs"));
supportingFiles.add(new SupportingFile("ApiException.mustache",
(sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "ApiException.cs"));
supportingFiles.add(new SupportingFile("Newtonsoft.Json.dll", "bin", "Newtonsoft.Json.dll"));
supportingFiles.add(new SupportingFile("RestSharp.dll", "bin", "RestSharp.dll"));
supportingFiles.add(new SupportingFile("compile.mustache", "", "compile.bat"));
languageSpecificPrimitives = new HashSet<String>(
Arrays.asList(
"string",
"bool?",
"double?",
"int?",
"long?",
"float?",
"byte[]",
"List",
"Dictionary",
"DateTime?",
"String",
"Boolean",
"Double",
"Integer",
"Long",
"Float",
"Object")
);
instantiationTypes.put("array", "List");
instantiationTypes.put("map", "Dictionary");
typeMapping = new HashMap<String, String>();
typeMapping.put("string", "string");
typeMapping.put("boolean", "bool?");
typeMapping.put("integer", "int?");
typeMapping.put("float", "float?");
typeMapping.put("long", "long?");
typeMapping.put("double", "double?");
typeMapping.put("number", "double?");
typeMapping.put("datetime", "DateTime?");
typeMapping.put("date", "DateTime?");
typeMapping.put("file", "string"); // path to file
typeMapping.put("array", "List");
typeMapping.put("list", "List");
typeMapping.put("map", "Dictionary");
typeMapping.put("object", "Object");
}
@Override
public String escapeReservedWord(String name) {
return "_" + name;
}
@Override
public String apiFileFolder() {
return (outputFolder + "/" + sourceFolder + "/" + apiPackage().replace('.', '/')).replace('.', File.separatorChar);
}
public String modelFileFolder() {
return (outputFolder + "/" + sourceFolder + "/" + modelPackage().replace('.', '/')).replace('.', File.separatorChar);
}
@Override
public String toVarName(String name) {
// replace - with _ e.g. created-at => created_at
name = name.replaceAll("-", "_");
// if it's all uppper case, do nothing
if (name.matches("^[A-Z_]*$"))
return name;
// camelize the variable name
// pet_id => PetId
name = camelize(name);
// for reserved word or word starting with number, append _
if(reservedWords.contains(name) || name.matches("^\\d.*"))
name = escapeReservedWord(name);
return name;
}
@Override
public String toParamName(String name) {
// should be the same as variable name
return toVarName(name);
}
@Override
public String toModelName(String name) {
// model name cannot use reserved keyword, e.g. return
if(reservedWords.contains(name))
throw new RuntimeException(name + " (reserved word) cannot be used as a model name");
// camelize the model name
// phone_number => PhoneNumber
return camelize(name);
}
@Override
public String toModelFilename(String name) {
// should be the same as the model name
return toModelName(name);
}
@Override
public String getTypeDeclaration(Property p) {
if(p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">";
} }
else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
return getSwaggerType(p) + "<String, " + getTypeDeclaration(inner) + ">"; public CodegenType getTag() {
return CodegenType.CLIENT;
} }
return super.getTypeDeclaration(p);
}
@Override public String getName() {
public String getSwaggerType(Property p) { return "csharp";
String swaggerType = super.getSwaggerType(p);
String type = null;
if(typeMapping.containsKey(swaggerType.toLowerCase())) {
type = typeMapping.get(swaggerType.toLowerCase());
if(languageSpecificPrimitives.contains(type))
return type;
} }
else
type = swaggerType;
return toModelName(type);
}
@Override public String getHelp() {
public String toOperationId(String operationId) { return "Generates a CSharp client library.";
// method name cannot use reserved keyword, e.g. return }
if(reservedWords.contains(operationId))
throw new RuntimeException(operationId + " (reserved word) cannot be used as method name");
return camelize(operationId); @Override
} public String escapeReservedWord(String name) {
return "_" + name;
}
@Override
public String apiFileFolder() {
return (outputFolder + "/" + sourceFolder + "/" + apiPackage().replace('.', '/')).replace('.', File.separatorChar);
}
public String modelFileFolder() {
return (outputFolder + "/" + sourceFolder + "/" + modelPackage().replace('.', '/')).replace('.', File.separatorChar);
}
@Override
public String toVarName(String name) {
// replace - with _ e.g. created-at => created_at
name = name.replaceAll("-", "_");
// if it's all uppper case, do nothing
if (name.matches("^[A-Z_]*$")) {
return name;
}
// camelize the variable name
// pet_id => PetId
name = camelize(name);
// for reserved word or word starting with number, append _
if (reservedWords.contains(name) || name.matches("^\\d.*")) {
name = escapeReservedWord(name);
}
return name;
}
@Override
public String toParamName(String name) {
// should be the same as variable name
return toVarName(name);
}
@Override
public String toModelName(String name) {
// model name cannot use reserved keyword, e.g. return
if (reservedWords.contains(name)) {
throw new RuntimeException(name + " (reserved word) cannot be used as a model name");
}
// camelize the model name
// phone_number => PhoneNumber
return camelize(name);
}
@Override
public String toModelFilename(String name) {
// should be the same as the model name
return toModelName(name);
}
@Override
public String getTypeDeclaration(Property p) {
if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">";
} else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
return getSwaggerType(p) + "<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.toLowerCase())) {
type = typeMapping.get(swaggerType.toLowerCase());
if (languageSpecificPrimitives.contains(type)) {
return type;
}
} else {
type = swaggerType;
}
return toModelName(type);
}
@Override
public String toOperationId(String operationId) {
// method name cannot use reserved keyword, e.g. return
if (reservedWords.contains(operationId)) {
throw new RuntimeException(operationId + " (reserved word) cannot be used as method name");
}
return camelize(operationId);
}
} }

View File

@ -1,241 +1,247 @@
package io.swagger.codegen.languages; package io.swagger.codegen.languages;
import io.swagger.codegen.*; import io.swagger.codegen.CliOption;
import io.swagger.models.properties.*; import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
import java.util.*;
import java.io.File; import java.io.File;
import java.util.Arrays;
import java.util.HashSet;
public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
protected String invokerPackage = "io.swagger.client"; protected String invokerPackage = "io.swagger.client";
protected String groupId = "io.swagger"; protected String groupId = "io.swagger";
protected String artifactId = "swagger-java-client"; protected String artifactId = "swagger-java-client";
protected String artifactVersion = "1.0.0"; protected String artifactVersion = "1.0.0";
protected String sourceFolder = "src/main/java"; protected String sourceFolder = "src/main/java";
public CodegenType getTag() { public JavaClientCodegen() {
return CodegenType.CLIENT; super();
} outputFolder = "generated-code/java";
modelTemplateFiles.put("model.mustache", ".java");
apiTemplateFiles.put("api.mustache", ".java");
templateDir = "Java";
apiPackage = "io.swagger.client.api";
modelPackage = "io.swagger.client.model";
public String getName() { reservedWords = new HashSet<String>(
return "java"; Arrays.asList(
} "abstract", "continue", "for", "new", "switch", "assert",
"default", "if", "package", "synchronized", "boolean", "do", "goto", "private",
"this", "break", "double", "implements", "protected", "throw", "byte", "else",
"import", "public", "throws", "case", "enum", "instanceof", "return", "transient",
"catch", "extends", "int", "short", "try", "char", "final", "interface", "static",
"void", "class", "finally", "long", "strictfp", "volatile", "const", "float",
"native", "super", "while")
);
public String getHelp() { languageSpecificPrimitives = new HashSet<String>(
return "Generates a Java client library."; Arrays.asList(
} "String",
"boolean",
"Boolean",
"Double",
"Integer",
"Long",
"Float",
"Object")
);
instantiationTypes.put("array", "ArrayList");
instantiationTypes.put("map", "HashMap");
public JavaClientCodegen() { cliOptions.add(new CliOption("invokerPackage", "root package for generated code"));
super(); cliOptions.add(new CliOption("groupId", "groupId in generated pom.xml"));
outputFolder = "generated-code/java"; cliOptions.add(new CliOption("artifactId", "artifactId in generated pom.xml"));
modelTemplateFiles.put("model.mustache", ".java"); cliOptions.add(new CliOption("artifactVersion", "artifact version in generated pom.xml"));
apiTemplateFiles.put("api.mustache", ".java"); cliOptions.add(new CliOption("sourceFolder", "source folder for generated code"));
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")
);
languageSpecificPrimitives = new HashSet<String>(
Arrays.asList(
"String",
"boolean",
"Boolean",
"Double",
"Integer",
"Long",
"Float",
"Object")
);
instantiationTypes.put("array", "ArrayList");
instantiationTypes.put("map", "HashMap");
cliOptions.add(new CliOption("invokerPackage", "root package for generated code"));
cliOptions.add(new CliOption("groupId", "groupId in generated pom.xml"));
cliOptions.add(new CliOption("artifactId", "artifactId in generated pom.xml"));
cliOptions.add(new CliOption("artifactVersion", "artifact version in generated pom.xml"));
cliOptions.add(new CliOption("sourceFolder", "source folder for generated code"));
}
@Override
public void processOpts() {
super.processOpts();
if(additionalProperties.containsKey("invokerPackage")) {
this.setInvokerPackage((String)additionalProperties.get("invokerPackage"));
}
else{
//not set, use default to be passed to template
additionalProperties.put("invokerPackage", invokerPackage);
} }
if(additionalProperties.containsKey("groupId")) { public CodegenType getTag() {
this.setGroupId((String)additionalProperties.get("groupId")); return CodegenType.CLIENT;
}
else{
//not set, use to be passed to template
additionalProperties.put("groupId", groupId);
} }
if(additionalProperties.containsKey("artifactId")) { public String getName() {
this.setArtifactId((String)additionalProperties.get("artifactId")); return "java";
}
else{
//not set, use to be passed to template
additionalProperties.put("artifactId", artifactId);
} }
if(additionalProperties.containsKey("artifactVersion")) { public String getHelp() {
this.setArtifactVersion((String)additionalProperties.get("artifactVersion")); return "Generates a Java client library.";
}
else{
//not set, use to be passed to template
additionalProperties.put("artifactVersion", artifactVersion);
} }
if(additionalProperties.containsKey("sourceFolder")) { @Override
this.setSourceFolder((String)additionalProperties.get("sourceFolder")); public void processOpts() {
super.processOpts();
if (additionalProperties.containsKey("invokerPackage")) {
this.setInvokerPackage((String) additionalProperties.get("invokerPackage"));
} else {
//not set, use default to be passed to template
additionalProperties.put("invokerPackage", invokerPackage);
}
if (additionalProperties.containsKey("groupId")) {
this.setGroupId((String) additionalProperties.get("groupId"));
} else {
//not set, use to be passed to template
additionalProperties.put("groupId", groupId);
}
if (additionalProperties.containsKey("artifactId")) {
this.setArtifactId((String) additionalProperties.get("artifactId"));
} else {
//not set, use to be passed to template
additionalProperties.put("artifactId", artifactId);
}
if (additionalProperties.containsKey("artifactVersion")) {
this.setArtifactVersion((String) additionalProperties.get("artifactVersion"));
} else {
//not set, use to be passed to template
additionalProperties.put("artifactVersion", artifactVersion);
}
if (additionalProperties.containsKey("sourceFolder")) {
this.setSourceFolder((String) additionalProperties.get("sourceFolder"));
}
final String invokerFolder = (sourceFolder + File.separator + invokerPackage).replace(".", File.separator);
supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml"));
supportingFiles.add(new SupportingFile("ApiClient.mustache", invokerFolder, "ApiClient.java"));
supportingFiles.add(new SupportingFile("apiException.mustache", invokerFolder, "ApiException.java"));
supportingFiles.add(new SupportingFile("Configuration.mustache", invokerFolder, "Configuration.java"));
supportingFiles.add(new SupportingFile("JsonUtil.mustache", invokerFolder, "JsonUtil.java"));
supportingFiles.add(new SupportingFile("StringUtil.mustache", invokerFolder, "StringUtil.java"));
final String authFolder = (sourceFolder + File.separator + invokerPackage + ".auth").replace(".", File.separator);
supportingFiles.add(new SupportingFile("auth/Authentication.mustache", authFolder, "Authentication.java"));
supportingFiles.add(new SupportingFile("auth/HttpBasicAuth.mustache", authFolder, "HttpBasicAuth.java"));
supportingFiles.add(new SupportingFile("auth/ApiKeyAuth.mustache", authFolder, "ApiKeyAuth.java"));
supportingFiles.add(new SupportingFile("auth/OAuth.mustache", authFolder, "OAuth.java"));
} }
final String invokerFolder = (sourceFolder + File.separator + invokerPackage).replace(".", File.separator);
supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml"));
supportingFiles.add(new SupportingFile("ApiClient.mustache", invokerFolder, "ApiClient.java"));
supportingFiles.add(new SupportingFile("apiException.mustache", invokerFolder, "ApiException.java"));
supportingFiles.add(new SupportingFile("Configuration.mustache", invokerFolder, "Configuration.java"));
supportingFiles.add(new SupportingFile("JsonUtil.mustache", invokerFolder, "JsonUtil.java"));
supportingFiles.add(new SupportingFile("StringUtil.mustache", invokerFolder, "StringUtil.java"));
final String authFolder = (sourceFolder + File.separator + invokerPackage + ".auth").replace(".", File.separator); @Override
supportingFiles.add(new SupportingFile("auth/Authentication.mustache", authFolder, "Authentication.java")); public String escapeReservedWord(String name) {
supportingFiles.add(new SupportingFile("auth/HttpBasicAuth.mustache", authFolder, "HttpBasicAuth.java")); return "_" + name;
supportingFiles.add(new SupportingFile("auth/ApiKeyAuth.mustache", authFolder, "ApiKeyAuth.java"));
supportingFiles.add(new SupportingFile("auth/OAuth.mustache", authFolder, "OAuth.java"));
}
@Override
public String escapeReservedWord(String name) {
return "_" + name;
}
@Override
public String apiFileFolder() {
return outputFolder + "/" + sourceFolder + "/" + apiPackage().replace('.', File.separatorChar);
}
public String modelFileFolder() {
return outputFolder + "/" + sourceFolder + "/" + modelPackage().replace('.', File.separatorChar);
}
@Override
public String toVarName(String name) {
// replace - with _ e.g. created-at => created_at
name = name.replaceAll("-", "_");
// if it's all uppper case, do nothing
if (name.matches("^[A-Z_]*$"))
return name;
// camelize (lower first character) the variable name
// pet_id => petId
name = camelize(name, true);
// for reserved word or word starting with number, append _
if(reservedWords.contains(name) || name.matches("^\\d.*"))
name = escapeReservedWord(name);
return name;
}
@Override
public String toParamName(String name) {
// should be the same as variable name
return toVarName(name);
}
@Override
public String toModelName(String name) {
// model name cannot use reserved keyword, e.g. return
if(reservedWords.contains(name))
throw new RuntimeException(name + " (reserved word) cannot be used as a model name");
// camelize the model name
// phone_number => PhoneNumber
return camelize(name);
}
@Override
public String toModelFilename(String name) {
// should be the same as the model name
return toModelName(name);
}
@Override
public String getTypeDeclaration(Property p) {
if(p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">";
} }
else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
return getSwaggerType(p) + "<String, " + getTypeDeclaration(inner) + ">"; @Override
public String apiFileFolder() {
return outputFolder + "/" + sourceFolder + "/" + apiPackage().replace('.', File.separatorChar);
} }
return super.getTypeDeclaration(p);
}
@Override public String modelFileFolder() {
public String getSwaggerType(Property p) { return outputFolder + "/" + sourceFolder + "/" + modelPackage().replace('.', File.separatorChar);
String swaggerType = super.getSwaggerType(p); }
String type = null;
if(typeMapping.containsKey(swaggerType)) { @Override
type = typeMapping.get(swaggerType); public String toVarName(String name) {
if(languageSpecificPrimitives.contains(type)) // replace - with _ e.g. created-at => created_at
name = name.replaceAll("-", "_");
// if it's all uppper case, do nothing
if (name.matches("^[A-Z_]*$")) {
return name;
}
// camelize (lower first character) the variable name
// pet_id => petId
name = camelize(name, true);
// for reserved word or word starting with number, append _
if (reservedWords.contains(name) || name.matches("^\\d.*")) {
name = escapeReservedWord(name);
}
return name;
}
@Override
public String toParamName(String name) {
// should be the same as variable name
return toVarName(name);
}
@Override
public String toModelName(String name) {
// model name cannot use reserved keyword, e.g. return
if (reservedWords.contains(name)) {
throw new RuntimeException(name + " (reserved word) cannot be used as a model name");
}
// camelize the model name
// phone_number => PhoneNumber
return camelize(name);
}
@Override
public String toModelFilename(String name) {
// should be the same as the model name
return toModelName(name);
}
@Override
public String getTypeDeclaration(Property p) {
if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">";
} else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
return getSwaggerType(p) + "<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); return toModelName(type);
} }
else
type = swaggerType;
return toModelName(type);
}
@Override @Override
public String toOperationId(String operationId) { public String toOperationId(String operationId) {
// method name cannot use reserved keyword, e.g. return // method name cannot use reserved keyword, e.g. return
if(reservedWords.contains(operationId)) if (reservedWords.contains(operationId)) {
throw new RuntimeException(operationId + " (reserved word) cannot be used as method name"); throw new RuntimeException(operationId + " (reserved word) cannot be used as method name");
}
return camelize(operationId, true); return camelize(operationId, true);
} }
public void setInvokerPackage(String invokerPackage) { public void setInvokerPackage(String invokerPackage) {
this.invokerPackage = invokerPackage; this.invokerPackage = invokerPackage;
} }
public void setGroupId(String groupId) { public void setGroupId(String groupId) {
this.groupId = groupId; this.groupId = groupId;
} }
public void setArtifactId(String artifactId) { public void setArtifactId(String artifactId) {
this.artifactId = artifactId; this.artifactId = artifactId;
} }
public void setArtifactVersion(String artifactVersion) { public void setArtifactVersion(String artifactVersion) {
this.artifactVersion = artifactVersion; this.artifactVersion = artifactVersion;
} }
public void setSourceFolder(String sourceFolder) { public void setSourceFolder(String sourceFolder) {
this.sourceFolder = sourceFolder; this.sourceFolder = sourceFolder;
} }
} }

View File

@ -1,200 +1,206 @@
package io.swagger.codegen.languages; package io.swagger.codegen.languages;
import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenOperation;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.SupportingFile;
import io.swagger.models.Operation; import io.swagger.models.Operation;
import io.swagger.codegen.*; import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.*; import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
import java.util.*;
import java.io.File; import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
public class JaxRSServerCodegen extends JavaClientCodegen implements CodegenConfig { public class JaxRSServerCodegen extends JavaClientCodegen implements CodegenConfig {
protected String invokerPackage = "io.swagger.api"; protected String invokerPackage = "io.swagger.api";
protected String groupId = "io.swagger"; protected String groupId = "io.swagger";
protected String artifactId = "swagger-jaxrs-server"; protected String artifactId = "swagger-jaxrs-server";
protected String artifactVersion = "1.0.0"; protected String artifactVersion = "1.0.0";
protected String title = "Swagger Server"; protected String title = "Swagger Server";
public CodegenType getTag() { public JaxRSServerCodegen() {
return CodegenType.SERVER; super.processOpts();
}
public String getName() { sourceFolder = "src/gen/java";
return "jaxrs";
}
public String getHelp() { outputFolder = System.getProperty("swagger.codegen.jaxrs.genfolder", "generated-code/javaJaxRS");
return "Generates a Java JAXRS Server application."; modelTemplateFiles.put("model.mustache", ".java");
} apiTemplateFiles.put("api.mustache", ".java");
apiTemplateFiles.put("apiService.mustache", ".java");
apiTemplateFiles.put("apiServiceImpl.mustache", ".java");
apiTemplateFiles.put("apiServiceFactory.mustache", ".java");
templateDir = "JavaJaxRS";
apiPackage = System.getProperty("swagger.codegen.jaxrs.apipackage", "io.swagger.api");
modelPackage = System.getProperty("swagger.codegen.jaxrs.modelpackage", "io.swagger.model");
public JaxRSServerCodegen() { additionalProperties.put("invokerPackage", invokerPackage);
super.processOpts(); additionalProperties.put("groupId", groupId);
additionalProperties.put("artifactId", artifactId);
sourceFolder = "src/gen/java"; additionalProperties.put("artifactVersion", artifactVersion);
additionalProperties.put("title", title);
outputFolder = System.getProperty( "swagger.codegen.jaxrs.genfolder", "generated-code/javaJaxRS" );
modelTemplateFiles.put("model.mustache", ".java");
apiTemplateFiles.put("api.mustache", ".java");
apiTemplateFiles.put("apiService.mustache", ".java");
apiTemplateFiles.put("apiServiceImpl.mustache", ".java");
apiTemplateFiles.put("apiServiceFactory.mustache", ".java");
templateDir = "JavaJaxRS";
apiPackage = System.getProperty( "swagger.codegen.jaxrs.apipackage", "io.swagger.api") ;
modelPackage = System.getProperty( "swagger.codegen.jaxrs.modelpackage", "io.swagger.model" );
additionalProperties.put("invokerPackage", invokerPackage);
additionalProperties.put("groupId", groupId);
additionalProperties.put("artifactId", artifactId);
additionalProperties.put("artifactVersion", artifactVersion);
additionalProperties.put("title", title);
languageSpecificPrimitives = new HashSet<String>( languageSpecificPrimitives = new HashSet<String>(
Arrays.asList( Arrays.asList(
"String", "String",
"boolean", "boolean",
"Boolean", "Boolean",
"Double", "Double",
"Integer", "Integer",
"Long", "Long",
"Float") "Float")
); );
}
@Override
public void processOpts() {
super.processOpts();
supportingFiles.clear();
supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml"));
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
supportingFiles.add(new SupportingFile("ApiException.mustache",
(sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiException.java"));
supportingFiles.add(new SupportingFile("ApiOriginFilter.mustache",
(sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiOriginFilter.java"));
supportingFiles.add(new SupportingFile("ApiResponseMessage.mustache",
(sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiResponseMessage.java"));
supportingFiles.add(new SupportingFile("NotFoundException.mustache",
(sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "NotFoundException.java"));
supportingFiles.add(new SupportingFile("web.mustache",
("src/main/webapp/WEB-INF"), "web.xml"));
}
@Override
public String getTypeDeclaration(Property p) {
if(p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">";
} }
else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
return getTypeDeclaration(inner); public CodegenType getTag() {
return CodegenType.SERVER;
} }
return super.getTypeDeclaration(p);
}
@Override public String getName() {
public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, Map<String, List<CodegenOperation>> operations) { return "jaxrs";
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) { public String getHelp() {
Map<String, Object> operations = (Map<String, Object>)objs.get("operations"); return "Generates a Java JAXRS Server application.";
if(operations != null) { }
List<CodegenOperation> ops = (List<CodegenOperation>) operations.get("operation");
for(CodegenOperation operation : ops) { @Override
if(operation.returnType == null) public void processOpts() {
operation.returnType = "Void"; super.processOpts();
else if(operation.returnType.startsWith("List")) {
String rt = operation.returnType; supportingFiles.clear();
int end = rt.lastIndexOf(">"); supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml"));
if(end > 0) { supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
operation.returnType = rt.substring("List<".length(), end); supportingFiles.add(new SupportingFile("ApiException.mustache",
operation.returnContainer = "List"; (sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiException.java"));
} supportingFiles.add(new SupportingFile("ApiOriginFilter.mustache",
(sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiOriginFilter.java"));
supportingFiles.add(new SupportingFile("ApiResponseMessage.mustache",
(sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiResponseMessage.java"));
supportingFiles.add(new SupportingFile("NotFoundException.mustache",
(sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "NotFoundException.java"));
supportingFiles.add(new SupportingFile("web.mustache",
("src/main/webapp/WEB-INF"), "web.xml"));
}
@Override
public String getTypeDeclaration(Property p) {
if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">";
} else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
return getTypeDeclaration(inner);
} }
else if(operation.returnType.startsWith("Map")) { return super.getTypeDeclaration(p);
String rt = operation.returnType; }
int end = rt.lastIndexOf(">");
if(end > 0) { @Override
operation.returnType = rt.substring("Map<".length(), end); public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, Map<String, List<CodegenOperation>> operations) {
operation.returnContainer = "Map"; String basePath = resourcePath;
} if (basePath.startsWith("/")) {
basePath = basePath.substring(1);
} }
else if(operation.returnType.startsWith("Set")) { int pos = basePath.indexOf("/");
String rt = operation.returnType; if (pos > 0) {
int end = rt.lastIndexOf(">"); basePath = basePath.substring(0, pos);
if(end > 0) {
operation.returnType = rt.substring("Set<".length(), end);
operation.returnContainer = "Set";
}
} }
}
}
return objs;
}
@Override if (basePath == "") {
public String apiFilename(String templateName, String tag) { basePath = "default";
} else {
String result = super.apiFilename(templateName, tag); if (co.path.startsWith("/" + basePath)) {
co.path = co.path.substring(("/" + basePath).length());
if( templateName.endsWith( "Impl.mustache")){ }
int ix = result.lastIndexOf( '/' ); co.subresourceOperation = !co.path.isEmpty();
result = result.substring( 0, ix ) + "/impl" + result.substring( ix, result.length()-5 ) + "ServiceImpl.java"; }
List<CodegenOperation> opList = operations.get(basePath);
String output = System.getProperty( "swagger.codegen.jaxrs.impl.source" ); if (opList == null) {
if( output != null ){ opList = new ArrayList<CodegenOperation>();
result = result.replace( apiFileFolder(), implFileFolder(output)); operations.put(basePath, opList);
} }
} opList.add(co);
else if( templateName.endsWith( "Factory.mustache")){ co.baseName = basePath;
int ix = result.lastIndexOf( '/' );
result = result.substring( 0, ix ) + "/factories" + result.substring( ix, result.length()-5 ) + "ServiceFactory.java";
String output = System.getProperty( "swagger.codegen.jaxrs.impl.source" );
if( output != null ){
result = result.replace( apiFileFolder(), implFileFolder(output));
}
}
else if( templateName.endsWith( "Service.mustache")) {
int ix = result.lastIndexOf('.');
result = result.substring(0, ix) + "Service.java";
} }
return result; 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;
}
private String implFileFolder(String output) { @Override
return outputFolder + "/" + output + "/" + apiPackage().replace('.', File.separatorChar); public String apiFilename(String templateName, String tag) {
}
public boolean shouldOverwrite( String filename ){ String result = super.apiFilename(templateName, tag);
return !filename.endsWith( "ServiceImpl.java") && !filename.endsWith( "ServiceFactory.java"); if (templateName.endsWith("Impl.mustache")) {
} int ix = result.lastIndexOf('/');
result = result.substring(0, ix) + "/impl" + result.substring(ix, result.length() - 5) + "ServiceImpl.java";
String output = System.getProperty("swagger.codegen.jaxrs.impl.source");
if (output != null) {
result = result.replace(apiFileFolder(), implFileFolder(output));
}
} else if (templateName.endsWith("Factory.mustache")) {
int ix = result.lastIndexOf('/');
result = result.substring(0, ix) + "/factories" + result.substring(ix, result.length() - 5) + "ServiceFactory.java";
String output = System.getProperty("swagger.codegen.jaxrs.impl.source");
if (output != null) {
result = result.replace(apiFileFolder(), implFileFolder(output));
}
} else if (templateName.endsWith("Service.mustache")) {
int ix = result.lastIndexOf('.');
result = result.substring(0, ix) + "Service.java";
}
return result;
}
private String implFileFolder(String output) {
return outputFolder + "/" + output + "/" + apiPackage().replace('.', File.separatorChar);
}
public boolean shouldOverwrite(String filename) {
return !filename.endsWith("ServiceImpl.java") && !filename.endsWith("ServiceFactory.java");
}
} }

View File

@ -1,12 +1,5 @@
package io.swagger.codegen.languages; package io.swagger.codegen.languages;
import java.io.File;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import io.swagger.codegen.CodegenConfig; import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenOperation; import io.swagger.codegen.CodegenOperation;
import io.swagger.codegen.CodegenParameter; import io.swagger.codegen.CodegenParameter;
@ -15,182 +8,193 @@ import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen; import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile; import io.swagger.codegen.SupportingFile;
import java.io.File;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig { public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig {
protected String apiVersion = "1.0.0"; protected String apiVersion = "1.0.0";
protected int serverPort = 8080; protected int serverPort = 8080;
protected String projectName = "swagger-server"; protected String projectName = "swagger-server";
public String apiPackage() { public NodeJSServerCodegen() {
return "controllers"; super();
}
/** // set the output folder here
* Configures the type of generator. outputFolder = "generated-code/nodejs";
*
* @return the CodegenType for this generator
* @see io.swagger.codegen.CodegenType
*/
public CodegenType getTag() {
return CodegenType.SERVER;
}
/** /**
* Configures a friendly name for the generator. This will be used by the generator * Models. You can write model files using the modelTemplateFiles map.
* to select the library with the -l flag. * if you want to create one template for file, you can do so here.
* * for multiple files for model, just put another entry in the `modelTemplateFiles` with
* @return the friendly name for the generator * a different extension
*/ */
public String getName() { modelTemplateFiles.clear();
return "nodejs";
}
/** /**
* Returns human-friendly help for the generator. Provide the consumer with help * Api classes. You can write classes for each Api file with the apiTemplateFiles map.
* tips, parameters here * as with models, add multiple entries with different extensions for multiple files per
* * class
* @return A string value for the help message */
*/ apiTemplateFiles.put(
public String getHelp() { "controller.mustache", // the template to use
return "Generates a nodejs server library using the swagger-tools project. By default, " + ".js"); // the extension for each file to write
"it will also generate service classes--which you can disable with the `-Dnoservice` environment variable.";
}
public NodeJSServerCodegen() { /**
super(); * Template Location. This is the location which templates will be read from. The generator
* will use the resource stream to attempt to read the templates.
*/
templateDir = "nodejs";
// set the output folder here /**
outputFolder = "generated-code/nodejs"; * Reserved words. Override this with reserved words specific to your language
*/
reservedWords = new HashSet<String>(
Arrays.asList(
"break", "case", "class", "catch", "const", "continue", "debugger",
"default", "delete", "do", "else", "export", "extends", "finally",
"for", "function", "if", "import", "in", "instanceof", "let", "new",
"return", "super", "switch", "this", "throw", "try", "typeof", "var",
"void", "while", "with", "yield")
);
/** /**
* Models. You can write model files using the modelTemplateFiles map. * Additional Properties. These values can be passed to the templates and
* if you want to create one template for file, you can do so here. * are available in models, apis, and supporting files
* for multiple files for model, just put another entry in the `modelTemplateFiles` with */
* a different extension additionalProperties.put("apiVersion", apiVersion);
*/ additionalProperties.put("serverPort", serverPort);
modelTemplateFiles.clear();
/** /**
* Api classes. You can write classes for each Api file with the apiTemplateFiles map. * Supporting Files. You can write single files for the generator with the
* as with models, add multiple entries with different extensions for multiple files per * entire object tree available. If the input file has a suffix of `.mustache
* class * it will be processed by the template engine. Otherwise, it will be copied
*/ */
apiTemplateFiles.put( // supportingFiles.add(new SupportingFile("controller.mustache",
"controller.mustache", // the template to use // "controllers",
".js"); // the extension for each file to write // "controller.js")
// );
/** supportingFiles.add(new SupportingFile("swagger.mustache",
* Template Location. This is the location which templates will be read from. The generator "api",
* will use the resource stream to attempt to read the templates. "swagger.json")
*/ );
templateDir = "nodejs"; supportingFiles.add(new SupportingFile("index.mustache",
"",
/** "index.js")
* Reserved words. Override this with reserved words specific to your language );
*/ supportingFiles.add(new SupportingFile("package.mustache",
reservedWords = new HashSet<String> ( "",
Arrays.asList( "package.json")
"break", "case", "class", "catch", "const", "continue", "debugger", );
"default", "delete", "do", "else", "export", "extends", "finally", if (System.getProperty("noservice") == null) {
"for", "function", "if", "import", "in", "instanceof", "let", "new", apiTemplateFiles.put(
"return", "super", "switch", "this", "throw", "try", "typeof", "var", "service.mustache", // the template to use
"void", "while", "with", "yield") "Service.js"); // the extension for each file to write
);
/**
* Additional Properties. These values can be passed to the templates and
* are available in models, apis, and supporting files
*/
additionalProperties.put("apiVersion", apiVersion);
additionalProperties.put("serverPort", serverPort);
/**
* Supporting Files. You can write single files for the generator with the
* entire object tree available. If the input file has a suffix of `.mustache
* it will be processed by the template engine. Otherwise, it will be copied
*/
// supportingFiles.add(new SupportingFile("controller.mustache",
// "controllers",
// "controller.js")
// );
supportingFiles.add(new SupportingFile("swagger.mustache",
"api",
"swagger.json")
);
supportingFiles.add(new SupportingFile("index.mustache",
"",
"index.js")
);
supportingFiles.add(new SupportingFile("package.mustache",
"",
"package.json")
);
if(System.getProperty("noservice") == null) {
apiTemplateFiles.put(
"service.mustache", // the template to use
"Service.js"); // the extension for each file to write
}
}
@Override
public String toApiName(String name) {
if(name.length() == 0)
return "DefaultController";
return initialCaps(name);
}
@Override
public String toApiFilename(String name) {
return toApiName(name);
}
/**
* Escapes a reserved word as defined in the `reservedWords` array. Handle escaping
* those terms here. This logic is only called if a variable matches the reseved words
*
* @return the escaped term
*/
@Override
public String escapeReservedWord(String name) {
return "_" + name; // add an underscore to the name
}
/**
* Location to write api files. You can use the apiPackage() as defined when the class is
* instantiated
*/
@Override
public String apiFileFolder() {
return outputFolder + File.separator + apiPackage().replace('.', File.separatorChar);
}
@Override
public Map<String, Object> postProcessOperations(Map<String, Object> objs) {
@SuppressWarnings("unchecked")
Map<String, Object> objectMap = (Map<String, Object>) objs.get("operations");
@SuppressWarnings("unchecked")
List<CodegenOperation> operations = (List<CodegenOperation>) objectMap.get("operation");
for(CodegenOperation operation : operations) {
operation.httpMethod = operation.httpMethod.toLowerCase();
List<CodegenParameter> params = operation.allParams;
if(params != null && params.size() == 0)
operation.allParams = null;
List<CodegenResponse> responses = operation.responses;
if(responses != null) {
for(CodegenResponse resp : responses) {
if("0".equals(resp.code))
resp.code = "default";
} }
}
if(operation.examples != null && !operation.examples.isEmpty()) {
// Leave application/json* items only
for (Iterator<Map<String, String>> it = operation.examples.iterator(); it.hasNext();) {
final Map<String, String> example = it.next();
final String contentType = example.get("contentType");
if (contentType == null || !contentType.startsWith("application/json")) {
it.remove();
}
}
}
} }
return objs;
} public String apiPackage() {
return "controllers";
}
/**
* Configures the type of generator.
*
* @return the CodegenType for this generator
* @see io.swagger.codegen.CodegenType
*/
public CodegenType getTag() {
return CodegenType.SERVER;
}
/**
* Configures a friendly name for the generator. This will be used by the generator
* to select the library with the -l flag.
*
* @return the friendly name for the generator
*/
public String getName() {
return "nodejs";
}
/**
* Returns human-friendly help for the generator. Provide the consumer with help
* tips, parameters here
*
* @return A string value for the help message
*/
public String getHelp() {
return "Generates a nodejs server library using the swagger-tools project. By default, " +
"it will also generate service classes--which you can disable with the `-Dnoservice` environment variable.";
}
@Override
public String toApiName(String name) {
if (name.length() == 0) {
return "DefaultController";
}
return initialCaps(name);
}
@Override
public String toApiFilename(String name) {
return toApiName(name);
}
/**
* Escapes a reserved word as defined in the `reservedWords` array. Handle escaping
* those terms here. This logic is only called if a variable matches the reseved words
*
* @return the escaped term
*/
@Override
public String escapeReservedWord(String name) {
return "_" + name; // add an underscore to the name
}
/**
* Location to write api files. You can use the apiPackage() as defined when the class is
* instantiated
*/
@Override
public String apiFileFolder() {
return outputFolder + File.separator + apiPackage().replace('.', File.separatorChar);
}
@Override
public Map<String, Object> postProcessOperations(Map<String, Object> objs) {
@SuppressWarnings("unchecked")
Map<String, Object> objectMap = (Map<String, Object>) objs.get("operations");
@SuppressWarnings("unchecked")
List<CodegenOperation> operations = (List<CodegenOperation>) objectMap.get("operation");
for (CodegenOperation operation : operations) {
operation.httpMethod = operation.httpMethod.toLowerCase();
List<CodegenParameter> params = operation.allParams;
if (params != null && params.size() == 0) {
operation.allParams = null;
}
List<CodegenResponse> responses = operation.responses;
if (responses != null) {
for (CodegenResponse resp : responses) {
if ("0".equals(resp.code)) {
resp.code = "default";
}
}
}
if (operation.examples != null && !operation.examples.isEmpty()) {
// Leave application/json* items only
for (Iterator<Map<String, String>> it = operation.examples.iterator(); it.hasNext(); ) {
final Map<String, String> example = it.next();
final String contentType = example.get("contentType");
if (contentType == null || !contentType.startsWith("application/json")) {
it.remove();
}
}
}
}
return objs;
}
} }

View File

@ -1,347 +1,361 @@
package io.swagger.codegen.languages; package io.swagger.codegen.languages;
import io.swagger.codegen.*; import io.swagger.codegen.CliOption;
import io.swagger.models.properties.*; import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenProperty;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
import java.util.*;
import java.io.File; import java.io.File;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
protected Set<String> foundationClasses = new HashSet<String>(); protected Set<String> foundationClasses = new HashSet<String>();
protected String sourceFolder = "client"; protected String sourceFolder = "client";
protected String classPrefix = "SWG"; protected String classPrefix = "SWG";
protected String projectName = "swaggerClient"; protected String projectName = "swaggerClient";
public CodegenType getTag() { public ObjcClientCodegen() {
return CodegenType.CLIENT; super();
} outputFolder = "generated-code" + File.separator + "objc";
modelTemplateFiles.put("model-header.mustache", ".h");
public String getName() { modelTemplateFiles.put("model-body.mustache", ".m");
return "objc"; apiTemplateFiles.put("api-header.mustache", ".h");
} apiTemplateFiles.put("api-body.mustache", ".m");
templateDir = "objc";
modelPackage = "";
public String getHelp() { defaultIncludes = new HashSet<String>(
return "Generates an Objective-C client library."; Arrays.asList(
} "bool",
"BOOL",
"int",
"NSString",
"NSObject",
"NSArray",
"NSNumber",
"NSDate",
"NSDictionary",
"NSMutableArray",
"NSMutableDictionary")
);
languageSpecificPrimitives = new HashSet<String>(
Arrays.asList(
"NSNumber",
"NSString",
"NSObject",
"NSDate",
"bool",
"BOOL")
);
public ObjcClientCodegen() { // ref: http://www.tutorialspoint.com/objective_c/objective_c_basic_syntax.htm
super(); reservedWords = new HashSet<String>(
outputFolder = "generated-code" + File.separator + "objc"; Arrays.asList(
modelTemplateFiles.put("model-header.mustache", ".h"); "auto", "else", "long", "switch",
modelTemplateFiles.put("model-body.mustache", ".m"); "break", "enum", "register", "typedef",
apiTemplateFiles.put("api-header.mustache", ".h"); "case", "extern", "return", "union",
apiTemplateFiles.put("api-body.mustache", ".m"); "char", "float", "short", "unsigned",
templateDir = "objc"; "const", "for", "signed", "void",
modelPackage = ""; "continue", "goto", "sizeof", "volatile",
"default", "if", "id", "static", "while",
"do", "int", "struct", "_Packed",
"double", "protocol", "interface", "implementation",
"NSObject", "NSInteger", "NSNumber", "CGFloat",
"property", "nonatomic", "retain", "strong",
"weak", "unsafe_unretained", "readwrite", "readonly"
));
defaultIncludes = new HashSet<String>( typeMapping = new HashMap<String, String>();
Arrays.asList( typeMapping.put("enum", "NSString");
"bool", typeMapping.put("Date", "NSDate");
"BOOL", typeMapping.put("DateTime", "NSDate");
"int", typeMapping.put("boolean", "BOOL");
"NSString", typeMapping.put("string", "NSString");
"NSObject", typeMapping.put("integer", "NSNumber");
"NSArray", typeMapping.put("int", "NSNumber");
"NSNumber", typeMapping.put("float", "NSNumber");
"NSDate", typeMapping.put("long", "NSNumber");
"NSDictionary", typeMapping.put("double", "NSNumber");
"NSMutableArray", typeMapping.put("array", "NSArray");
"NSMutableDictionary") typeMapping.put("map", "NSDictionary");
); typeMapping.put("number", "NSNumber");
languageSpecificPrimitives = new HashSet<String>( typeMapping.put("List", "NSArray");
Arrays.asList( typeMapping.put("object", "NSObject");
"NSNumber",
"NSString",
"NSObject",
"NSDate",
"bool",
"BOOL")
);
// ref: http://www.tutorialspoint.com/objective_c/objective_c_basic_syntax.htm importMapping = new HashMap<String, String>();
reservedWords = new HashSet<String>(
Arrays.asList(
"auto", "else", "long", "switch",
"break", "enum", "register", "typedef",
"case", "extern", "return", "union",
"char", "float", "short", "unsigned",
"const", "for", "signed", "void",
"continue", "goto", "sizeof", "volatile",
"default", "if", "id", "static", "while",
"do", "int", "struct", "_Packed",
"double", "protocol", "interface", "implementation",
"NSObject", "NSInteger", "NSNumber", "CGFloat",
"property", "nonatomic", "retain", "strong",
"weak", "unsafe_unretained", "readwrite", "readonly"
));
typeMapping = new HashMap<String, String>(); foundationClasses = new HashSet<String>(
typeMapping.put("enum", "NSString"); Arrays.asList(
typeMapping.put("Date", "NSDate"); "NSNumber",
typeMapping.put("DateTime", "NSDate"); "NSObject",
typeMapping.put("boolean", "BOOL"); "NSString",
typeMapping.put("string", "NSString"); "NSDate",
typeMapping.put("integer", "NSNumber"); "NSDictionary")
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> (); instantiationTypes.put("array", "NSMutableArray");
instantiationTypes.put("map", "NSMutableDictionary");
foundationClasses = new HashSet<String> ( cliOptions.add(new CliOption("classPrefix", "prefix for generated classes"));
Arrays.asList( cliOptions.add(new CliOption("sourceFolder", "source folder for generated code"));
"NSNumber", cliOptions.add(new CliOption("projectName", "name of the Xcode project in generated Podfile"));
"NSObject",
"NSString",
"NSDate",
"NSDictionary")
);
instantiationTypes.put("array", "NSMutableArray");
instantiationTypes.put("map", "NSMutableDictionary");
cliOptions.add(new CliOption("classPrefix", "prefix for generated classes"));
cliOptions.add(new CliOption("sourceFolder", "source folder for generated code"));
cliOptions.add(new CliOption("projectName", "name of the Xcode project in generated Podfile"));
}
@Override
public void processOpts() {
super.processOpts();
if(additionalProperties.containsKey("sourceFolder")) {
this.setSourceFolder((String)additionalProperties.get("sourceFolder"));
} }
if(additionalProperties.containsKey("classPrefix")) {
this.setClassPrefix((String)additionalProperties.get("classPrefix"));
}
if(additionalProperties.containsKey("projectName")) {
this.setProjectName((String)additionalProperties.get("projectName"));
}
else{
additionalProperties.put("projectName", projectName);
}
supportingFiles.add(new SupportingFile("SWGObject.h", sourceFolder, "SWGObject.h"));
supportingFiles.add(new SupportingFile("SWGObject.m", sourceFolder, "SWGObject.m"));
supportingFiles.add(new SupportingFile("SWGQueryParamCollection.h", sourceFolder, "SWGQueryParamCollection.h"));
supportingFiles.add(new SupportingFile("SWGQueryParamCollection.m", sourceFolder, "SWGQueryParamCollection.m"));
supportingFiles.add(new SupportingFile("SWGApiClient.h", sourceFolder, "SWGApiClient.h"));
supportingFiles.add(new SupportingFile("SWGApiClient.m", sourceFolder, "SWGApiClient.m"));
supportingFiles.add(new SupportingFile("SWGFile.h", sourceFolder, "SWGFile.h"));
supportingFiles.add(new SupportingFile("SWGFile.m", sourceFolder, "SWGFile.m"));
supportingFiles.add(new SupportingFile("JSONValueTransformer+ISO8601.m", sourceFolder, "JSONValueTransformer+ISO8601.m"));
supportingFiles.add(new SupportingFile("JSONValueTransformer+ISO8601.h", sourceFolder, "JSONValueTransformer+ISO8601.h"));
supportingFiles.add(new SupportingFile("SWGConfiguration-body.mustache", sourceFolder, "SWGConfiguration.m"));
supportingFiles.add(new SupportingFile("SWGConfiguration-header.mustache", sourceFolder, "SWGConfiguration.h"));
supportingFiles.add(new SupportingFile("Podfile.mustache", "", "Podfile"));
}
@Override public CodegenType getTag() {
public String toInstantiationType(Property p) { return CodegenType.CLIENT;
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; public String getName() {
String inner = getSwaggerType(ap.getItems()); return "objc";
return instantiationTypes.get("array");
} }
else
return null;
}
@Override public String getHelp() {
public String getTypeDeclaration(String name) { return "Generates an Objective-C client library.";
if(languageSpecificPrimitives.contains(name) && !foundationClasses.contains(name)) }
return name;
else
return name + "*";
}
@Override @Override
public String getSwaggerType(Property p) { public void processOpts() {
String swaggerType = super.getSwaggerType(p); super.processOpts();
String type = null;
if(typeMapping.containsKey(swaggerType)) { if (additionalProperties.containsKey("sourceFolder")) {
type = typeMapping.get(swaggerType); this.setSourceFolder((String) additionalProperties.get("sourceFolder"));
if(languageSpecificPrimitives.contains(type) && !foundationClasses.contains(type)) }
if (additionalProperties.containsKey("classPrefix")) {
this.setClassPrefix((String) additionalProperties.get("classPrefix"));
}
if (additionalProperties.containsKey("projectName")) {
this.setProjectName((String) additionalProperties.get("projectName"));
} else {
additionalProperties.put("projectName", projectName);
}
supportingFiles.add(new SupportingFile("SWGObject.h", sourceFolder, "SWGObject.h"));
supportingFiles.add(new SupportingFile("SWGObject.m", sourceFolder, "SWGObject.m"));
supportingFiles.add(new SupportingFile("SWGQueryParamCollection.h", sourceFolder, "SWGQueryParamCollection.h"));
supportingFiles.add(new SupportingFile("SWGQueryParamCollection.m", sourceFolder, "SWGQueryParamCollection.m"));
supportingFiles.add(new SupportingFile("SWGApiClient.h", sourceFolder, "SWGApiClient.h"));
supportingFiles.add(new SupportingFile("SWGApiClient.m", sourceFolder, "SWGApiClient.m"));
supportingFiles.add(new SupportingFile("SWGFile.h", sourceFolder, "SWGFile.h"));
supportingFiles.add(new SupportingFile("SWGFile.m", sourceFolder, "SWGFile.m"));
supportingFiles.add(new SupportingFile("JSONValueTransformer+ISO8601.m", sourceFolder, "JSONValueTransformer+ISO8601.m"));
supportingFiles.add(new SupportingFile("JSONValueTransformer+ISO8601.h", sourceFolder, "JSONValueTransformer+ISO8601.h"));
supportingFiles.add(new SupportingFile("SWGConfiguration-body.mustache", sourceFolder, "SWGConfiguration.m"));
supportingFiles.add(new SupportingFile("SWGConfiguration-header.mustache", sourceFolder, "SWGConfiguration.h"));
supportingFiles.add(new SupportingFile("Podfile.mustache", "", "Podfile"));
}
@Override
public String toInstantiationType(Property p) {
if (p instanceof MapProperty) {
MapProperty ap = (MapProperty) p;
String inner = getSwaggerType(ap.getAdditionalProperties());
return instantiationTypes.get("map");
} else if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
String inner = getSwaggerType(ap.getItems());
return instantiationTypes.get("array");
} else {
return null;
}
}
@Override
public String getTypeDeclaration(String name) {
if (languageSpecificPrimitives.contains(name) && !foundationClasses.contains(name)) {
return name;
} else {
return name + "*";
}
}
@Override
public String getSwaggerType(Property p) {
String swaggerType = super.getSwaggerType(p);
String type = null;
if (typeMapping.containsKey(swaggerType)) {
type = typeMapping.get(swaggerType);
if (languageSpecificPrimitives.contains(type) && !foundationClasses.contains(type)) {
return toModelName(type);
}
} else {
type = swaggerType;
}
return toModelName(type); return toModelName(type);
} }
else
type = swaggerType;
return toModelName(type);
}
@Override @Override
public String getTypeDeclaration(Property p) { public String getTypeDeclaration(Property p) {
if (p instanceof ArrayProperty) { if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p; ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems(); Property inner = ap.getItems();
String innerType = getSwaggerType(inner); String innerType = getSwaggerType(inner);
// In this codition, type of property p is array of primitive, // In this codition, type of property p is array of primitive,
// return container type with pointer, e.g. `NSArray*' // return container type with pointer, e.g. `NSArray*'
if (languageSpecificPrimitives.contains(innerType)) if (languageSpecificPrimitives.contains(innerType)) {
return getSwaggerType(p) + "*"; return getSwaggerType(p) + "*";
}
// In this codition, type of property p is array of model, // In this codition, type of property p is array of model,
// return container type combine inner type with pointer, e.g. `NSArray<SWGTag>*' // return container type combine inner type with pointer, e.g. `NSArray<SWGTag>*'
String innerTypeDeclaration = getTypeDeclaration(inner); String innerTypeDeclaration = getTypeDeclaration(inner);
if (innerTypeDeclaration.endsWith("*"))
innerTypeDeclaration = innerTypeDeclaration.substring(0, innerTypeDeclaration.length() - 1);
return getSwaggerType(p) + "<" + innerTypeDeclaration + ">*";
}
else {
String swaggerType = getSwaggerType(p);
// In this codition, type of p is objective-c primitive type, e.g. `NSSNumber', if (innerTypeDeclaration.endsWith("*")) {
// return type of p with pointer, e.g. `NSNumber*' innerTypeDeclaration = innerTypeDeclaration.substring(0, innerTypeDeclaration.length() - 1);
if (languageSpecificPrimitives.contains(swaggerType) && }
foundationClasses.contains(swaggerType)) {
return swaggerType + "*";
}
// In this codition, type of p is c primitive type, e.g. `bool',
// return type of p, e.g. `bool'
else if (languageSpecificPrimitives.contains(swaggerType)) {
return swaggerType;
}
// In this codition, type of p is objective-c object type, e.g. `SWGPet',
// return type of p with pointer, e.g. `SWGPet*'
else {
return swaggerType + "*";
}
}
}
@Override return getSwaggerType(p) + "<" + innerTypeDeclaration + ">*";
public String toModelName(String type) { } else {
type = type.replaceAll("[^0-9a-zA-Z_]", "_"); String swaggerType = getSwaggerType(p);
// language build-in classes // In this codition, type of p is objective-c primitive type, e.g. `NSSNumber',
if(typeMapping.keySet().contains(type) || // return type of p with pointer, e.g. `NSNumber*'
foundationClasses.contains(type) || if (languageSpecificPrimitives.contains(swaggerType) &&
importMapping.values().contains(type) || foundationClasses.contains(swaggerType)) {
defaultIncludes.contains(type) || return swaggerType + "*";
languageSpecificPrimitives.contains(type)) { }
return camelize(type); // In this codition, type of p is c primitive type, e.g. `bool',
// return type of p, e.g. `bool'
else if (languageSpecificPrimitives.contains(swaggerType)) {
return swaggerType;
}
// In this codition, type of p is objective-c object type, e.g. `SWGPet',
// return type of p with pointer, e.g. `SWGPet*'
else {
return swaggerType + "*";
}
}
} }
// custom classes
else {
return classPrefix + camelize(type);
}
}
@Override @Override
public String toModelFilename(String name) { public String toModelName(String type) {
// should be the same as the model name type = type.replaceAll("[^0-9a-zA-Z_]", "_");
return toModelName(name);
} // language build-in classes
if (typeMapping.keySet().contains(type) ||
foundationClasses.contains(type) ||
importMapping.values().contains(type) ||
defaultIncludes.contains(type) ||
languageSpecificPrimitives.contains(type)) {
return camelize(type);
}
// custom classes
else {
return classPrefix + camelize(type);
}
}
@Override
public String toModelFilename(String name) {
// should be the same as the model name
return toModelName(name);
}
@Override @Override
protected void setNonArrayMapProperty(CodegenProperty property, String type) { protected void setNonArrayMapProperty(CodegenProperty property, String type) {
super.setNonArrayMapProperty(property, type); super.setNonArrayMapProperty(property, type);
if("NSDictionary".equals(type)) { if ("NSDictionary".equals(type)) {
property.setter = "initWithDictionary"; property.setter = "initWithDictionary";
} } else {
else {
property.setter = "initWithValues"; property.setter = "initWithValues";
} }
} }
@Override @Override
public String toModelImport(String name) { public String toModelImport(String name) {
if("".equals(modelPackage())) if ("".equals(modelPackage())) {
return name; return name;
else } else {
return modelPackage() + "." + name; return modelPackage() + "." + name;
} }
}
@Override @Override
public String toDefaultValue(Property p) { public String toDefaultValue(Property p) {
return null; return null;
} }
@Override @Override
public String apiFileFolder() { public String apiFileFolder() {
return outputFolder + File.separator + sourceFolder; return outputFolder + File.separator + sourceFolder;
} }
@Override @Override
public String modelFileFolder() { public String modelFileFolder() {
return outputFolder + File.separator + sourceFolder; return outputFolder + File.separator + sourceFolder;
} }
@Override @Override
public String toApiName(String name) { public String toApiName(String name) {
return classPrefix + camelize(name) + "Api"; return classPrefix + camelize(name) + "Api";
} }
public String toApiFilename(String name) { public String toApiFilename(String name) {
return classPrefix + camelize(name) + "Api"; return classPrefix + camelize(name) + "Api";
} }
@Override @Override
public String toVarName(String name) { public String toVarName(String name) {
// replace non-word characters to `_` // replace non-word characters to `_`
// e.g. `created-at` to `created_at` // e.g. `created-at` to `created_at`
name = name.replaceAll("[^a-zA-Z0-9_]","_"); name = name.replaceAll("[^a-zA-Z0-9_]", "_");
// if it's all upper case, do noting // if it's all upper case, do noting
if (name.matches("^[A-Z_]$")) if (name.matches("^[A-Z_]$")) {
return name; return name;
}
// camelize (lower first character) the variable name // camelize (lower first character) the variable name
// e.g. `pet_id` to `petId` // e.g. `pet_id` to `petId`
name = camelize(name, true); name = camelize(name, true);
// for reserved word or word starting with number, prepend `_` // for reserved word or word starting with number, prepend `_`
if (reservedWords.contains(name) || name.matches("^\\d.*")) if (reservedWords.contains(name) || name.matches("^\\d.*")) {
name = escapeReservedWord(name); name = escapeReservedWord(name);
}
return name; return name;
} }
@Override
public String toParamName(String name) {
// should be the same as variable name
return toVarName(name);
}
public String escapeReservedWord(String name) { @Override
return "_" + name; public String toParamName(String name) {
} // should be the same as variable name
return toVarName(name);
}
@Override public String escapeReservedWord(String name) {
public String toOperationId(String operationId) { return "_" + name;
// method name cannot use reserved keyword, e.g. return }
if(reservedWords.contains(operationId))
throw new RuntimeException(operationId + " (reserved word) cannot be used as method name");
return camelize(operationId, true); @Override
} public String toOperationId(String operationId) {
// method name cannot use reserved keyword, e.g. return
if (reservedWords.contains(operationId)) {
throw new RuntimeException(operationId + " (reserved word) cannot be used as method name");
}
public void setSourceFolder(String sourceFolder) { return camelize(operationId, true);
this.sourceFolder = sourceFolder; }
}
public void setClassPrefix(String classPrefix) { public void setSourceFolder(String sourceFolder) {
this.classPrefix = classPrefix; this.sourceFolder = sourceFolder;
} }
public void setProjectName(String projectName) { public void setClassPrefix(String classPrefix) {
this.projectName = projectName; this.classPrefix = classPrefix;
} }
public void setProjectName(String projectName) {
this.projectName = projectName;
}
} }

View File

@ -1,200 +1,208 @@
package io.swagger.codegen.languages; package io.swagger.codegen.languages;
import io.swagger.codegen.*; import io.swagger.codegen.CodegenConfig;
import io.swagger.util.Json; import io.swagger.codegen.CodegenType;
import io.swagger.models.properties.*; import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
import java.util.*;
import java.io.File; import java.io.File;
import java.util.Arrays;
import java.util.HashSet;
public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig { public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig {
protected String invokerPackage = "SwaggerClient"; protected String invokerPackage = "SwaggerClient";
protected String groupId = "io.swagger"; protected String groupId = "io.swagger";
protected String artifactId = "swagger-client"; protected String artifactId = "swagger-client";
protected String artifactVersion = "1.0.0"; protected String artifactVersion = "1.0.0";
public CodegenType getTag() { public PerlClientCodegen() {
return CodegenType.CLIENT; super();
} modelPackage = File.separatorChar + "Object";
outputFolder = "generated-code" + File.separatorChar + "perl";
modelTemplateFiles.put("object.mustache", ".pm");
apiTemplateFiles.put("api.mustache", ".pm");
templateDir = "perl";
public String getName() { typeMapping.clear();
return "perl"; languageSpecificPrimitives.clear();
}
public String getHelp() { reservedWords = new HashSet<String>(
return "Generates a Perl client library."; Arrays.asList(
} "else", "lock", "qw",
"__END__", "elsif", "lt", "qx",
"__FILE__", "eq", "m", "s",
"__LINE__", "exp", "ne", "sub",
"__PACKAGE__", "for", "no", "tr",
"and", "foreach", "or", "unless",
"cmp", "ge", "package", "until",
"continue", "gt", "q", "while",
"CORE", "if", "qq", "xor",
"do", "le", "qr", "y"
)
);
public PerlClientCodegen() { additionalProperties.put("invokerPackage", invokerPackage);
super(); additionalProperties.put("groupId", groupId);
modelPackage = File.separatorChar + "Object"; additionalProperties.put("artifactId", artifactId);
outputFolder = "generated-code" + File.separatorChar + "perl"; additionalProperties.put("artifactVersion", artifactVersion);
modelTemplateFiles.put("object.mustache", ".pm");
apiTemplateFiles.put("api.mustache", ".pm");
templateDir = "perl";
typeMapping.clear(); languageSpecificPrimitives.add("int");
languageSpecificPrimitives.clear(); languageSpecificPrimitives.add("double");
languageSpecificPrimitives.add("string");
languageSpecificPrimitives.add("boolean");
languageSpecificPrimitives.add("DateTime");
languageSpecificPrimitives.add("ARRAY");
languageSpecificPrimitives.add("HASH");
languageSpecificPrimitives.add("object");
reservedWords = new HashSet<String> ( typeMapping.put("integer", "int");
Arrays.asList( typeMapping.put("long", "int");
"else", "lock", "qw", typeMapping.put("float", "double");
"__END__", "elsif", "lt", "qx", typeMapping.put("double", "double");
"__FILE__", "eq", "m", "s", typeMapping.put("boolean", "boolean");
"__LINE__", "exp", "ne", "sub", typeMapping.put("string", "string");
"__PACKAGE__", "for", "no", "tr", typeMapping.put("date", "DateTime");
"and", "foreach", "or", "unless", typeMapping.put("dateTime", "DateTime");
"cmp", "ge", "package", "until", typeMapping.put("password", "string");
"continue", "gt", "q", "while", typeMapping.put("array", "ARRAY");
"CORE", "if", "qq", "xor", typeMapping.put("map", "HASH");
"do", "le", "qr", "y" typeMapping.put("object", "object");
)
);
additionalProperties.put("invokerPackage", invokerPackage); supportingFiles.add(new SupportingFile("ApiClient.mustache", ("lib/WWW/" + invokerPackage).replace('/', File.separatorChar), "ApiClient.pm"));
additionalProperties.put("groupId", groupId); supportingFiles.add(new SupportingFile("Configuration.mustache", ("lib/WWW/" + invokerPackage).replace('/', File.separatorChar), "Configuration.pm"));
additionalProperties.put("artifactId", artifactId); supportingFiles.add(new SupportingFile("BaseObject.mustache", ("lib/WWW/" + invokerPackage).replace('/', File.separatorChar), "Object/BaseObject.pm"));
additionalProperties.put("artifactVersion", artifactVersion);
languageSpecificPrimitives.add("int");
languageSpecificPrimitives.add("double");
languageSpecificPrimitives.add("string");
languageSpecificPrimitives.add("boolean");
languageSpecificPrimitives.add("DateTime");
languageSpecificPrimitives.add("ARRAY");
languageSpecificPrimitives.add("HASH");
languageSpecificPrimitives.add("object");
typeMapping.put("integer", "int");
typeMapping.put("long", "int");
typeMapping.put("float", "double");
typeMapping.put("double", "double");
typeMapping.put("boolean", "boolean");
typeMapping.put("string", "string");
typeMapping.put("date", "DateTime");
typeMapping.put("dateTime", "DateTime");
typeMapping.put("password", "string");
typeMapping.put("array", "ARRAY");
typeMapping.put("map", "HASH");
typeMapping.put("object", "object");
supportingFiles.add(new SupportingFile("ApiClient.mustache", ("lib/WWW/" + invokerPackage).replace('/', File.separatorChar), "ApiClient.pm"));
supportingFiles.add(new SupportingFile("Configuration.mustache", ("lib/WWW/" + invokerPackage).replace('/', File.separatorChar), "Configuration.pm"));
supportingFiles.add(new SupportingFile("BaseObject.mustache", ("lib/WWW/" + invokerPackage).replace('/', File.separatorChar), "Object/BaseObject.pm"));
}
@Override
public String escapeReservedWord(String name) {
return "_" + name;
}
@Override
public String apiFileFolder() {
return (outputFolder + "/lib/WWW/" + invokerPackage + apiPackage()).replace('/', File.separatorChar);
}
public String modelFileFolder() {
return (outputFolder + "/lib/WWW/" + invokerPackage + modelPackage()).replace('/', File.separatorChar);
}
@Override
public String getTypeDeclaration(Property p) {
if(p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]";
} }
else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
return getSwaggerType(p) + "[string," + getTypeDeclaration(inner) + "]";
}
return super.getTypeDeclaration(p);
}
@Override public CodegenType getTag() {
public String getSwaggerType(Property p) { return CodegenType.CLIENT;
String swaggerType = super.getSwaggerType(p); }
String type = null;
if(typeMapping.containsKey(swaggerType)) { public String getName() {
type = typeMapping.get(swaggerType); return "perl";
if(languageSpecificPrimitives.contains(type)) { }
public String getHelp() {
return "Generates a Perl client library.";
}
@Override
public String escapeReservedWord(String name) {
return "_" + name;
}
@Override
public String apiFileFolder() {
return (outputFolder + "/lib/WWW/" + invokerPackage + apiPackage()).replace('/', File.separatorChar);
}
public String modelFileFolder() {
return (outputFolder + "/lib/WWW/" + invokerPackage + modelPackage()).replace('/', File.separatorChar);
}
@Override
public String getTypeDeclaration(Property p) {
if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]";
} else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
return getSwaggerType(p) + "[string," + getTypeDeclaration(inner) + "]";
}
return super.getTypeDeclaration(p);
}
@Override
public String getSwaggerType(Property p) {
String swaggerType = super.getSwaggerType(p);
String type = null;
if (typeMapping.containsKey(swaggerType)) {
type = typeMapping.get(swaggerType);
if (languageSpecificPrimitives.contains(type)) {
return type;
}
} else {
type = swaggerType;
}
if (type == null) {
return null;
}
return type; return type;
}
} }
else
type = swaggerType;
if(type == null)
return null;
return type;
}
public String toDefaultValue(Property p) { public String toDefaultValue(Property p) {
return "null"; return "null";
}
@Override
public String toVarName(String name) {
// parameter name starting with number won't compile
// need to escape it by appending _ at the beginning
if (name.matches("^[0-9]")) {
name = "_" + name;
} }
// return the name in underscore style
// PhoneNumber => phone_number
return underscore(name);
}
@Override
public String toParamName(String name) {
// should be the same as variable name
return toVarName(name);
}
@Override @Override
public String toModelName(String name) { public String toVarName(String name) {
// model name cannot use reserved keyword // parameter name starting with number won't compile
if(reservedWords.contains(name)) // need to escape it by appending _ at the beginning
escapeReservedWord(name); // e.g. return => _return if (name.matches("^[0-9]")) {
name = "_" + name;
}
// camelize the model name // return the name in underscore style
// phone_number => PhoneNumber // PhoneNumber => phone_number
return camelize(name); return underscore(name);
} }
@Override @Override
public String toModelFilename(String name) { public String toParamName(String name) {
// should be the same as the model name // should be the same as variable name
return toModelName(name); return toVarName(name);
} }
@Override @Override
public String toApiFilename(String name) { public String toModelName(String name) {
// replace - with _ e.g. created-at => created_at // model name cannot use reserved keyword
name = name.replaceAll("-", "_"); if (reservedWords.contains(name)) {
escapeReservedWord(name); // e.g. return => _return
}
// e.g. phone_number_api.rb => PhoneNumberApi.rb // camelize the model name
return camelize(name) + "Api"; // phone_number => PhoneNumber
} return camelize(name);
}
@Override @Override
public String toApiName(String name) { public String toModelFilename(String name) {
if(name.length() == 0) // should be the same as the model name
return "DefaultApi"; return toModelName(name);
// e.g. phone_number_api => PhoneNumberApi }
return camelize(name) + "Api";
}
@Override @Override
public String toOperationId(String operationId) { public String toApiFilename(String name) {
// method name cannot use reserved keyword, e.g. return // replace - with _ e.g. created-at => created_at
if(reservedWords.contains(operationId)) name = name.replaceAll("-", "_");
throw new RuntimeException(operationId + " (reserved word) cannot be used as method name");
return underscore(operationId); // e.g. phone_number_api.rb => PhoneNumberApi.rb
} return camelize(name) + "Api";
}
@Override
public String toApiName(String name) {
if (name.length() == 0) {
return "DefaultApi";
}
// e.g. phone_number_api => PhoneNumberApi
return camelize(name) + "Api";
}
@Override
public String toOperationId(String operationId) {
// method name cannot use reserved keyword, e.g. return
if (reservedWords.contains(operationId)) {
throw new RuntimeException(operationId + " (reserved word) cannot be used as method name");
}
return underscore(operationId);
}
} }

View File

@ -1,184 +1,190 @@
package io.swagger.codegen.languages; package io.swagger.codegen.languages;
import io.swagger.codegen.*; import io.swagger.codegen.CodegenConfig;
import io.swagger.util.Json; import io.swagger.codegen.CodegenType;
import io.swagger.models.properties.*; import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
import java.util.*;
import java.io.File; import java.io.File;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig {
protected String invokerPackage = "io.swagger.client"; protected String invokerPackage = "io.swagger.client";
protected String groupId = "io.swagger"; protected String groupId = "io.swagger";
protected String artifactId = "swagger-client"; protected String artifactId = "swagger-client";
protected String artifactVersion = "1.0.0"; protected String artifactVersion = "1.0.0";
public CodegenType getTag() { public PhpClientCodegen() {
return CodegenType.CLIENT; super();
}
public String getName() { invokerPackage = camelize("SwaggerClient");
return "php";
}
public String getHelp() { String packagePath = invokerPackage + "-php";
return "Generates a PHP client library.";
}
public PhpClientCodegen() { modelPackage = packagePath + "/lib/models";
super(); apiPackage = packagePath + "/lib";
outputFolder = "generated-code/php";
modelTemplateFiles.put("model.mustache", ".php");
apiTemplateFiles.put("api.mustache", ".php");
templateDir = "php";
invokerPackage = camelize("SwaggerClient"); reservedWords = new HashSet<String>(
Arrays.asList(
"__halt_compiler", "abstract", "and", "array", "as", "break", "callable", "case", "catch", "class", "clone", "const", "continue", "declare", "default", "die", "do", "echo", "else", "elseif", "empty", "enddeclare", "endfor", "endforeach", "endif", "endswitch", "endwhile", "eval", "exit", "extends", "final", "for", "foreach", "function", "global", "goto", "if", "implements", "include", "include_once", "instanceof", "insteadof", "interface", "isset", "list", "namespace", "new", "or", "print", "private", "protected", "public", "require", "require_once", "return", "static", "switch", "throw", "trait", "try", "unset", "use", "var", "while", "xor")
);
String packagePath = invokerPackage + "-php"; additionalProperties.put("invokerPackage", invokerPackage);
additionalProperties.put("groupId", groupId);
additionalProperties.put("artifactId", artifactId);
additionalProperties.put("artifactVersion", artifactVersion);
modelPackage = packagePath + "/lib/models"; // ref: http://php.net/manual/en/language.types.intro.php
apiPackage = packagePath + "/lib"; languageSpecificPrimitives = new HashSet<String>(
outputFolder = "generated-code/php"; Arrays.asList(
modelTemplateFiles.put("model.mustache", ".php"); "boolean",
apiTemplateFiles.put("api.mustache", ".php"); "int",
templateDir = "php"; "integer",
"double",
"float",
"string",
"object",
"DateTime",
"mixed",
"number")
);
reservedWords = new HashSet<String> ( instantiationTypes.put("array", "array");
Arrays.asList( instantiationTypes.put("map", "map");
"__halt_compiler", "abstract", "and", "array", "as", "break", "callable", "case", "catch", "class", "clone", "const", "continue", "declare", "default", "die", "do", "echo", "else", "elseif", "empty", "enddeclare", "endfor", "endforeach", "endif", "endswitch", "endwhile", "eval", "exit", "extends", "final", "for", "foreach", "function", "global", "goto", "if", "implements", "include", "include_once", "instanceof", "insteadof", "interface", "isset", "list", "namespace", "new", "or", "print", "private", "protected", "public", "require", "require_once", "return", "static", "switch", "throw", "trait", "try", "unset", "use", "var", "while", "xor")
);
additionalProperties.put("invokerPackage", invokerPackage); // ref: https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#data-types
additionalProperties.put("groupId", groupId); typeMapping = new HashMap<String, String>();
additionalProperties.put("artifactId", artifactId); typeMapping.put("integer", "int");
additionalProperties.put("artifactVersion", artifactVersion); typeMapping.put("long", "int");
typeMapping.put("float", "float");
typeMapping.put("double", "double");
typeMapping.put("string", "string");
typeMapping.put("byte", "int");
typeMapping.put("boolean", "boolean");
typeMapping.put("date", "DateTime");
typeMapping.put("datetime", "DateTime");
typeMapping.put("file", "string");
typeMapping.put("map", "map");
typeMapping.put("array", "array");
typeMapping.put("list", "array");
typeMapping.put("object", "object");
// ref: http://php.net/manual/en/language.types.intro.php supportingFiles.add(new SupportingFile("composer.mustache", packagePath.replace('/', File.separatorChar), "composer.json"));
languageSpecificPrimitives = new HashSet<String>( supportingFiles.add(new SupportingFile("configuration.mustache", (packagePath + "/lib").replace('/', File.separatorChar), "Configuration.php"));
Arrays.asList( supportingFiles.add(new SupportingFile("ApiClient.mustache", (packagePath + "/lib").replace('/', File.separatorChar), "ApiClient.php"));
"boolean", supportingFiles.add(new SupportingFile("ApiException.mustache", (packagePath + "/lib").replace('/', File.separatorChar), "ApiException.php"));
"int", supportingFiles.add(new SupportingFile("require.mustache", packagePath.replace('/', File.separatorChar), invokerPackage + ".php"));
"integer",
"double",
"float",
"string",
"object",
"DateTime",
"mixed",
"number")
);
instantiationTypes.put("array", "array");
instantiationTypes.put("map", "map");
// ref: https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#data-types
typeMapping = new HashMap<String, String>();
typeMapping.put("integer", "int");
typeMapping.put("long", "int");
typeMapping.put("float", "float");
typeMapping.put("double", "double");
typeMapping.put("string", "string");
typeMapping.put("byte", "int");
typeMapping.put("boolean", "boolean");
typeMapping.put("date", "DateTime");
typeMapping.put("datetime", "DateTime");
typeMapping.put("file", "string");
typeMapping.put("map", "map");
typeMapping.put("array", "array");
typeMapping.put("list", "array");
typeMapping.put("object", "object");
supportingFiles.add(new SupportingFile("composer.mustache", packagePath.replace('/', File.separatorChar), "composer.json"));
supportingFiles.add(new SupportingFile("configuration.mustache", (packagePath + "/lib").replace('/', File.separatorChar), "Configuration.php"));
supportingFiles.add(new SupportingFile("ApiClient.mustache", (packagePath + "/lib").replace('/', File.separatorChar), "ApiClient.php"));
supportingFiles.add(new SupportingFile("ApiException.mustache", (packagePath + "/lib").replace('/', File.separatorChar), "ApiException.php"));
supportingFiles.add(new SupportingFile("require.mustache", packagePath.replace('/', File.separatorChar), invokerPackage + ".php"));
}
@Override
public String escapeReservedWord(String name) {
return "_" + name;
}
@Override
public String apiFileFolder() {
return (outputFolder + "/" + apiPackage()).replace('/', File.separatorChar);
}
public String modelFileFolder() {
return (outputFolder + "/" + modelPackage()).replace('/', File.separatorChar);
}
@Override
public String getTypeDeclaration(Property p) {
if(p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]";
} }
else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p; public CodegenType getTag() {
Property inner = mp.getAdditionalProperties(); return CodegenType.CLIENT;
return getSwaggerType(p) + "[string," + getTypeDeclaration(inner) + "]";
} }
return super.getTypeDeclaration(p);
}
@Override public String getName() {
public String getSwaggerType(Property p) { return "php";
String swaggerType = super.getSwaggerType(p);
String type = null;
if(typeMapping.containsKey(swaggerType)) {
type = typeMapping.get(swaggerType);
if(languageSpecificPrimitives.contains(type)) {
return type;
}
else if (instantiationTypes.containsKey(type)) {
return type;
}
} }
else
type = swaggerType;
if(type == null)
return null;
return toModelName(type);
}
public String toDefaultValue(Property p) { public String getHelp() {
return "null"; return "Generates a PHP client library.";
}
@Override
public String toVarName(String name) {
// parameter name starting with number won't compile
// need to escape it by appending _ at the beginning
if (name.matches("^[0-9]")) {
name = "_" + name;
} }
// return the name in underscore style
// PhoneNumber => phone_number
return underscore(name);
}
@Override @Override
public String toParamName(String name) { public String escapeReservedWord(String name) {
// should be the same as variable name return "_" + name;
return toVarName(name); }
}
@Override @Override
public String toModelName(String name) { public String apiFileFolder() {
// model name cannot use reserved keyword return (outputFolder + "/" + apiPackage()).replace('/', File.separatorChar);
if(reservedWords.contains(name)) }
escapeReservedWord(name); // e.g. return => _return
// camelize the model name public String modelFileFolder() {
// phone_number => PhoneNumber return (outputFolder + "/" + modelPackage()).replace('/', File.separatorChar);
return camelize(name); }
}
@Override @Override
public String toModelFilename(String name) { public String getTypeDeclaration(Property p) {
// should be the same as the model name if (p instanceof ArrayProperty) {
return toModelName(name); ArrayProperty ap = (ArrayProperty) p;
} Property inner = ap.getItems();
return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]";
} else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
return getSwaggerType(p) + "[string," + getTypeDeclaration(inner) + "]";
}
return super.getTypeDeclaration(p);
}
@Override
public String getSwaggerType(Property p) {
String swaggerType = super.getSwaggerType(p);
String type = null;
if (typeMapping.containsKey(swaggerType)) {
type = typeMapping.get(swaggerType);
if (languageSpecificPrimitives.contains(type)) {
return type;
} else if (instantiationTypes.containsKey(type)) {
return type;
}
} else {
type = swaggerType;
}
if (type == null) {
return null;
}
return toModelName(type);
}
public String toDefaultValue(Property p) {
return "null";
}
@Override
public String toVarName(String name) {
// parameter name starting with number won't compile
// need to escape it by appending _ at the beginning
if (name.matches("^[0-9]")) {
name = "_" + name;
}
// return the name in underscore style
// PhoneNumber => phone_number
return underscore(name);
}
@Override
public String toParamName(String name) {
// should be the same as variable name
return toVarName(name);
}
@Override
public String toModelName(String name) {
// model name cannot use reserved keyword
if (reservedWords.contains(name)) {
escapeReservedWord(name); // e.g. return => _return
}
// camelize the model name
// phone_number => PhoneNumber
return camelize(name);
}
@Override
public String toModelFilename(String name) {
// should be the same as the model name
return toModelName(name);
}
} }

View File

@ -1,198 +1,210 @@
package io.swagger.codegen.languages; package io.swagger.codegen.languages;
import io.swagger.codegen.*; import io.swagger.codegen.CodegenConfig;
import io.swagger.models.properties.*; import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
import java.io.File; import java.io.File;
import java.util.*; import java.util.Arrays;
import java.util.HashSet;
public class Python3ClientCodegen extends DefaultCodegen implements CodegenConfig { public class Python3ClientCodegen extends DefaultCodegen implements CodegenConfig {
String module = "client"; String module = "client";
public CodegenType getTag() { public Python3ClientCodegen() {
return CodegenType.CLIENT; super();
} outputFolder = "generated-code/python3";
modelTemplateFiles.put("model.mustache", ".py");
apiTemplateFiles.put("api.mustache", ".py");
templateDir = "python3";
public String getName() { apiPackage = module;
return "python3"; modelPackage = module + ".models";
}
public String getHelp() { languageSpecificPrimitives.clear();
return "Generates a Python3 client library."; languageSpecificPrimitives.add("int");
} languageSpecificPrimitives.add("float");
//languageSpecificPrimitives.add("long");
languageSpecificPrimitives.add("list");
languageSpecificPrimitives.add("bool");
languageSpecificPrimitives.add("str");
languageSpecificPrimitives.add("datetime");
public Python3ClientCodegen() { typeMapping.clear();
super(); typeMapping.put("integer", "int");
outputFolder = "generated-code/python3"; typeMapping.put("float", "float");
modelTemplateFiles.put("model.mustache", ".py"); typeMapping.put("long", "int");
apiTemplateFiles.put("api.mustache", ".py"); typeMapping.put("double", "float");
templateDir = "python3"; typeMapping.put("array", "list");
typeMapping.put("map", "map");
typeMapping.put("boolean", "bool");
typeMapping.put("string", "str");
typeMapping.put("date", "datetime");
apiPackage = module; // from https://docs.python.org/release/2.5.4/ref/keywords.html
modelPackage = module + ".models"; reservedWords = new HashSet<String>(
Arrays.asList(
"and", "del", "from", "not", "while", "as", "elif", "global", "or", "with",
"assert", "else", "if", "pass", "yield", "break", "except", "import",
"print", "class", "exec", "in", "raise", "continue", "finally", "is",
"return", "def", "for", "lambda", "try"));
languageSpecificPrimitives.clear(); //supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
languageSpecificPrimitives.add("int"); supportingFiles.add(new SupportingFile("swagger.mustache", module, "swagger.py"));
languageSpecificPrimitives.add("float"); supportingFiles.add(new SupportingFile("__init__.mustache", module, "__init__.py"));
//languageSpecificPrimitives.add("long");
languageSpecificPrimitives.add("list");
languageSpecificPrimitives.add("bool");
languageSpecificPrimitives.add("str");
languageSpecificPrimitives.add("datetime");
typeMapping.clear();
typeMapping.put("integer", "int");
typeMapping.put("float", "float");
typeMapping.put("long", "int");
typeMapping.put("double", "float");
typeMapping.put("array", "list");
typeMapping.put("map", "map");
typeMapping.put("boolean", "bool");
typeMapping.put("string", "str");
typeMapping.put("date", "datetime");
// from https://docs.python.org/release/2.5.4/ref/keywords.html
reservedWords = new HashSet<String> (
Arrays.asList(
"and", "del", "from", "not", "while", "as", "elif", "global", "or", "with",
"assert", "else", "if", "pass", "yield", "break", "except", "import",
"print", "class", "exec", "in", "raise", "continue", "finally", "is",
"return", "def", "for", "lambda", "try"));
//supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
supportingFiles.add(new SupportingFile("swagger.mustache", module, "swagger.py"));
supportingFiles.add(new SupportingFile("__init__.mustache", module, "__init__.py"));
}
@Override
public String escapeReservedWord(String name) {
return "_" + name;
}
@Override
public String apiFileFolder() {
return outputFolder + "/" + apiPackage().replace('.', File.separatorChar);
}
public String modelFileFolder() {
return outputFolder + "/" + modelPackage().replace('.', File.separatorChar);
}
@Override
public String getTypeDeclaration(Property p) {
if(p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]";
} }
else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
return getSwaggerType(p) + "(String, " + getTypeDeclaration(inner) + ")"; public CodegenType getTag() {
return CodegenType.CLIENT;
} }
return super.getTypeDeclaration(p);
}
@Override public String getName() {
public String getSwaggerType(Property p) { return "python3";
String swaggerType = super.getSwaggerType(p); }
String type = null;
if(typeMapping.containsKey(swaggerType)) { public String getHelp() {
type = typeMapping.get(swaggerType); return "Generates a Python3 client library.";
if(languageSpecificPrimitives.contains(type)) { }
@Override
public String escapeReservedWord(String name) {
return "_" + name;
}
@Override
public String apiFileFolder() {
return outputFolder + "/" + apiPackage().replace('.', File.separatorChar);
}
public String modelFileFolder() {
return outputFolder + "/" + modelPackage().replace('.', File.separatorChar);
}
@Override
public String getTypeDeclaration(Property p) {
if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]";
} else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
return getSwaggerType(p) + "(String, " + getTypeDeclaration(inner) + ")";
}
return super.getTypeDeclaration(p);
}
@Override
public String getSwaggerType(Property p) {
String swaggerType = super.getSwaggerType(p);
String type = null;
if (typeMapping.containsKey(swaggerType)) {
type = typeMapping.get(swaggerType);
if (languageSpecificPrimitives.contains(type)) {
return type;
}
} else {
type = swaggerType;
}
return type; return type;
}
} }
else
type = swaggerType;
return type;
}
public String toDefaultValue(Property p) { public String toDefaultValue(Property p) {
// TODO: Support Python def value // TODO: Support Python def value
return "null"; return "null";
} }
@Override @Override
public String toVarName(String name) { public String toVarName(String name) {
// replace - with _ e.g. created-at => created_at // replace - with _ e.g. created-at => created_at
name = name.replaceAll("-", "_"); name = name.replaceAll("-", "_");
// if it's all uppper case, convert to lower case // if it's all uppper case, convert to lower case
if (name.matches("^[A-Z_]*$")) if (name.matches("^[A-Z_]*$")) {
name = name.toLowerCase(); name = name.toLowerCase();
}
// camelize (lower first character) the variable name // camelize (lower first character) the variable name
// petId => pet_id // petId => pet_id
name = underscore(name); name = underscore(name);
// for reserved word or word starting with number, append _ // for reserved word or word starting with number, append _
if(reservedWords.contains(name) || name.matches("^\\d.*")) if (reservedWords.contains(name) || name.matches("^\\d.*")) {
name = escapeReservedWord(name); name = escapeReservedWord(name);
}
return name; return name;
} }
@Override @Override
public String toParamName(String name) { public String toParamName(String name) {
// should be the same as variable name // should be the same as variable name
return toVarName(name); return toVarName(name);
} }
@Override @Override
public String toModelName(String name) { public String toModelName(String name) {
// model name cannot use reserved keyword, e.g. return // model name cannot use reserved keyword, e.g. return
if(reservedWords.contains(name)) if (reservedWords.contains(name)) {
throw new RuntimeException(name + " (reserved word) cannot be used as a model name"); throw new RuntimeException(name + " (reserved word) cannot be used as a model name");
}
// camelize the model name // camelize the model name
// phone_number => PhoneNumber // phone_number => PhoneNumber
return camelize(name); return camelize(name);
} }
@Override @Override
public String toModelFilename(String name) { public String toModelFilename(String name) {
// model name cannot use reserved keyword, e.g. return // model name cannot use reserved keyword, e.g. return
if(reservedWords.contains(name)) if (reservedWords.contains(name)) {
throw new RuntimeException(name + " (reserved word) cannot be used as a model name"); throw new RuntimeException(name + " (reserved word) cannot be used as a model name");
}
// underscore the model file name // underscore the model file name
// PhoneNumber.rb => phone_number.rb // PhoneNumber.rb => phone_number.rb
return underscore(name); return underscore(name);
} }
@Override @Override
public String toApiFilename(String name) { public String toApiFilename(String name) {
// replace - with _ e.g. created-at => created_at // replace - with _ e.g. created-at => created_at
name = name.replaceAll("-", "_"); name = name.replaceAll("-", "_");
// e.g. PhoneNumberApi.rb => phone_number_api.rb // e.g. PhoneNumberApi.rb => phone_number_api.rb
return underscore(name) + "_api"; return underscore(name) + "_api";
} }
@Override @Override
public String toApiName(String name) { public String toApiName(String name) {
if(name.length() == 0) if (name.length() == 0) {
return "DefaultApi"; return "DefaultApi";
// e.g. phone_number_api => PhoneNumberApi }
return camelize(name) + "Api"; // e.g. phone_number_api => PhoneNumberApi
} return camelize(name) + "Api";
}
@Override @Override
public String toApiVarName(String name) { public String toApiVarName(String name) {
if(name.length() == 0) if (name.length() == 0) {
return "default_api"; return "default_api";
return underscore(name) + "_api"; }
} return underscore(name) + "_api";
}
@Override @Override
public String toOperationId(String operationId) { public String toOperationId(String operationId) {
// method name cannot use reserved keyword, e.g. return // method name cannot use reserved keyword, e.g. return
if(reservedWords.contains(operationId)) if (reservedWords.contains(operationId)) {
throw new RuntimeException(operationId + " (reserved word) cannot be used as method name"); throw new RuntimeException(operationId + " (reserved word) cannot be used as method name");
}
return underscore(operationId); return underscore(operationId);
} }
} }

View File

@ -1,215 +1,227 @@
package io.swagger.codegen.languages; package io.swagger.codegen.languages;
import io.swagger.codegen.*; import io.swagger.codegen.CodegenConfig;
import io.swagger.models.properties.*; import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
import java.io.File; import java.io.File;
import java.util.*; import java.util.Arrays;
import java.util.HashSet;
public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig { public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig {
protected String module = "SwaggerPetstore"; protected String module = "SwaggerPetstore";
protected String invokerPackage; protected String invokerPackage;
protected String eggPackage; protected String eggPackage;
public CodegenType getTag() { public PythonClientCodegen() {
return CodegenType.CLIENT; super();
}
public String getName() { eggPackage = module + "-python";
return "python";
}
public String getHelp() { invokerPackage = eggPackage + File.separatorChar + module;
return "Generates a Python client library.";
}
public PythonClientCodegen() { outputFolder = "generated-code" + File.separatorChar + "python";
super(); modelTemplateFiles.put("model.mustache", ".py");
apiTemplateFiles.put("api.mustache", ".py");
templateDir = "python";
eggPackage = module + "-python"; apiPackage = invokerPackage + File.separatorChar + "apis";
modelPackage = invokerPackage + File.separatorChar + "models";
invokerPackage = eggPackage + File.separatorChar + module;
outputFolder = "generated-code" + File.separatorChar + "python"; languageSpecificPrimitives.clear();
modelTemplateFiles.put("model.mustache", ".py"); languageSpecificPrimitives.add("int");
apiTemplateFiles.put("api.mustache", ".py"); languageSpecificPrimitives.add("float");
templateDir = "python"; languageSpecificPrimitives.add("list");
languageSpecificPrimitives.add("bool");
languageSpecificPrimitives.add("str");
languageSpecificPrimitives.add("datetime");
apiPackage = invokerPackage + File.separatorChar + "apis"; typeMapping.clear();
modelPackage = invokerPackage + File.separatorChar + "models"; typeMapping.put("integer", "int");
typeMapping.put("float", "float");
typeMapping.put("long", "int");
typeMapping.put("double", "float");
typeMapping.put("array", "list");
typeMapping.put("map", "map");
typeMapping.put("boolean", "bool");
typeMapping.put("string", "str");
typeMapping.put("date", "datetime");
languageSpecificPrimitives.clear(); // from https://docs.python.org/release/2.5.4/ref/keywords.html
languageSpecificPrimitives.add("int"); reservedWords = new HashSet<String>(
languageSpecificPrimitives.add("float"); Arrays.asList(
languageSpecificPrimitives.add("list"); "and", "del", "from", "not", "while", "as", "elif", "global", "or", "with",
languageSpecificPrimitives.add("bool"); "assert", "else", "if", "pass", "yield", "break", "except", "import",
languageSpecificPrimitives.add("str"); "print", "class", "exec", "in", "raise", "continue", "finally", "is",
languageSpecificPrimitives.add("datetime"); "return", "def", "for", "lambda", "try"));
typeMapping.clear(); additionalProperties.put("module", module);
typeMapping.put("integer", "int");
typeMapping.put("float", "float");
typeMapping.put("long", "int");
typeMapping.put("double", "float");
typeMapping.put("array", "list");
typeMapping.put("map", "map");
typeMapping.put("boolean", "bool");
typeMapping.put("string", "str");
typeMapping.put("date", "datetime");
// from https://docs.python.org/release/2.5.4/ref/keywords.html supportingFiles.add(new SupportingFile("README.mustache", eggPackage, "README.md"));
reservedWords = new HashSet<String> ( supportingFiles.add(new SupportingFile("setup.mustache", eggPackage, "setup.py"));
Arrays.asList( supportingFiles.add(new SupportingFile("api_client.mustache", invokerPackage, "api_client.py"));
"and", "del", "from", "not", "while", "as", "elif", "global", "or", "with", supportingFiles.add(new SupportingFile("rest.mustache", invokerPackage, "rest.py"));
"assert", "else", "if", "pass", "yield", "break", "except", "import", supportingFiles.add(new SupportingFile("configuration.mustache", invokerPackage, "configuration.py"));
"print", "class", "exec", "in", "raise", "continue", "finally", "is", supportingFiles.add(new SupportingFile("__init__package.mustache", invokerPackage, "__init__.py"));
"return", "def", "for", "lambda", "try")); supportingFiles.add(new SupportingFile("__init__model.mustache", modelPackage, "__init__.py"));
supportingFiles.add(new SupportingFile("__init__api.mustache", apiPackage, "__init__.py"));
additionalProperties.put("module", module);
supportingFiles.add(new SupportingFile("README.mustache", eggPackage, "README.md"));
supportingFiles.add(new SupportingFile("setup.mustache", eggPackage, "setup.py"));
supportingFiles.add(new SupportingFile("api_client.mustache", invokerPackage, "api_client.py"));
supportingFiles.add(new SupportingFile("rest.mustache", invokerPackage, "rest.py"));
supportingFiles.add(new SupportingFile("configuration.mustache", invokerPackage, "configuration.py"));
supportingFiles.add(new SupportingFile("__init__package.mustache", invokerPackage, "__init__.py"));
supportingFiles.add(new SupportingFile("__init__model.mustache", modelPackage, "__init__.py"));
supportingFiles.add(new SupportingFile("__init__api.mustache", apiPackage, "__init__.py"));
}
@Override
public String escapeReservedWord(String name) {
return "_" + name;
}
@Override
public String apiFileFolder() {
return outputFolder + File.separatorChar + apiPackage().replace('.', File.separatorChar);
}
public String modelFileFolder() {
return outputFolder + File.separatorChar + modelPackage().replace('.', File.separatorChar);
}
@Override
public String getTypeDeclaration(Property p) {
if(p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]";
} }
else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
return getSwaggerType(p) + "(String, " + getTypeDeclaration(inner) + ")"; private static String dropDots(String str) {
return str.replaceAll("\\.", "_");
} }
return super.getTypeDeclaration(p);
}
@Override public CodegenType getTag() {
public String getSwaggerType(Property p) { return CodegenType.CLIENT;
String swaggerType = super.getSwaggerType(p); }
String type = null;
if(typeMapping.containsKey(swaggerType)) { public String getName() {
type = typeMapping.get(swaggerType); return "python";
if(languageSpecificPrimitives.contains(type)) { }
public String getHelp() {
return "Generates a Python client library.";
}
@Override
public String escapeReservedWord(String name) {
return "_" + name;
}
@Override
public String apiFileFolder() {
return outputFolder + File.separatorChar + apiPackage().replace('.', File.separatorChar);
}
public String modelFileFolder() {
return outputFolder + File.separatorChar + modelPackage().replace('.', File.separatorChar);
}
@Override
public String getTypeDeclaration(Property p) {
if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]";
} else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
return getSwaggerType(p) + "(String, " + getTypeDeclaration(inner) + ")";
}
return super.getTypeDeclaration(p);
}
@Override
public String getSwaggerType(Property p) {
String swaggerType = super.getSwaggerType(p);
String type = null;
if (typeMapping.containsKey(swaggerType)) {
type = typeMapping.get(swaggerType);
if (languageSpecificPrimitives.contains(type)) {
return type;
}
} else {
type = toModelName(swaggerType);
}
return type; return type;
}
} else {
type = toModelName(swaggerType);
} }
return type;
}
public String toDefaultValue(Property p) { public String toDefaultValue(Property p) {
// TODO: Support Python def value // TODO: Support Python def value
return "null"; return "null";
} }
@Override @Override
public String toVarName(String name) { public String toVarName(String name) {
// replace - with _ e.g. created-at => created_at // replace - with _ e.g. created-at => created_at
name = name.replaceAll("-", "_"); name = name.replaceAll("-", "_");
// if it's all uppper case, convert to lower case // if it's all uppper case, convert to lower case
if (name.matches("^[A-Z_]*$")) if (name.matches("^[A-Z_]*$")) {
name = name.toLowerCase(); name = name.toLowerCase();
}
// underscore the variable name // underscore the variable name
// petId => pet_id // petId => pet_id
name = underscore(dropDots(name)); name = underscore(dropDots(name));
// for reserved word or word starting with number, append _ // for reserved word or word starting with number, append _
if(reservedWords.contains(name) || name.matches("^\\d.*")) if (reservedWords.contains(name) || name.matches("^\\d.*")) {
name = escapeReservedWord(name); name = escapeReservedWord(name);
}
return name; return name;
} }
private static String dropDots(String str) { @Override
return str.replaceAll("\\.", "_"); public String toParamName(String name) {
} // should be the same as variable name
return toVarName(name);
}
@Override @Override
public String toParamName(String name) { public String toModelName(String name) {
// should be the same as variable name // model name cannot use reserved keyword, e.g. return
return toVarName(name); if (reservedWords.contains(name)) {
} throw new RuntimeException(name + " (reserved word) cannot be used as a model name");
}
@Override // camelize the model name
public String toModelName(String name) { // phone_number => PhoneNumber
// model name cannot use reserved keyword, e.g. return return camelize(name);
if(reservedWords.contains(name)) }
throw new RuntimeException(name + " (reserved word) cannot be used as a model name");
// camelize the model name @Override
// phone_number => PhoneNumber public String toModelFilename(String name) {
return camelize(name); // model name cannot use reserved keyword, e.g. return
} if (reservedWords.contains(name)) {
throw new RuntimeException(name + " (reserved word) cannot be used as a model name");
}
@Override // underscore the model file name
public String toModelFilename(String name) { // PhoneNumber => phone_number
// model name cannot use reserved keyword, e.g. return return underscore(dropDots(name));
if(reservedWords.contains(name)) }
throw new RuntimeException(name + " (reserved word) cannot be used as a model name");
// underscore the model file name @Override
// PhoneNumber => phone_number public String toApiFilename(String name) {
return underscore(dropDots(name)); // replace - with _ e.g. created-at => created_at
} name = name.replaceAll("-", "_");
@Override // e.g. PhoneNumberApi.rb => phone_number_api.rb
public String toApiFilename(String name) { return underscore(name) + "_api";
// replace - with _ e.g. created-at => created_at }
name = name.replaceAll("-", "_");
// e.g. PhoneNumberApi.rb => phone_number_api.rb @Override
return underscore(name) + "_api"; public String toApiName(String name) {
} if (name.length() == 0) {
return "DefaultApi";
}
// e.g. phone_number_api => PhoneNumberApi
return camelize(name) + "Api";
}
@Override @Override
public String toApiName(String name) { public String toApiVarName(String name) {
if(name.length() == 0) if (name.length() == 0) {
return "DefaultApi"; return "default_api";
// e.g. phone_number_api => PhoneNumberApi }
return camelize(name) + "Api"; return underscore(name) + "_api";
} }
@Override @Override
public String toApiVarName(String name) { public String toOperationId(String operationId) {
if(name.length() == 0) // method name cannot use reserved keyword, e.g. return
return "default_api"; if (reservedWords.contains(operationId)) {
return underscore(name) + "_api"; throw new RuntimeException(operationId + " (reserved word) cannot be used as method name");
} }
@Override return underscore(operationId);
public String toOperationId(String operationId) { }
// method name cannot use reserved keyword, e.g. return
if(reservedWords.contains(operationId))
throw new RuntimeException(operationId + " (reserved word) cannot be used as method name");
return underscore(operationId);
}
} }

View File

@ -1,308 +1,324 @@
package io.swagger.codegen.languages; package io.swagger.codegen.languages;
import io.swagger.codegen.*; import io.swagger.codegen.CodegenConfig;
import io.swagger.util.Json; import io.swagger.codegen.CodegenType;
import io.swagger.models.properties.*; import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.BooleanProperty;
import io.swagger.models.properties.DateProperty;
import io.swagger.models.properties.DateTimeProperty;
import io.swagger.models.properties.DecimalProperty;
import io.swagger.models.properties.DoubleProperty;
import io.swagger.models.properties.FloatProperty;
import io.swagger.models.properties.IntegerProperty;
import io.swagger.models.properties.LongProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
import io.swagger.models.properties.RefProperty;
import io.swagger.models.properties.StringProperty;
import java.util.*;
import java.io.File; import java.io.File;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class Qt5CPPGenerator extends DefaultCodegen implements CodegenConfig { public class Qt5CPPGenerator extends DefaultCodegen implements CodegenConfig {
protected Set<String> foundationClasses = new HashSet<String>(); protected final String PREFIX = "SWG";
protected Set<String> foundationClasses = new HashSet<String>();
// source folder where to write the files
protected String sourceFolder = "client";
protected String apiVersion = "1.0.0";
protected Map<String, String> namespaces = new HashMap<String, String>();
protected Set<String> systemIncludes = new HashSet<String>();
// source folder where to write the files public Qt5CPPGenerator() {
protected String sourceFolder = "client"; super();
protected String apiVersion = "1.0.0";
protected final String PREFIX = "SWG";
protected Map<String, String> namespaces = new HashMap<String, String>();
protected Set<String> systemIncludes = new HashSet<String>();
/** // set the output folder here
* Configures the type of generator. outputFolder = "generated-code/qt5cpp";
*
* @return the CodegenType for this generator
* @see io.swagger.codegen.CodegenType
*/
public CodegenType getTag() {
return CodegenType.CLIENT;
}
/** /**
* Configures a friendly name for the generator. This will be used by the generator * Models. You can write model files using the modelTemplateFiles map.
* to select the library with the -l flag. * if you want to create one template for file, you can do so here.
* * for multiple files for model, just put another entry in the `modelTemplateFiles` with
* @return the friendly name for the generator * a different extension
*/ */
public String getName() { modelTemplateFiles.put(
return "qt5cpp"; "model-header.mustache",
} ".h");
/** modelTemplateFiles.put(
* Returns human-friendly help for the generator. Provide the consumer with help "model-body.mustache",
* tips, parameters here ".cpp");
*
* @return A string value for the help message
*/
public String getHelp() {
return "Generates a qt5 C++ client library.";
}
public Qt5CPPGenerator() { /**
super(); * Api classes. You can write classes for each Api file with the apiTemplateFiles map.
* as with models, add multiple entries with different extensions for multiple files per
* class
*/
apiTemplateFiles.put(
"api-header.mustache", // the template to use
".h"); // the extension for each file to write
// set the output folder here apiTemplateFiles.put(
outputFolder = "generated-code/qt5cpp"; "api-body.mustache", // the template to use
".cpp"); // the extension for each file to write
/**
* Template Location. This is the location which templates will be read from. The generator
* will use the resource stream to attempt to read the templates.
*/
templateDir = "qt5cpp";
/**
* Reserved words. Override this with reserved words specific to your language
*/
reservedWords = new HashSet<String>(
Arrays.asList(
"sample1", // replace with static values
"sample2")
);
/**
* Additional Properties. These values can be passed to the templates and
* are available in models, apis, and supporting files
*/
additionalProperties.put("apiVersion", apiVersion);
additionalProperties().put("prefix", PREFIX);
/**
* Language Specific Primitives. These types will not trigger imports by
* the client generator
*/
languageSpecificPrimitives = new HashSet<String>(
Arrays.asList(
"bool",
"qint32",
"qint64")
);
supportingFiles.add(new SupportingFile("helpers-header.mustache", sourceFolder, PREFIX + "Helpers.h"));
supportingFiles.add(new SupportingFile("helpers-body.mustache", sourceFolder, PREFIX + "Helpers.cpp"));
supportingFiles.add(new SupportingFile("HttpRequest.h", sourceFolder, PREFIX + "HttpRequest.h"));
supportingFiles.add(new SupportingFile("HttpRequest.cpp", sourceFolder, PREFIX + "HttpRequest.cpp"));
supportingFiles.add(new SupportingFile("modelFactory.mustache", sourceFolder, PREFIX + "ModelFactory.h"));
supportingFiles.add(new SupportingFile("object.mustache", sourceFolder, PREFIX + "Object.h"));
super.typeMapping = new HashMap<String, String>();
typeMapping.put("Date", "QDate");
typeMapping.put("DateTime", "QDateTime");
typeMapping.put("string", "QString");
typeMapping.put("integer", "qint32");
typeMapping.put("long", "qint64");
typeMapping.put("boolean", "bool");
typeMapping.put("array", "QList");
typeMapping.put("map", "QMap");
typeMapping.put("file", "SWGHttpRequestInputFileElement");
typeMapping.put("object", PREFIX + "Object");
importMapping = new HashMap<String, String>();
importMapping.put("SWGHttpRequestInputFileElement", "#include \"" + PREFIX + "HttpRequest.h\"");
namespaces = new HashMap<String, String>();
foundationClasses.add("QString");
systemIncludes.add("QString");
systemIncludes.add("QList");
}
/** /**
* Models. You can write model files using the modelTemplateFiles map. * Configures the type of generator.
* if you want to create one template for file, you can do so here. *
* for multiple files for model, just put another entry in the `modelTemplateFiles` with * @return the CodegenType for this generator
* a different extension * @see io.swagger.codegen.CodegenType
*/ */
modelTemplateFiles.put( public CodegenType getTag() {
"model-header.mustache", return CodegenType.CLIENT;
".h"); }
modelTemplateFiles.put(
"model-body.mustache",
".cpp");
/** /**
* Api classes. You can write classes for each Api file with the apiTemplateFiles map. * Configures a friendly name for the generator. This will be used by the generator
* as with models, add multiple entries with different extensions for multiple files per * to select the library with the -l flag.
* class *
* @return the friendly name for the generator
*/ */
apiTemplateFiles.put( public String getName() {
"api-header.mustache", // the template to use return "qt5cpp";
".h"); // the extension for each file to write }
apiTemplateFiles.put(
"api-body.mustache", // the template to use
".cpp"); // the extension for each file to write
/** /**
* Template Location. This is the location which templates will be read from. The generator * Returns human-friendly help for the generator. Provide the consumer with help
* will use the resource stream to attempt to read the templates. * tips, parameters here
*
* @return A string value for the help message
*/ */
templateDir = "qt5cpp"; public String getHelp() {
return "Generates a qt5 C++ client library.";
}
@Override
public String toModelImport(String name) {
if (namespaces.containsKey(name)) {
return "using " + namespaces.get(name) + ";";
} else if (systemIncludes.contains(name)) {
return "#include <" + name + ">";
}
return "#include \"" + name + ".h\"";
}
/** /**
* Reserved words. Override this with reserved words specific to your language * Escapes a reserved word as defined in the `reservedWords` array. Handle escaping
* those terms here. This logic is only called if a variable matches the reseved words
*
* @return the escaped term
*/ */
reservedWords = new HashSet<String> ( @Override
Arrays.asList( public String escapeReservedWord(String name) {
"sample1", // replace with static values return "_" + name; // add an underscore to the name
"sample2") }
);
/** /**
* Additional Properties. These values can be passed to the templates and * Location to write model files. You can use the modelPackage() as defined when the class is
* are available in models, apis, and supporting files * instantiated
*/ */
additionalProperties.put("apiVersion", apiVersion); public String modelFileFolder() {
additionalProperties().put("prefix", PREFIX); return outputFolder + "/" + sourceFolder + "/" + modelPackage().replace('.', File.separatorChar);
}
/** /**
* Language Specific Primitives. These types will not trigger imports by * Location to write api files. You can use the apiPackage() as defined when the class is
* the client generator * instantiated
*/ */
languageSpecificPrimitives = new HashSet<String>( @Override
Arrays.asList( public String apiFileFolder() {
"bool", return outputFolder + "/" + sourceFolder + "/" + apiPackage().replace('.', File.separatorChar);
"qint32",
"qint64")
);
supportingFiles.add(new SupportingFile("helpers-header.mustache", sourceFolder, PREFIX + "Helpers.h"));
supportingFiles.add(new SupportingFile("helpers-body.mustache", sourceFolder, PREFIX + "Helpers.cpp"));
supportingFiles.add(new SupportingFile("HttpRequest.h", sourceFolder, PREFIX + "HttpRequest.h"));
supportingFiles.add(new SupportingFile("HttpRequest.cpp", sourceFolder, PREFIX + "HttpRequest.cpp"));
supportingFiles.add(new SupportingFile("modelFactory.mustache", sourceFolder, PREFIX + "ModelFactory.h"));
supportingFiles.add(new SupportingFile("object.mustache", sourceFolder, PREFIX + "Object.h"));
super.typeMapping = new HashMap<String, String>();
typeMapping.put("Date", "QDate");
typeMapping.put("DateTime", "QDateTime");
typeMapping.put("string", "QString");
typeMapping.put("integer", "qint32");
typeMapping.put("long", "qint64");
typeMapping.put("boolean", "bool");
typeMapping.put("array", "QList");
typeMapping.put("map", "QMap");
typeMapping.put("file", "SWGHttpRequestInputFileElement");
typeMapping.put("object", PREFIX + "Object");
importMapping = new HashMap<String, String>();
importMapping.put("SWGHttpRequestInputFileElement", "#include \"" + PREFIX + "HttpRequest.h\"");
namespaces = new HashMap<String, String> ();
foundationClasses.add("QString");
systemIncludes.add("QString");
systemIncludes.add("QList");
}
@Override
public String toModelImport(String name) {
if(namespaces.containsKey(name)) {
return "using " + namespaces.get(name) + ";";
} }
else if(systemIncludes.contains(name)) {
return "#include <" + name + ">"; @Override
public String toModelFilename(String name) {
return PREFIX + initialCaps(name);
} }
return "#include \"" + name + ".h\"";
}
/** @Override
* Escapes a reserved word as defined in the `reservedWords` array. Handle escaping public String toApiFilename(String name) {
* those terms here. This logic is only called if a variable matches the reseved words return PREFIX + initialCaps(name) + "Api";
*
* @return the escaped term
*/
@Override
public String escapeReservedWord(String name) {
return "_" + name; // add an underscore to the name
}
/**
* Location to write model files. You can use the modelPackage() as defined when the class is
* instantiated
*/
public String modelFileFolder() {
return outputFolder + "/" + sourceFolder + "/" + modelPackage().replace('.', File.separatorChar);
}
/**
* Location to write api files. You can use the apiPackage() as defined when the class is
* instantiated
*/
@Override
public String apiFileFolder() {
return outputFolder + "/" + sourceFolder + "/" + apiPackage().replace('.', File.separatorChar);
}
@Override
public String toModelFilename(String name) {
return PREFIX + initialCaps(name);
}
@Override
public String toApiFilename(String name) {
return PREFIX + initialCaps(name) + "Api";
}
/**
* Optional - type declaration. This is a String which is used by the templates to instantiate your
* types. There is typically special handling for different property types
*
* @return a string value used as the `dataType` field for model templates, `returnType` for api templates
*/
@Override
public String getTypeDeclaration(Property p) {
String swaggerType = getSwaggerType(p);
if(p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">*";
} }
else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
return getSwaggerType(p) + "<QString, " + getTypeDeclaration(inner) + ">*";
}
if(foundationClasses.contains(swaggerType))
return swaggerType + "*";
else if(languageSpecificPrimitives.contains(swaggerType))
return toModelName(swaggerType);
else
return swaggerType + "*";
}
@Override /**
public String toDefaultValue(Property p) { * Optional - type declaration. This is a String which is used by the templates to instantiate your
if(p instanceof StringProperty) * types. There is typically special handling for different property types
return "new QString(\"\")"; *
else if (p instanceof BooleanProperty) * @return a string value used as the `dataType` field for model templates, `returnType` for api templates
return "false"; */
else if(p instanceof DateProperty) @Override
return "NULL"; public String getTypeDeclaration(Property p) {
else if(p instanceof DateTimeProperty) String swaggerType = getSwaggerType(p);
return "NULL";
else if (p instanceof DoubleProperty) if (p instanceof ArrayProperty) {
return "0.0"; ArrayProperty ap = (ArrayProperty) p;
else if (p instanceof FloatProperty) Property inner = ap.getItems();
return "0.0f"; return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">*";
else if (p instanceof IntegerProperty) } else if (p instanceof MapProperty) {
return "0"; MapProperty mp = (MapProperty) p;
else if (p instanceof LongProperty) Property inner = mp.getAdditionalProperties();
return "0L"; return getSwaggerType(p) + "<QString, " + getTypeDeclaration(inner) + ">*";
else if (p instanceof DecimalProperty) }
return "0.0"; if (foundationClasses.contains(swaggerType)) {
else if (p instanceof MapProperty) { return swaggerType + "*";
MapProperty ap = (MapProperty) p; } else if (languageSpecificPrimitives.contains(swaggerType)) {
String inner = getSwaggerType(ap.getAdditionalProperties()); return toModelName(swaggerType);
return "new QMap<QString, " + inner + ">()"; } else {
return swaggerType + "*";
}
} }
else if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p; @Override
String inner = getSwaggerType(ap.getItems()); public String toDefaultValue(Property p) {
if(!languageSpecificPrimitives.contains(inner)) { if (p instanceof StringProperty) {
inner += "*"; return "new QString(\"\")";
} } else if (p instanceof BooleanProperty) {
return "new QList<" + inner + ">()"; return "false";
} else if (p instanceof DateProperty) {
return "NULL";
} else if (p instanceof DateTimeProperty) {
return "NULL";
} else if (p instanceof DoubleProperty) {
return "0.0";
} else if (p instanceof FloatProperty) {
return "0.0f";
} else if (p instanceof IntegerProperty) {
return "0";
} else if (p instanceof LongProperty) {
return "0L";
} else if (p instanceof DecimalProperty) {
return "0.0";
} else if (p instanceof MapProperty) {
MapProperty ap = (MapProperty) p;
String inner = getSwaggerType(ap.getAdditionalProperties());
return "new QMap<QString, " + inner + ">()";
} else if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
String inner = getSwaggerType(ap.getItems());
if (!languageSpecificPrimitives.contains(inner)) {
inner += "*";
}
return "new QList<" + inner + ">()";
}
// else
if (p instanceof RefProperty) {
RefProperty rp = (RefProperty) p;
return "new " + toModelName(rp.getSimpleRef()) + "()";
}
return "NULL";
} }
// else
if(p instanceof RefProperty) {
RefProperty rp = (RefProperty) p;
return "new " + toModelName(rp.getSimpleRef()) + "()";
}
return "NULL";
}
/** /**
* Optional - swagger type conversion. This is used to map swagger types in a `Property` into * Optional - swagger type conversion. This is used to map swagger types in a `Property` into
* either language specific types via `typeMapping` or into complex models if there is not a mapping. * either language specific types via `typeMapping` or into complex models if there is not a mapping.
* *
* @return a string value of the type or complex model for this property * @return a string value of the type or complex model for this property
* @see io.swagger.models.properties.Property * @see io.swagger.models.properties.Property
*/ */
@Override @Override
public String getSwaggerType(Property p) { public String getSwaggerType(Property p) {
String swaggerType = super.getSwaggerType(p); String swaggerType = super.getSwaggerType(p);
String type = null; String type = null;
if(typeMapping.containsKey(swaggerType)) { if (typeMapping.containsKey(swaggerType)) {
type = typeMapping.get(swaggerType); type = typeMapping.get(swaggerType);
if(languageSpecificPrimitives.contains(type)) if (languageSpecificPrimitives.contains(type)) {
return toModelName(type);
}
if (foundationClasses.contains(type)) {
return type;
}
} else {
type = swaggerType;
}
return toModelName(type); return toModelName(type);
if(foundationClasses.contains(type))
return type;
} }
else
type = swaggerType;
return toModelName(type);
}
@Override @Override
public String toModelName(String type) { public String toModelName(String type) {
if(typeMapping.keySet().contains(type) || if (typeMapping.keySet().contains(type) ||
typeMapping.values().contains(type) || typeMapping.values().contains(type) ||
importMapping.values().contains(type) || importMapping.values().contains(type) ||
defaultIncludes.contains(type) || defaultIncludes.contains(type) ||
languageSpecificPrimitives.contains(type)) { languageSpecificPrimitives.contains(type)) {
return type; return type;
} else {
return PREFIX + Character.toUpperCase(type.charAt(0)) + type.substring(1);
}
} }
else {
return PREFIX + Character.toUpperCase(type.charAt(0)) + type.substring(1);
}
}
@Override @Override
public String toApiName(String type) { public String toApiName(String type) {
return PREFIX + Character.toUpperCase(type.charAt(0)) + type.substring(1) + "Api"; return PREFIX + Character.toUpperCase(type.charAt(0)) + type.substring(1) + "Api";
} }
} }

View File

@ -1,190 +1,202 @@
package io.swagger.codegen.languages; package io.swagger.codegen.languages;
import io.swagger.codegen.*; import io.swagger.codegen.CodegenConfig;
import io.swagger.models.Operation; import io.swagger.codegen.CodegenOperation;
import io.swagger.models.properties.*; import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
import java.util.*;
import java.io.File; import java.io.File;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
public class RetrofitClientCodegen extends DefaultCodegen implements CodegenConfig { public class RetrofitClientCodegen extends DefaultCodegen implements CodegenConfig {
protected String invokerPackage = "io.swagger.client"; protected String invokerPackage = "io.swagger.client";
protected String groupId = "io.swagger"; protected String groupId = "io.swagger";
protected String artifactId = "swagger-java-client"; protected String artifactId = "swagger-java-client";
protected String artifactVersion = "1.0.0"; protected String artifactVersion = "1.0.0";
protected String sourceFolder = "src/main/java"; protected String sourceFolder = "src/main/java";
public CodegenType getTag() { public RetrofitClientCodegen() {
return CodegenType.CLIENT; super();
} outputFolder = "generated-code/java";
modelTemplateFiles.put("model.mustache", ".java");
apiTemplateFiles.put("api.mustache", ".java");
templateDir = "retrofit";
apiPackage = "io.swagger.client.api";
modelPackage = "io.swagger.client.model";
public String getName() { reservedWords = new HashSet<String>(
return "retrofit"; Arrays.asList(
} "abstract", "continue", "for", "new", "switch", "assert",
"default", "if", "package", "synchronized", "boolean", "do", "goto", "private",
"this", "break", "double", "implements", "protected", "throw", "byte", "else",
"import", "public", "throws", "case", "enum", "instanceof", "return", "transient",
"catch", "extends", "int", "short", "try", "char", "final", "interface", "static",
"void", "class", "finally", "long", "strictfp", "volatile", "const", "float",
"native", "super", "while")
);
public String getHelp() { additionalProperties.put("invokerPackage", invokerPackage);
return "Generates a Retrofit client library."; additionalProperties.put("groupId", groupId);
} additionalProperties.put("artifactId", artifactId);
additionalProperties.put("artifactVersion", artifactVersion);
public RetrofitClientCodegen() { supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml"));
super(); supportingFiles.add(new SupportingFile("service.mustache",
outputFolder = "generated-code/java"; (sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "ServiceGenerator.java"));
modelTemplateFiles.put("model.mustache", ".java");
apiTemplateFiles.put("api.mustache", ".java");
templateDir = "retrofit";
apiPackage = "io.swagger.client.api";
modelPackage = "io.swagger.client.model";
reservedWords = new HashSet<String> ( languageSpecificPrimitives = new HashSet<String>(
Arrays.asList( Arrays.asList(
"abstract", "continue", "for", "new", "switch", "assert", "String",
"default", "if", "package", "synchronized", "boolean", "do", "goto", "private", "boolean",
"this", "break", "double", "implements", "protected", "throw", "byte", "else", "Boolean",
"import", "public", "throws", "case", "enum", "instanceof", "return", "transient", "Double",
"catch", "extends", "int", "short", "try", "char", "final", "interface", "static", "Integer",
"void", "class", "finally", "long", "strictfp", "volatile", "const", "float", "Long",
"native", "super", "while") "Float",
); "Object")
);
additionalProperties.put("invokerPackage", invokerPackage); instantiationTypes.put("array", "ArrayList");
additionalProperties.put("groupId", groupId); instantiationTypes.put("map", "HashMap");
additionalProperties.put("artifactId", artifactId);
additionalProperties.put("artifactVersion", artifactVersion);
supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml"));
supportingFiles.add(new SupportingFile("service.mustache",
(sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "ServiceGenerator.java"));
languageSpecificPrimitives = new HashSet<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().replace('.', File.separatorChar);
}
public String modelFileFolder() {
return outputFolder + "/" + sourceFolder + "/" + modelPackage().replace('.', File.separatorChar);
}
@Override
public String toVarName(String name) {
// replace - with _ e.g. created-at => created_at
name = name.replaceAll("-", "_");
// if it's all uppper case, do nothing
if (name.matches("^[A-Z_]*$"))
return name;
// camelize (lower first character) the variable name
// pet_id => petId
name = camelize(name, true);
// for reserved word or word starting with number, append _
if(reservedWords.contains(name) || name.matches("^\\d.*"))
name = escapeReservedWord(name);
return name;
}
@Override
public String toParamName(String name) {
// should be the same as variable name
return toVarName(name);
}
@Override
public String toModelName(String name) {
// model name cannot use reserved keyword, e.g. return
if(reservedWords.contains(name))
throw new RuntimeException(name + " (reserved word) cannot be used as a model name");
// camelize the model name
// phone_number => PhoneNumber
return camelize(name);
}
@Override
public String toModelFilename(String name) {
// should be the same as the model name
return toModelName(name);
}
@Override
public String getTypeDeclaration(Property p) {
if(p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">";
} }
else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
return getSwaggerType(p) + "<String, " + getTypeDeclaration(inner) + ">"; public CodegenType getTag() {
return CodegenType.CLIENT;
} }
return super.getTypeDeclaration(p);
}
@Override public String getName() {
public String getSwaggerType(Property p) { return "retrofit";
String swaggerType = super.getSwaggerType(p); }
String type = null;
if(typeMapping.containsKey(swaggerType)) { public String getHelp() {
type = typeMapping.get(swaggerType); return "Generates a Retrofit client library.";
if(languageSpecificPrimitives.contains(type)) }
@Override
public String escapeReservedWord(String name) {
return "_" + name;
}
@Override
public String apiFileFolder() {
return outputFolder + "/" + sourceFolder + "/" + apiPackage().replace('.', File.separatorChar);
}
public String modelFileFolder() {
return outputFolder + "/" + sourceFolder + "/" + modelPackage().replace('.', File.separatorChar);
}
@Override
public String toVarName(String name) {
// replace - with _ e.g. created-at => created_at
name = name.replaceAll("-", "_");
// if it's all uppper case, do nothing
if (name.matches("^[A-Z_]*$")) {
return name;
}
// camelize (lower first character) the variable name
// pet_id => petId
name = camelize(name, true);
// for reserved word or word starting with number, append _
if (reservedWords.contains(name) || name.matches("^\\d.*")) {
name = escapeReservedWord(name);
}
return name;
}
@Override
public String toParamName(String name) {
// should be the same as variable name
return toVarName(name);
}
@Override
public String toModelName(String name) {
// model name cannot use reserved keyword, e.g. return
if (reservedWords.contains(name)) {
throw new RuntimeException(name + " (reserved word) cannot be used as a model name");
}
// camelize the model name
// phone_number => PhoneNumber
return camelize(name);
}
@Override
public String toModelFilename(String name) {
// should be the same as the model name
return toModelName(name);
}
@Override
public String getTypeDeclaration(Property p) {
if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">";
} else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
return getSwaggerType(p) + "<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); return toModelName(type);
} }
else
type = swaggerType;
return toModelName(type);
}
@Override @Override
public String toOperationId(String operationId) { public String toOperationId(String operationId) {
// method name cannot use reserved keyword, e.g. return // method name cannot use reserved keyword, e.g. return
if(reservedWords.contains(operationId)) if (reservedWords.contains(operationId)) {
throw new RuntimeException(operationId + " (reserved word) cannot be used as method name"); throw new RuntimeException(operationId + " (reserved word) cannot be used as method name");
return camelize(operationId, true);
}
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.hasConsumes == Boolean.TRUE) {
Map<String, String> firstType = operation.consumes.get(0);
if (firstType != null) {
if ("multipart/form-data".equals(firstType.get("mediaType"))) {
operation.isMultipart = Boolean.TRUE;
}
}
} }
if(operation.returnType == null) {
operation.returnType = "Void"; return camelize(operationId, true);
} }
}
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.hasConsumes == Boolean.TRUE) {
Map<String, String> firstType = operation.consumes.get(0);
if (firstType != null) {
if ("multipart/form-data".equals(firstType.get("mediaType"))) {
operation.isMultipart = Boolean.TRUE;
}
}
}
if (operation.returnType == null) {
operation.returnType = "Void";
}
}
}
return objs;
} }
return objs;
}
} }

View File

@ -1,220 +1,231 @@
package io.swagger.codegen.languages; package io.swagger.codegen.languages;
import io.swagger.codegen.*; import io.swagger.codegen.CodegenConfig;
import io.swagger.util.Json; import io.swagger.codegen.CodegenType;
import io.swagger.models.properties.*; import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
import java.util.*;
import java.io.File; import java.io.File;
import java.util.Arrays;
import java.util.HashSet;
public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig {
protected String gemName = "swagger_client"; protected String gemName = "swagger_client";
protected String moduleName = null; protected String moduleName = null;
protected String libFolder = "lib"; protected String libFolder = "lib";
public CodegenType getTag() { public RubyClientCodegen() {
return CodegenType.CLIENT; super();
} moduleName = generateModuleName();
modelPackage = gemName + "/models";
apiPackage = gemName + "/api";
outputFolder = "generated-code" + File.separatorChar + "ruby";
modelTemplateFiles.put("model.mustache", ".rb");
apiTemplateFiles.put("api.mustache", ".rb");
templateDir = "ruby";
public String getName() { typeMapping.clear();
return "ruby"; languageSpecificPrimitives.clear();
}
public String getHelp() { reservedWords = new HashSet<String>(
return "Generates a Ruby client library."; Arrays.asList(
} "__FILE__", "and", "def", "end", "in", "or", "self", "unless", "__LINE__",
"begin", "defined?", "ensure", "module", "redo", "super", "until", "BEGIN",
"break", "do", "false", "next", "rescue", "then", "when", "END", "case",
"else", "for", "nil", "retry", "true", "while", "alias", "class", "elsif",
"if", "not", "return", "undef", "yield")
);
/** additionalProperties.put("gemName", gemName);
* Generate Ruby module name from the gem name, e.g. use "SwaggerClient" for "swagger_client". additionalProperties.put("moduleName", moduleName);
*/
public String generateModuleName() {
return camelize(gemName.replaceAll("[^\\w]+", "_"));
}
public RubyClientCodegen() { languageSpecificPrimitives.add("int");
super(); languageSpecificPrimitives.add("array");
moduleName = generateModuleName(); languageSpecificPrimitives.add("map");
modelPackage = gemName + "/models"; languageSpecificPrimitives.add("string");
apiPackage = gemName + "/api"; languageSpecificPrimitives.add("DateTime");
outputFolder = "generated-code" + File.separatorChar + "ruby";
modelTemplateFiles.put("model.mustache", ".rb");
apiTemplateFiles.put("api.mustache", ".rb");
templateDir = "ruby";
typeMapping.clear(); typeMapping.put("long", "int");
languageSpecificPrimitives.clear(); typeMapping.put("integer", "int");
typeMapping.put("Array", "array");
typeMapping.put("String", "string");
typeMapping.put("List", "array");
typeMapping.put("map", "map");
reservedWords = new HashSet<String> ( String baseFolder = "lib" + File.separatorChar + gemName;
Arrays.asList( String swaggerFolder = baseFolder + File.separatorChar + "swagger";
"__FILE__", "and", "def", "end", "in", "or", "self", "unless", "__LINE__", String modelFolder = baseFolder + File.separatorChar + "models";
"begin", "defined?", "ensure", "module", "redo", "super", "until", "BEGIN", supportingFiles.add(new SupportingFile("swagger_client.gemspec.mustache", "", gemName + ".gemspec"));
"break", "do", "false", "next", "rescue", "then", "when", "END", "case", supportingFiles.add(new SupportingFile("swagger_client.mustache", "lib", gemName + ".rb"));
"else", "for", "nil", "retry", "true", "while", "alias", "class", "elsif", supportingFiles.add(new SupportingFile("monkey.mustache", baseFolder, "monkey.rb"));
"if", "not", "return", "undef", "yield") supportingFiles.add(new SupportingFile("swagger.mustache", baseFolder, "swagger.rb"));
); supportingFiles.add(new SupportingFile("swagger" + File.separatorChar + "request.mustache", swaggerFolder, "request.rb"));
supportingFiles.add(new SupportingFile("swagger" + File.separatorChar + "response.mustache", swaggerFolder, "response.rb"));
additionalProperties.put("gemName", gemName); supportingFiles.add(new SupportingFile("swagger" + File.separatorChar + "version.mustache", swaggerFolder, "version.rb"));
additionalProperties.put("moduleName", moduleName); supportingFiles.add(new SupportingFile("swagger" + File.separatorChar + "configuration.mustache", swaggerFolder, "configuration.rb"));
supportingFiles.add(new SupportingFile("base_object.mustache", modelFolder, "base_object.rb"));
languageSpecificPrimitives.add("int");
languageSpecificPrimitives.add("array");
languageSpecificPrimitives.add("map");
languageSpecificPrimitives.add("string");
languageSpecificPrimitives.add("DateTime");
typeMapping.put("long", "int");
typeMapping.put("integer", "int");
typeMapping.put("Array", "array");
typeMapping.put("String", "string");
typeMapping.put("List", "array");
typeMapping.put("map", "map");
String baseFolder = "lib" + File.separatorChar + gemName;
String swaggerFolder = baseFolder + File.separatorChar + "swagger";
String modelFolder = baseFolder + File.separatorChar + "models";
supportingFiles.add(new SupportingFile("swagger_client.gemspec.mustache", "", gemName + ".gemspec"));
supportingFiles.add(new SupportingFile("swagger_client.mustache", "lib", gemName + ".rb"));
supportingFiles.add(new SupportingFile("monkey.mustache", baseFolder, "monkey.rb"));
supportingFiles.add(new SupportingFile("swagger.mustache", baseFolder, "swagger.rb"));
supportingFiles.add(new SupportingFile("swagger" + File.separatorChar + "request.mustache", swaggerFolder, "request.rb"));
supportingFiles.add(new SupportingFile("swagger" + File.separatorChar + "response.mustache", swaggerFolder, "response.rb"));
supportingFiles.add(new SupportingFile("swagger" + File.separatorChar + "version.mustache", swaggerFolder, "version.rb"));
supportingFiles.add(new SupportingFile("swagger" + File.separatorChar + "configuration.mustache", swaggerFolder, "configuration.rb"));
supportingFiles.add(new SupportingFile("base_object.mustache", modelFolder, "base_object.rb"));
}
@Override
public String escapeReservedWord(String name) {
return "_" + name;
}
@Override
public String apiFileFolder() {
return outputFolder + File.separatorChar + "lib" + File.separatorChar + gemName + File.separatorChar + "api";
}
public String modelFileFolder() {
return outputFolder + File.separatorChar + "lib" + File.separatorChar + gemName + File.separatorChar + "models";
}
@Override
public String getTypeDeclaration(Property p) {
if(p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]";
} }
else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
return getSwaggerType(p) + "[string," + getTypeDeclaration(inner) + "]";
}
return super.getTypeDeclaration(p);
}
@Override public CodegenType getTag() {
public String getSwaggerType(Property p) { return CodegenType.CLIENT;
String swaggerType = super.getSwaggerType(p); }
String type = null;
if(typeMapping.containsKey(swaggerType)) { public String getName() {
type = typeMapping.get(swaggerType); return "ruby";
if(languageSpecificPrimitives.contains(type)) { }
public String getHelp() {
return "Generates a Ruby client library.";
}
/**
* Generate Ruby module name from the gem name, e.g. use "SwaggerClient" for "swagger_client".
*/
public String generateModuleName() {
return camelize(gemName.replaceAll("[^\\w]+", "_"));
}
@Override
public String escapeReservedWord(String name) {
return "_" + name;
}
@Override
public String apiFileFolder() {
return outputFolder + File.separatorChar + "lib" + File.separatorChar + gemName + File.separatorChar + "api";
}
public String modelFileFolder() {
return outputFolder + File.separatorChar + "lib" + File.separatorChar + gemName + File.separatorChar + "models";
}
@Override
public String getTypeDeclaration(Property p) {
if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]";
} else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
return getSwaggerType(p) + "[string," + getTypeDeclaration(inner) + "]";
}
return super.getTypeDeclaration(p);
}
@Override
public String getSwaggerType(Property p) {
String swaggerType = super.getSwaggerType(p);
String type = null;
if (typeMapping.containsKey(swaggerType)) {
type = typeMapping.get(swaggerType);
if (languageSpecificPrimitives.contains(type)) {
return type;
}
} else {
type = swaggerType;
}
if (type == null) {
return null;
}
return type; return type;
}
} }
else
type = swaggerType;
if(type == null)
return null;
return type;
}
public String toDefaultValue(Property p) { public String toDefaultValue(Property p) {
return "null"; return "null";
} }
@Override @Override
public String toVarName(String name) { public String toVarName(String name) {
// replace - with _ e.g. created-at => created_at // replace - with _ e.g. created-at => created_at
name = name.replaceAll("-", "_"); name = name.replaceAll("-", "_");
// if it's all uppper case, convert to lower case // if it's all uppper case, convert to lower case
if (name.matches("^[A-Z_]*$")) if (name.matches("^[A-Z_]*$")) {
name = name.toLowerCase(); name = name.toLowerCase();
}
// camelize (lower first character) the variable name // camelize (lower first character) the variable name
// petId => pet_id // petId => pet_id
name = underscore(name); name = underscore(name);
// for reserved word or word starting with number, append _ // for reserved word or word starting with number, append _
if(reservedWords.contains(name) || name.matches("^\\d.*")) if (reservedWords.contains(name) || name.matches("^\\d.*")) {
name = escapeReservedWord(name); name = escapeReservedWord(name);
}
return name; return name;
} }
@Override @Override
public String toParamName(String name) { public String toParamName(String name) {
// should be the same as variable name // should be the same as variable name
return toVarName(name); return toVarName(name);
} }
@Override @Override
public String toModelName(String name) { public String toModelName(String name) {
// model name cannot use reserved keyword, e.g. return // model name cannot use reserved keyword, e.g. return
if(reservedWords.contains(name)) if (reservedWords.contains(name)) {
throw new RuntimeException(name + " (reserved word) cannot be used as a model name"); throw new RuntimeException(name + " (reserved word) cannot be used as a model name");
}
// camelize the model name // camelize the model name
// phone_number => PhoneNumber // phone_number => PhoneNumber
return camelize(name); return camelize(name);
} }
@Override @Override
public String toModelFilename(String name) { public String toModelFilename(String name) {
// model name cannot use reserved keyword, e.g. return // model name cannot use reserved keyword, e.g. return
if(reservedWords.contains(name)) if (reservedWords.contains(name)) {
throw new RuntimeException(name + " (reserved word) cannot be used as a model name"); throw new RuntimeException(name + " (reserved word) cannot be used as a model name");
}
// underscore the model file name // underscore the model file name
// PhoneNumber.rb => phone_number.rb // PhoneNumber.rb => phone_number.rb
return underscore(name); return underscore(name);
} }
@Override @Override
public String toApiFilename(String name) { public String toApiFilename(String name) {
// replace - with _ e.g. created-at => created_at // replace - with _ e.g. created-at => created_at
name = name.replaceAll("-", "_"); name = name.replaceAll("-", "_");
// e.g. PhoneNumberApi.rb => phone_number_api.rb // e.g. PhoneNumberApi.rb => phone_number_api.rb
return underscore(name) + "_api"; return underscore(name) + "_api";
} }
@Override @Override
public String toApiName(String name) { public String toApiName(String name) {
if(name.length() == 0) if (name.length() == 0) {
return "DefaultApi"; return "DefaultApi";
// e.g. phone_number_api => PhoneNumberApi }
return camelize(name) + "Api"; // e.g. phone_number_api => PhoneNumberApi
} return camelize(name) + "Api";
}
@Override @Override
public String toOperationId(String operationId) { public String toOperationId(String operationId) {
// method name cannot use reserved keyword, e.g. return // method name cannot use reserved keyword, e.g. return
if(reservedWords.contains(operationId)) if (reservedWords.contains(operationId)) {
throw new RuntimeException(operationId + " (reserved word) cannot be used as method name"); throw new RuntimeException(operationId + " (reserved word) cannot be used as method name");
}
return underscore(operationId); return underscore(operationId);
} }
@Override @Override
public String toModelImport(String name) { public String toModelImport(String name) {
return modelPackage() + "/" + toModelFilename(name); return modelPackage() + "/" + toModelFilename(name);
} }
@Override @Override
public String toApiImport(String name) { public String toApiImport(String name) {
return apiPackage() + "/" + toApiFilename(name); return apiPackage() + "/" + toApiFilename(name);
} }
} }

View File

@ -1,203 +1,217 @@
package io.swagger.codegen.languages; package io.swagger.codegen.languages;
import io.swagger.codegen.*; import io.swagger.codegen.CodegenConfig;
import io.swagger.models.properties.*; import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.BooleanProperty;
import io.swagger.models.properties.DateProperty;
import io.swagger.models.properties.DateTimeProperty;
import io.swagger.models.properties.DoubleProperty;
import io.swagger.models.properties.FloatProperty;
import io.swagger.models.properties.IntegerProperty;
import io.swagger.models.properties.LongProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
import io.swagger.models.properties.StringProperty;
import java.util.*;
import java.io.File; import java.io.File;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
public class ScalaClientCodegen extends DefaultCodegen implements CodegenConfig { public class ScalaClientCodegen extends DefaultCodegen implements CodegenConfig {
protected String invokerPackage = "io.swagger.client"; protected String invokerPackage = "io.swagger.client";
protected String groupId = "io.swagger"; protected String groupId = "io.swagger";
protected String artifactId = "swagger-scala-client"; protected String artifactId = "swagger-scala-client";
protected String artifactVersion = "1.0.0"; protected String artifactVersion = "1.0.0";
protected String sourceFolder = "src/main/scala"; protected String sourceFolder = "src/main/scala";
protected String authScheme = ""; protected String authScheme = "";
protected boolean authPreemptive = false; protected boolean authPreemptive = false;
protected boolean asyncHttpClient = !authScheme.isEmpty(); protected boolean asyncHttpClient = !authScheme.isEmpty();
public CodegenType getTag() { public ScalaClientCodegen() {
return CodegenType.CLIENT; super();
} outputFolder = "generated-code/scala";
modelTemplateFiles.put("model.mustache", ".scala");
public String getName() { apiTemplateFiles.put("api.mustache", ".scala");
return "scala"; templateDir = "scala";
} apiPackage = "io.swagger.client.api";
modelPackage = "io.swagger.client.model";
public String getHelp() { reservedWords = new HashSet<String>(
return "Generates a Scala client library."; Arrays.asList(
} "abstract", "case", "catch", "class", "def", "do", "else", "extends",
"false", "final", "finally", "for", "forSome", "if", "implicit",
"import", "lazy", "match", "new", "null", "object", "override", "package",
"private", "protected", "return", "sealed", "super", "this", "throw",
"trait", "try", "true", "type", "val", "var", "while", "with", "yield")
);
public ScalaClientCodegen() { additionalProperties.put("invokerPackage", invokerPackage);
super(); additionalProperties.put("groupId", groupId);
outputFolder = "generated-code/scala"; additionalProperties.put("artifactId", artifactId);
modelTemplateFiles.put("model.mustache", ".scala"); additionalProperties.put("artifactVersion", artifactVersion);
apiTemplateFiles.put("api.mustache", ".scala"); additionalProperties.put("asyncHttpClient", asyncHttpClient);
templateDir = "scala"; additionalProperties.put("authScheme", authScheme);
apiPackage = "io.swagger.client.api"; additionalProperties.put("authPreemptive", authPreemptive);
modelPackage = "io.swagger.client.model";
reservedWords = new HashSet<String> ( supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml"));
Arrays.asList( supportingFiles.add(new SupportingFile("apiInvoker.mustache",
"abstract", "case", "catch", "class", "def", "do", "else", "extends", (sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "ApiInvoker.scala"));
"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); importMapping.remove("List");
additionalProperties.put("groupId", groupId); importMapping.remove("Set");
additionalProperties.put("artifactId", artifactId); importMapping.remove("Map");
additionalProperties.put("artifactVersion", artifactVersion);
additionalProperties.put("asyncHttpClient", asyncHttpClient);
additionalProperties.put("authScheme", authScheme);
additionalProperties.put("authPreemptive", authPreemptive);
supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml")); importMapping.put("DateTime", "org.joda.time.DateTime");
supportingFiles.add(new SupportingFile("apiInvoker.mustache", importMapping.put("ListBuffer", "scala.collections.mutable.ListBuffer");
(sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "ApiInvoker.scala"));
importMapping.remove("List"); typeMapping = new HashMap<String, String>();
importMapping.remove("Set"); typeMapping.put("enum", "NSString");
importMapping.remove("Map"); typeMapping.put("array", "List");
typeMapping.put("set", "Set");
typeMapping.put("boolean", "Boolean");
typeMapping.put("string", "String");
typeMapping.put("int", "Int");
typeMapping.put("long", "Long");
typeMapping.put("float", "Float");
typeMapping.put("byte", "Byte");
typeMapping.put("short", "Short");
typeMapping.put("char", "Char");
typeMapping.put("long", "Long");
typeMapping.put("double", "Double");
typeMapping.put("object", "Any");
typeMapping.put("file", "File");
importMapping.put("DateTime", "org.joda.time.DateTime"); languageSpecificPrimitives = new HashSet<String>(
importMapping.put("ListBuffer", "scala.collections.mutable.ListBuffer"); Arrays.asList(
"String",
typeMapping = new HashMap<String, String>(); "boolean",
typeMapping.put("enum", "NSString"); "Boolean",
typeMapping.put("array", "List"); "Double",
typeMapping.put("set", "Set"); "Int",
typeMapping.put("boolean", "Boolean"); "Long",
typeMapping.put("string", "String"); "Float",
typeMapping.put("int", "Int"); "Object",
typeMapping.put("long", "Long"); "List",
typeMapping.put("float", "Float"); "Map")
typeMapping.put("byte", "Byte"); );
typeMapping.put("short", "Short"); instantiationTypes.put("array", "ListBuffer");
typeMapping.put("char", "Char"); instantiationTypes.put("map", "HashMap");
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().replace('.', File.separatorChar);
}
public String modelFileFolder() {
return outputFolder + "/" + sourceFolder + "/" + modelPackage().replace('.', File.separatorChar);
}
@Override
public String getTypeDeclaration(Property p) {
if(p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]";
} }
else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
return getSwaggerType(p) + "[String, " + getTypeDeclaration(inner) + "]"; public CodegenType getTag() {
return CodegenType.CLIENT;
} }
return super.getTypeDeclaration(p);
}
@Override public String getName() {
public String getSwaggerType(Property p) { return "scala";
String swaggerType = super.getSwaggerType(p); }
String type = null;
if(typeMapping.containsKey(swaggerType)) { public String getHelp() {
type = typeMapping.get(swaggerType); return "Generates a Scala client library.";
if(languageSpecificPrimitives.contains(type)) }
@Override
public String escapeReservedWord(String name) {
return "_" + name;
}
@Override
public String apiFileFolder() {
return outputFolder + "/" + sourceFolder + "/" + apiPackage().replace('.', File.separatorChar);
}
public String modelFileFolder() {
return outputFolder + "/" + sourceFolder + "/" + modelPackage().replace('.', File.separatorChar);
}
@Override
public String getTypeDeclaration(Property p) {
if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]";
} else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
return getSwaggerType(p) + "[String, " + getTypeDeclaration(inner) + "]";
}
return super.getTypeDeclaration(p);
}
@Override
public String getSwaggerType(Property p) {
String swaggerType = super.getSwaggerType(p);
String type = null;
if (typeMapping.containsKey(swaggerType)) {
type = typeMapping.get(swaggerType);
if (languageSpecificPrimitives.contains(type)) {
return toModelName(type);
}
} else {
type = swaggerType;
}
return toModelName(type); return toModelName(type);
} }
else
type = swaggerType;
return toModelName(type);
}
@Override @Override
public String toInstantiationType(Property p) { public String toInstantiationType(Property p) {
if (p instanceof MapProperty) { if (p instanceof MapProperty) {
MapProperty ap = (MapProperty) p; MapProperty ap = (MapProperty) p;
String inner = getSwaggerType(ap.getAdditionalProperties()); String inner = getSwaggerType(ap.getAdditionalProperties());
return instantiationTypes.get("map") + "[String, " + inner + "]"; return instantiationTypes.get("map") + "[String, " + inner + "]";
} else if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
String inner = getSwaggerType(ap.getItems());
return instantiationTypes.get("array") + "[" + inner + "]";
} else {
return null;
}
} }
else if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p; public String toDefaultValue(Property p) {
String inner = getSwaggerType(ap.getItems()); if (p instanceof StringProperty) {
return instantiationTypes.get("array") + "[" + inner + "]"; return "null";
} else if (p instanceof BooleanProperty) {
return "null";
} else if (p instanceof DateProperty) {
return "null";
} else if (p instanceof DateTimeProperty) {
return "null";
} else if (p instanceof DoubleProperty) {
return "null";
} else if (p instanceof FloatProperty) {
return "null";
} else if (p instanceof IntegerProperty) {
return "null";
} else if (p instanceof LongProperty) {
return "null";
} else if (p instanceof MapProperty) {
MapProperty ap = (MapProperty) p;
String inner = getSwaggerType(ap.getAdditionalProperties());
return "new HashMap[String, " + inner + "]() ";
} else if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
String inner = getSwaggerType(ap.getItems());
return "new ListBuffer[" + inner + "]() ";
} else {
return "null";
}
} }
else
return null;
}
public String toDefaultValue(Property p) {
if(p instanceof StringProperty) @Override
return "null"; public String toOperationId(String operationId) {
else if (p instanceof BooleanProperty) // method name cannot use reserved keyword, e.g. return
return "null"; if (reservedWords.contains(operationId)) {
else if(p instanceof DateProperty) throw new RuntimeException(operationId + " (reserved word) cannot be used as method name");
return "null"; }
else if(p instanceof DateTimeProperty)
return "null"; return camelize(operationId, true);
else if (p instanceof DoubleProperty)
return "null";
else if (p instanceof FloatProperty)
return "null";
else if (p instanceof IntegerProperty)
return "null";
else if (p instanceof LongProperty)
return "null";
else if (p instanceof MapProperty) {
MapProperty ap = (MapProperty) p;
String inner = getSwaggerType(ap.getAdditionalProperties());
return "new HashMap[String, " + inner + "]() ";
} }
else if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
String inner = getSwaggerType(ap.getItems());
return "new ListBuffer[" + inner + "]() ";
}
else
return "null";
}
@Override
public String toOperationId(String operationId) {
// method name cannot use reserved keyword, e.g. return
if(reservedWords.contains(operationId))
throw new RuntimeException(operationId + " (reserved word) cannot be used as method name");
return camelize(operationId, true);
}
} }

View File

@ -1,178 +1,187 @@
package io.swagger.codegen.languages; package io.swagger.codegen.languages;
import io.swagger.codegen.*; import io.swagger.codegen.CodegenConfig;
import io.swagger.models.properties.*; import io.swagger.codegen.CodegenOperation;
import io.swagger.util.Json; import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
import java.util.*;
import java.io.File; import java.io.File;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
public class ScalatraServerCodegen extends DefaultCodegen implements CodegenConfig { public class ScalatraServerCodegen extends DefaultCodegen implements CodegenConfig {
protected String invokerPackage = "io.swagger.client"; protected String invokerPackage = "io.swagger.client";
protected String groupId = "io.swagger"; protected String groupId = "io.swagger";
protected String artifactId = "swagger-client"; protected String artifactId = "swagger-client";
protected String artifactVersion = "1.0.0"; protected String artifactVersion = "1.0.0";
protected String sourceFolder = "src/main/scala"; protected String sourceFolder = "src/main/scala";
public CodegenType getTag() { public ScalatraServerCodegen() {
return CodegenType.SERVER; super();
} outputFolder = "generated-code/scalatra";
modelTemplateFiles.put("model.mustache", ".scala");
apiTemplateFiles.put("api.mustache", ".scala");
templateDir = "scalatra";
apiPackage = "com.wordnik.client.api";
modelPackage = "com.wordnik.client.model";
public String getName() { reservedWords = new HashSet<String>(
return "scalatra"; Arrays.asList(
} "abstract", "continue", "for", "new", "switch", "assert",
"default", "if", "package", "synchronized", "boolean", "do", "goto", "private",
"this", "break", "double", "implements", "protected", "throw", "byte", "else",
"import", "public", "throws", "case", "enum", "instanceof", "return", "transient",
"catch", "extends", "int", "short", "try", "char", "final", "interface", "static",
"void", "class", "finally", "long", "strictfp", "volatile", "const", "float",
"native", "super", "while")
);
public String getHelp() { defaultIncludes = new HashSet<String>(
return "Generates a Scala server application with Scalatra."; Arrays.asList("double",
} "Int",
"Long",
"Float",
"Double",
"char",
"float",
"String",
"boolean",
"Boolean",
"Double",
"Integer",
"Long",
"Float",
"List",
"Set",
"Map")
);
public ScalatraServerCodegen() { typeMapping.put("integer", "Int");
super(); typeMapping.put("long", "Long");
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> ( additionalProperties.put("appName", "Swagger Sample");
Arrays.asList( additionalProperties.put("appName", "Swagger Sample");
"abstract", "continue", "for", "new", "switch", "assert", additionalProperties.put("appDescription", "A sample swagger server");
"default", "if", "package", "synchronized", "boolean", "do", "goto", "private", additionalProperties.put("infoUrl", "http://swagger.io");
"this", "break", "double", "implements", "protected", "throw", "byte", "else", additionalProperties.put("infoEmail", "apiteam@swagger.io");
"import", "public", "throws", "case", "enum", "instanceof", "return", "transient", additionalProperties.put("licenseInfo", "All rights reserved");
"catch", "extends", "int", "short", "try", "char", "final", "interface", "static", additionalProperties.put("licenseUrl", "http://apache.org/licenses/LICENSE-2.0.html");
"void", "class", "finally", "long", "strictfp", "volatile", "const", "float", additionalProperties.put("invokerPackage", invokerPackage);
"native", "super", "while") additionalProperties.put("groupId", groupId);
); additionalProperties.put("artifactId", artifactId);
additionalProperties.put("artifactVersion", artifactVersion);
defaultIncludes = new HashSet<String>( supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
Arrays.asList("double", supportingFiles.add(new SupportingFile("build.sbt", "", "build.sbt"));
"Int", supportingFiles.add(new SupportingFile("web.xml", "/src/main/webapp/WEB-INF", "web.xml"));
"Long", supportingFiles.add(new SupportingFile("JettyMain.scala", sourceFolder, "JettyMain.scala"));
"Float", supportingFiles.add(new SupportingFile("Bootstrap.mustache", sourceFolder, "ScalatraBootstrap.scala"));
"Double", supportingFiles.add(new SupportingFile("ServletApp.mustache", sourceFolder, "ServletApp.scala"));
"char", supportingFiles.add(new SupportingFile("project/build.properties", "project", "build.properties"));
"float", supportingFiles.add(new SupportingFile("project/plugins.sbt", "project", "plugins.sbt"));
"String", supportingFiles.add(new SupportingFile("sbt", "", "sbt"));
"boolean",
"Boolean",
"Double",
"Integer",
"Long",
"Float",
"List",
"Set",
"Map")
);
typeMapping.put("integer", "Int"); languageSpecificPrimitives = new HashSet<String>(
typeMapping.put("long", "Long"); Arrays.asList(
"String",
"boolean",
"Boolean",
"Double",
"Integer",
"Long",
"Float",
"Object")
);
instantiationTypes.put("array", "ArrayList");
instantiationTypes.put("map", "HashMap");
additionalProperties.put("appName", "Swagger Sample"); importMapping = new HashMap<String, String>();
additionalProperties.put("appName", "Swagger Sample"); importMapping.put("BigDecimal", "java.math.BigDecimal");
additionalProperties.put("appDescription", "A sample swagger server"); importMapping.put("UUID", "java.util.UUID");
additionalProperties.put("infoUrl", "http://swagger.io"); importMapping.put("File", "java.io.File");
additionalProperties.put("infoEmail", "apiteam@swagger.io"); importMapping.put("Date", "java.util.Date");
additionalProperties.put("licenseInfo", "All rights reserved"); importMapping.put("Timestamp", "java.sql.Timestamp");
additionalProperties.put("licenseUrl", "http://apache.org/licenses/LICENSE-2.0.html"); importMapping.put("Map", "java.util.Map");
additionalProperties.put("invokerPackage", invokerPackage); importMapping.put("HashMap", "java.util.HashMap");
additionalProperties.put("groupId", groupId); importMapping.put("Array", "java.util.List");
additionalProperties.put("artifactId", artifactId); importMapping.put("ArrayList", "java.util.ArrayList");
additionalProperties.put("artifactVersion", artifactVersion); importMapping.put("DateTime", "org.joda.time.DateTime");
importMapping.put("LocalDateTime", "org.joda.time.LocalDateTime");
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); importMapping.put("LocalDate", "org.joda.time.LocalDate");
supportingFiles.add(new SupportingFile("build.sbt", "", "build.sbt")); importMapping.put("LocalTime", "org.joda.time.LocalTime");
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().replace('.', File.separatorChar);
}
public String modelFileFolder() {
return outputFolder + "/" + sourceFolder + "/" + modelPackage().replace('.', File.separatorChar);
}
@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;
}
public CodegenType getTag() {
@Override return CodegenType.SERVER;
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) + "]"; public String getName() {
return "scalatra";
} }
return super.getTypeDeclaration(p);
}
@Override public String getHelp() {
public String getSwaggerType(Property p) { return "Generates a Scala server application with Scalatra.";
String swaggerType = super.getSwaggerType(p); }
String type = null;
if(typeMapping.containsKey(swaggerType)) { @Override
type = typeMapping.get(swaggerType); public String escapeReservedWord(String name) {
if(languageSpecificPrimitives.contains(type)) return "_" + name;
}
@Override
public String apiFileFolder() {
return outputFolder + "/" + sourceFolder + "/" + apiPackage().replace('.', File.separatorChar);
}
public String modelFileFolder() {
return outputFolder + "/" + sourceFolder + "/" + modelPackage().replace('.', File.separatorChar);
}
@Override
public Map<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); return toModelName(type);
} }
else
type = swaggerType;
return toModelName(type);
}
} }

View File

@ -1,13 +1,20 @@
package io.swagger.codegen.languages; package io.swagger.codegen.languages;
import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenOperation;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.SupportingFile;
import io.swagger.models.Operation; import io.swagger.models.Operation;
import io.swagger.models.Path; import io.swagger.models.properties.ArrayProperty;
import io.swagger.util.Json; import io.swagger.models.properties.MapProperty;
import io.swagger.codegen.*; import io.swagger.models.properties.Property;
import io.swagger.models.properties.*;
import java.util.*;
import java.io.File; import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
public class SpringMVCServerCodegen extends JavaClientCodegen implements CodegenConfig { public class SpringMVCServerCodegen extends JavaClientCodegen implements CodegenConfig {
protected String invokerPackage = "io.swagger.api"; protected String invokerPackage = "io.swagger.api";
@ -19,18 +26,6 @@ public class SpringMVCServerCodegen extends JavaClientCodegen implements Codegen
protected String configPackage = ""; protected String configPackage = "";
public CodegenType getTag() {
return CodegenType.SERVER;
}
public String getName() {
return "spring-mvc";
}
public String getHelp() {
return "Generates a Java Spring-MVC Server application using the SpringFox integration.";
}
public SpringMVCServerCodegen() { public SpringMVCServerCodegen() {
super.processOpts(); super.processOpts();
outputFolder = "generated-code/javaSpringMVC"; outputFolder = "generated-code/javaSpringMVC";
@ -51,17 +46,29 @@ public class SpringMVCServerCodegen extends JavaClientCodegen implements Codegen
additionalProperties.put("configPackage", configPackage); additionalProperties.put("configPackage", configPackage);
languageSpecificPrimitives = new HashSet<String>( languageSpecificPrimitives = new HashSet<String>(
Arrays.asList( Arrays.asList(
"String", "String",
"boolean", "boolean",
"Boolean", "Boolean",
"Double", "Double",
"Integer", "Integer",
"Long", "Long",
"Float") "Float")
); );
} }
public CodegenType getTag() {
return CodegenType.SERVER;
}
public String getName() {
return "spring-mvc";
}
public String getHelp() {
return "Generates a Java Spring-MVC Server application using the SpringFox integration.";
}
@Override @Override
public void processOpts() { public void processOpts() {
super.processOpts(); super.processOpts();
@ -93,12 +100,11 @@ public class SpringMVCServerCodegen extends JavaClientCodegen implements Codegen
@Override @Override
public String getTypeDeclaration(Property p) { public String getTypeDeclaration(Property p) {
if(p instanceof ArrayProperty) { if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p; ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems(); Property inner = ap.getItems();
return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">"; return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">";
} } else if (p instanceof MapProperty) {
else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p; MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties(); Property inner = mp.getAdditionalProperties();
@ -110,21 +116,24 @@ public class SpringMVCServerCodegen extends JavaClientCodegen implements Codegen
@Override @Override
public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, Map<String, List<CodegenOperation>> operations) { public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, Map<String, List<CodegenOperation>> operations) {
String basePath = resourcePath; String basePath = resourcePath;
if(basePath.startsWith("/")) if (basePath.startsWith("/")) {
basePath = basePath.substring(1); basePath = basePath.substring(1);
}
int pos = basePath.indexOf("/"); int pos = basePath.indexOf("/");
if(pos > 0) if (pos > 0) {
basePath = basePath.substring(0, pos); basePath = basePath.substring(0, pos);
}
if(basePath == "") if (basePath == "") {
basePath = "default"; basePath = "default";
else { } else {
if(co.path.startsWith("/" + basePath)) if (co.path.startsWith("/" + basePath)) {
co.path = co.path.substring(("/" + basePath).length()); co.path = co.path.substring(("/" + basePath).length());
}
co.subresourceOperation = !co.path.isEmpty(); co.subresourceOperation = !co.path.isEmpty();
} }
List<CodegenOperation> opList = operations.get(basePath); List<CodegenOperation> opList = operations.get(basePath);
if(opList == null) { if (opList == null) {
opList = new ArrayList<CodegenOperation>(); opList = new ArrayList<CodegenOperation>();
operations.put(basePath, opList); operations.put(basePath, opList);
} }
@ -133,32 +142,30 @@ public class SpringMVCServerCodegen extends JavaClientCodegen implements Codegen
} }
public Map<String, Object> postProcessOperations(Map<String, Object> objs) { public Map<String, Object> postProcessOperations(Map<String, Object> objs) {
Map<String, Object> operations = (Map<String, Object>)objs.get("operations"); Map<String, Object> operations = (Map<String, Object>) objs.get("operations");
if(operations != null) { if (operations != null) {
List<CodegenOperation> ops = (List<CodegenOperation>) operations.get("operation"); List<CodegenOperation> ops = (List<CodegenOperation>) operations.get("operation");
for(CodegenOperation operation : ops) { for (CodegenOperation operation : ops) {
if(operation.returnType == null) if (operation.returnType == null) {
operation.returnType = "Void"; operation.returnType = "Void";
else if(operation.returnType.startsWith("List")) { } else if (operation.returnType.startsWith("List")) {
String rt = operation.returnType; String rt = operation.returnType;
int end = rt.lastIndexOf(">"); int end = rt.lastIndexOf(">");
if(end > 0) { if (end > 0) {
operation.returnType = rt.substring("List<".length(), end); operation.returnType = rt.substring("List<".length(), end);
operation.returnContainer = "List"; operation.returnContainer = "List";
} }
} } else if (operation.returnType.startsWith("Map")) {
else if(operation.returnType.startsWith("Map")) {
String rt = operation.returnType; String rt = operation.returnType;
int end = rt.lastIndexOf(">"); int end = rt.lastIndexOf(">");
if(end > 0) { if (end > 0) {
operation.returnType = rt.substring("Map<".length(), end); operation.returnType = rt.substring("Map<".length(), end);
operation.returnContainer = "Map"; operation.returnContainer = "Map";
} }
} } else if (operation.returnType.startsWith("Set")) {
else if(operation.returnType.startsWith("Set")) {
String rt = operation.returnType; String rt = operation.returnType;
int end = rt.lastIndexOf(">"); int end = rt.lastIndexOf(">");
if(end > 0) { if (end > 0) {
operation.returnType = rt.substring("Set<".length(), end); operation.returnType = rt.substring("Set<".length(), end);
operation.returnContainer = "Set"; operation.returnContainer = "Set";
} }

View File

@ -1,76 +1,77 @@
package io.swagger.codegen.languages; package io.swagger.codegen.languages;
import io.swagger.codegen.*; import io.swagger.codegen.CodegenConfig;
import io.swagger.models.properties.*; import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile;
import java.util.*;
import java.io.File; import java.io.File;
public class StaticDocCodegen extends DefaultCodegen implements CodegenConfig { public class StaticDocCodegen extends DefaultCodegen implements CodegenConfig {
protected String invokerPackage = "io.swagger.client"; protected String invokerPackage = "io.swagger.client";
protected String groupId = "io.swagger"; protected String groupId = "io.swagger";
protected String artifactId = "swagger-client"; protected String artifactId = "swagger-client";
protected String artifactVersion = "1.0.0"; protected String artifactVersion = "1.0.0";
protected String sourceFolder = "docs"; protected String sourceFolder = "docs";
public CodegenType getTag() { public StaticDocCodegen() {
return CodegenType.DOCUMENTATION; super();
} outputFolder = "docs";
modelTemplateFiles.put("model.mustache", ".html");
apiTemplateFiles.put("operation.mustache", ".html");
templateDir = "swagger-static";
public String getName() { additionalProperties.put("invokerPackage", invokerPackage);
return "dynamic-html"; additionalProperties.put("groupId", groupId);
} additionalProperties.put("artifactId", artifactId);
additionalProperties.put("artifactVersion", artifactVersion);
public String getHelp() { supportingFiles.add(new SupportingFile("package.mustache", "", "package.json"));
return "Generates a dynamic HTML site."; supportingFiles.add(new SupportingFile("main.mustache", "", "main.js"));
} supportingFiles.add(new SupportingFile("assets/css/bootstrap-responsive.css",
outputFolder + "/assets/css", "bootstrap-responsive.css"));
supportingFiles.add(new SupportingFile("assets/css/bootstrap.css",
outputFolder + "/assets/css", "bootstrap.css"));
supportingFiles.add(new SupportingFile("assets/css/style.css",
outputFolder + "/assets/css", "style.css"));
supportingFiles.add(new SupportingFile("assets/images/logo.png",
outputFolder + "/assets/images", "logo.png"));
supportingFiles.add(new SupportingFile("assets/js/bootstrap.js",
outputFolder + "/assets/js", "bootstrap.js"));
supportingFiles.add(new SupportingFile("assets/js/jquery-1.8.3.min.js",
outputFolder + "/assets/js", "jquery-1.8.3.min.js"));
supportingFiles.add(new SupportingFile("assets/js/main.js",
outputFolder + "/assets/js", "main.js"));
supportingFiles.add(new SupportingFile("index.mustache",
outputFolder, "index.html"));
public StaticDocCodegen() { instantiationTypes.put("array", "ArrayList");
super(); instantiationTypes.put("map", "HashMap");
outputFolder = "docs"; }
modelTemplateFiles.put("model.mustache", ".html");
apiTemplateFiles.put("operation.mustache", ".html");
templateDir = "swagger-static";
additionalProperties.put("invokerPackage", invokerPackage); public CodegenType getTag() {
additionalProperties.put("groupId", groupId); return CodegenType.DOCUMENTATION;
additionalProperties.put("artifactId", artifactId); }
additionalProperties.put("artifactVersion", artifactVersion);
supportingFiles.add(new SupportingFile("package.mustache", "", "package.json")); public String getName() {
supportingFiles.add(new SupportingFile("main.mustache", "", "main.js")); return "dynamic-html";
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"); public String getHelp() {
instantiationTypes.put("map", "HashMap"); return "Generates a dynamic HTML site.";
} }
@Override @Override
public String escapeReservedWord(String name) { public String escapeReservedWord(String name) {
return "_" + name; return "_" + name;
} }
@Override @Override
public String apiFileFolder() { public String apiFileFolder() {
return outputFolder + File.separator + sourceFolder + File.separator + "operations"; return outputFolder + File.separator + sourceFolder + File.separator + "operations";
} }
public String modelFileFolder() { public String modelFileFolder() {
return outputFolder + File.separator + sourceFolder + File.separator + "models"; return outputFolder + File.separator + sourceFolder + File.separator + "models";
} }
} }

View File

@ -1,97 +1,104 @@
package io.swagger.codegen.languages; package io.swagger.codegen.languages;
import io.swagger.codegen.*; import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenOperation;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile;
import io.swagger.models.Operation; import io.swagger.models.Operation;
import io.swagger.models.properties.*; import io.swagger.models.properties.ArrayProperty;
import io.swagger.util.Json; import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
import java.util.*; import java.util.ArrayList;
import java.io.File; import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
public class StaticHtmlGenerator extends DefaultCodegen implements CodegenConfig { public class StaticHtmlGenerator extends DefaultCodegen implements CodegenConfig {
private static final String ALL_OPERATIONS = ""; private static final String ALL_OPERATIONS = "";
protected String invokerPackage = "io.swagger.client"; protected String invokerPackage = "io.swagger.client";
protected String groupId = "io.swagger"; protected String groupId = "io.swagger";
protected String artifactId = "swagger-client"; protected String artifactId = "swagger-client";
protected String artifactVersion = "1.0.0"; protected String artifactVersion = "1.0.0";
protected String sourceFolder = "src/main/scala"; protected String sourceFolder = "src/main/scala";
public CodegenType getTag() { public StaticHtmlGenerator() {
return CodegenType.DOCUMENTATION; super();
} outputFolder = "docs";
templateDir = "htmlDocs";
public String getName() { defaultIncludes = new HashSet<String>();
return "html";
}
public String getHelp() { additionalProperties.put("appName", "Swagger Sample");
return "Generates a static HTML file."; additionalProperties.put("appDescription", "A sample swagger server");
} additionalProperties.put("infoUrl", "https://helloreverb.com");
additionalProperties.put("infoEmail", "hello@helloreverb.com");
additionalProperties.put("licenseInfo", "All rights reserved");
additionalProperties.put("licenseUrl", "http://apache.org/licenses/LICENSE-2.0.html");
additionalProperties.put("invokerPackage", invokerPackage);
additionalProperties.put("groupId", groupId);
additionalProperties.put("artifactId", artifactId);
additionalProperties.put("artifactVersion", artifactVersion);
public StaticHtmlGenerator() { supportingFiles.add(new SupportingFile("index.mustache", "", "index.html"));
super(); reservedWords = new HashSet<String>();
outputFolder = "docs";
templateDir = "htmlDocs";
defaultIncludes = new HashSet<String>(); languageSpecificPrimitives = new HashSet<String>();
importMapping = new HashMap<String, String>();
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) + "]"; public CodegenType getTag() {
return CodegenType.DOCUMENTATION;
} }
return super.getTypeDeclaration(p);
}
@Override public String getName() {
public Map<String, Object> postProcessOperations(Map<String, Object> objs) { return "html";
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 getHelp() {
public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, Map<String, List<CodegenOperation>> operations) { return "Generates a static HTML file.";
List<CodegenOperation> opList = operations.get(ALL_OPERATIONS);
if(opList == null) {
opList = new ArrayList<CodegenOperation>();
operations.put(ALL_OPERATIONS, opList);
} }
for (CodegenOperation addedOperation: opList){
if (addedOperation.operationId.equals(co.operationId) && addedOperation.path.equals(co.path) && addedOperation.httpMethod.equals(co.httpMethod)) { @Override
addedOperation.tags.addAll(co.tags); public String getTypeDeclaration(Property p) {
return; 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;
}
@Override
public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, Map<String, List<CodegenOperation>> operations) {
List<CodegenOperation> opList = operations.get(ALL_OPERATIONS);
if (opList == null) {
opList = new ArrayList<CodegenOperation>();
operations.put(ALL_OPERATIONS, opList);
}
for (CodegenOperation addedOperation : opList) {
if (addedOperation.operationId.equals(co.operationId) && addedOperation.path.equals(co.path) && addedOperation.httpMethod.equals(co.httpMethod)) {
addedOperation.tags.addAll(co.tags);
return;
}
}
opList.add(co);
} }
opList.add(co);
}
} }

View File

@ -1,45 +1,46 @@
package io.swagger.codegen.languages; package io.swagger.codegen.languages;
import io.swagger.codegen.*; import io.swagger.codegen.CodegenConfig;
import io.swagger.util.*; import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile;
import io.swagger.models.Swagger; import io.swagger.models.Swagger;
import io.swagger.util.Json;
import org.apache.commons.io.FileUtils; import org.apache.commons.io.FileUtils;
import java.io.File; import java.io.File;
public class SwaggerGenerator extends DefaultCodegen implements CodegenConfig { public class SwaggerGenerator extends DefaultCodegen implements CodegenConfig {
public CodegenType getTag() { public SwaggerGenerator() {
return CodegenType.DOCUMENTATION; super();
} templateDir = "swagger";
outputFolder = "generated-code/swagger";
public String getName() { supportingFiles.add(new SupportingFile("README.md", "", "README.md"));
return "swagger";
}
public String getHelp() {
return "Creates a static swagger.json file.";
}
public SwaggerGenerator() {
super();
templateDir = "swagger";
outputFolder = "generated-code/swagger";
supportingFiles.add(new SupportingFile("README.md", "", "README.md"));
}
@Override
public void processSwagger(Swagger swagger) {
String swaggerString = Json.pretty(swagger);
try{
String outputFile = outputFolder + File.separator + "swagger.json";
FileUtils.writeStringToFile(new File(outputFile), swaggerString);
System.out.println("wrote file to " + outputFile);
} }
catch(Exception e) {
e.printStackTrace(); public CodegenType getTag() {
return CodegenType.DOCUMENTATION;
}
public String getName() {
return "swagger";
}
public String getHelp() {
return "Creates a static swagger.json file.";
}
@Override
public void processSwagger(Swagger swagger) {
String swaggerString = Json.pretty(swagger);
try {
String outputFile = outputFolder + File.separator + "swagger.json";
FileUtils.writeStringToFile(new File(outputFile), swaggerString);
System.out.println("wrote file to " + outputFile);
} catch (Exception e) {
e.printStackTrace();
}
} }
}
} }

View File

@ -1,44 +1,45 @@
package io.swagger.codegen.languages; package io.swagger.codegen.languages;
import io.swagger.codegen.*; import io.swagger.codegen.CodegenConfig;
import io.swagger.util.*; import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile;
import io.swagger.models.Swagger; import io.swagger.models.Swagger;
import io.swagger.util.Yaml;
import org.apache.commons.io.FileUtils; import org.apache.commons.io.FileUtils;
import java.io.File; import java.io.File;
public class SwaggerYamlGenerator extends DefaultCodegen implements CodegenConfig { public class SwaggerYamlGenerator extends DefaultCodegen implements CodegenConfig {
public CodegenType getTag() { public SwaggerYamlGenerator() {
return CodegenType.DOCUMENTATION; super();
} templateDir = "swagger";
outputFolder = "generated-code/swagger";
public String getName() { supportingFiles.add(new SupportingFile("README.md", "", "README.md"));
return "swagger-yaml";
}
public String getHelp() {
return "Creates a static swagger.yaml file.";
}
public SwaggerYamlGenerator() {
super();
templateDir = "swagger";
outputFolder = "generated-code/swagger";
supportingFiles.add(new SupportingFile("README.md", "", "README.md"));
}
@Override
public void processSwagger(Swagger swagger) {
try{
String swaggerString = Yaml.mapper().writeValueAsString(swagger);
String outputFile = outputFolder + File.separator + "swagger.yaml";
FileUtils.writeStringToFile(new File(outputFile), swaggerString);
System.out.println("wrote file to " + outputFile);
} }
catch(Exception e) {
e.printStackTrace(); public CodegenType getTag() {
return CodegenType.DOCUMENTATION;
}
public String getName() {
return "swagger-yaml";
}
public String getHelp() {
return "Creates a static swagger.yaml file.";
}
@Override
public void processSwagger(Swagger swagger) {
try {
String swaggerString = Yaml.mapper().writeValueAsString(swagger);
String outputFile = outputFolder + File.separator + "swagger.yaml";
FileUtils.writeStringToFile(new File(outputFile), swaggerString);
System.out.println("wrote file to " + outputFile);
} catch (Exception e) {
e.printStackTrace();
}
} }
}
} }

View File

@ -3,248 +3,263 @@ package io.swagger.codegen.languages;
import com.google.common.base.Predicate; import com.google.common.base.Predicate;
import com.google.common.collect.Iterators; import com.google.common.collect.Iterators;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import io.swagger.codegen.*; import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenOperation;
import io.swagger.codegen.CodegenProperty;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile;
import io.swagger.models.Model; import io.swagger.models.Model;
import io.swagger.models.Operation; import io.swagger.models.Operation;
import io.swagger.models.parameters.HeaderParameter; import io.swagger.models.parameters.HeaderParameter;
import io.swagger.models.parameters.Parameter; import io.swagger.models.parameters.Parameter;
import io.swagger.models.properties.*; import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import java.util.*;
import java.io.File; import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
public class SwiftGenerator extends DefaultCodegen implements CodegenConfig { public class SwiftGenerator extends DefaultCodegen implements CodegenConfig {
private static final Pattern PATH_PARAM_PATTERN = Pattern.compile("\\{[a-zA-Z_]+\\}"); private static final Pattern PATH_PARAM_PATTERN = Pattern.compile("\\{[a-zA-Z_]+\\}");
protected String sourceFolder = "Classes/Swaggers"; protected String sourceFolder = "Classes/Swaggers";
public CodegenType getTag() { public SwiftGenerator() {
return CodegenType.CLIENT; super();
} outputFolder = "generated-code/swift";
modelTemplateFiles.put("model.mustache", ".swift");
apiTemplateFiles.put("api.mustache", ".swift");
templateDir = "swift";
apiPackage = "/APIs";
modelPackage = "/Models";
public String getName() { // Inject application name
return "swift"; String appName = System.getProperty("appName");
} if (appName == null) {
appName = "SwaggerClient";
}
additionalProperties.put("projectName", appName);
public String getHelp() { // Inject base url override
return "Generates a swift client library."; String basePathOverride = System.getProperty("basePathOverride");
} if (basePathOverride != null) {
additionalProperties.put("basePathOverride", basePathOverride);
}
public SwiftGenerator() { sourceFolder = appName + "/" + sourceFolder;
super();
outputFolder = "generated-code/swift";
modelTemplateFiles.put("model.mustache", ".swift");
apiTemplateFiles.put("api.mustache", ".swift");
templateDir = "swift";
apiPackage = "/APIs";
modelPackage = "/Models";
// Inject application name supportingFiles.add(new SupportingFile("Cartfile.mustache", "", "Cartfile"));
String appName = System.getProperty("appName"); supportingFiles.add(new SupportingFile("APIHelper.mustache", sourceFolder, "APIHelper.swift"));
if (appName == null) { supportingFiles.add(new SupportingFile("AlamofireImplementations.mustache", sourceFolder, "AlamofireImplementations.swift"));
appName = "SwaggerClient"; supportingFiles.add(new SupportingFile("Extensions.mustache", sourceFolder, "Extensions.swift"));
} supportingFiles.add(new SupportingFile("Models.mustache", sourceFolder, "Models.swift"));
additionalProperties.put("projectName", appName); supportingFiles.add(new SupportingFile("APIs.mustache", sourceFolder, "APIs.swift"));
// Inject base url override languageSpecificPrimitives = new HashSet<String>(
String basePathOverride = System.getProperty("basePathOverride"); Arrays.asList(
if (basePathOverride != null) { "Int",
additionalProperties.put("basePathOverride", basePathOverride); "Float",
"Double",
"Bool",
"Void",
"String",
"Character")
);
defaultIncludes = new HashSet<String>(
Arrays.asList(
"NSDate",
"Array",
"Dictionary",
"Set",
"Any",
"Empty",
"AnyObject")
);
reservedWords = new HashSet<String>(
Arrays.asList(
"class", "break", "as", "associativity", "deinit", "case", "dynamicType", "convenience", "enum", "continue",
"false", "dynamic", "extension", "default", "is", "didSet", "func", "do", "nil", "final", "import", "else",
"self", "get", "init", "fallthrough", "Self", "infix", "internal", "for", "super", "inout", "let", "if",
"true", "lazy", "operator", "in", "COLUMN", "left", "private", "return", "FILE", "mutating", "protocol",
"switch", "FUNCTION", "none", "public", "where", "LINE", "nonmutating", "static", "while", "optional",
"struct", "override", "subscript", "postfix", "typealias", "precedence", "var", "prefix", "Protocol",
"required", "right", "set", "Type", "unowned", "weak")
);
typeMapping = new HashMap<String, String>();
typeMapping.put("array", "Array");
typeMapping.put("List", "Array");
typeMapping.put("map", "Dictionary");
typeMapping.put("date", "NSDate");
typeMapping.put("Date", "NSDate");
typeMapping.put("DateTime", "NSDate");
typeMapping.put("boolean", "Bool");
typeMapping.put("string", "String");
typeMapping.put("char", "Character");
typeMapping.put("short", "Int");
typeMapping.put("int", "Int");
typeMapping.put("long", "Int");
typeMapping.put("integer", "Int");
typeMapping.put("Integer", "Int");
typeMapping.put("float", "Float");
typeMapping.put("number", "Double");
typeMapping.put("double", "Double");
typeMapping.put("object", "AnyObject");
typeMapping.put("file", "NSData");
importMapping = new HashMap<String, String>();
} }
sourceFolder = appName + "/" + sourceFolder; private static String normalizePath(String path) {
StringBuilder builder = new StringBuilder();
supportingFiles.add(new SupportingFile("Cartfile.mustache", "", "Cartfile")); int cursor = 0;
supportingFiles.add(new SupportingFile("APIHelper.mustache", sourceFolder, "APIHelper.swift")); Matcher matcher = PATH_PARAM_PATTERN.matcher(path);
supportingFiles.add(new SupportingFile("AlamofireImplementations.mustache", sourceFolder, "AlamofireImplementations.swift")); boolean found = matcher.find();
supportingFiles.add(new SupportingFile("Extensions.mustache", sourceFolder, "Extensions.swift")); while (found) {
supportingFiles.add(new SupportingFile("Models.mustache", sourceFolder, "Models.swift")); String stringBeforeMatch = path.substring(cursor, matcher.start());
supportingFiles.add(new SupportingFile("APIs.mustache", sourceFolder, "APIs.swift")); builder.append(stringBeforeMatch);
languageSpecificPrimitives = new HashSet<String>( String group = matcher.group().substring(1, matcher.group().length() - 1);
Arrays.asList( group = camelize(group, true);
"Int", builder
"Float", .append("{")
"Double", .append(group)
"Bool", .append("}");
"Void",
"String",
"Character")
);
defaultIncludes = new HashSet<String>(
Arrays.asList(
"NSDate",
"Array",
"Dictionary",
"Set",
"Any",
"Empty",
"AnyObject")
);
reservedWords = new HashSet<String>(
Arrays.asList(
"class", "break", "as", "associativity", "deinit", "case", "dynamicType", "convenience", "enum", "continue",
"false", "dynamic", "extension", "default", "is", "didSet", "func", "do", "nil", "final", "import", "else",
"self", "get", "init", "fallthrough", "Self", "infix", "internal", "for", "super", "inout", "let", "if",
"true", "lazy", "operator", "in", "COLUMN", "left", "private", "return", "FILE", "mutating", "protocol",
"switch", "FUNCTION", "none", "public", "where", "LINE", "nonmutating", "static", "while", "optional",
"struct", "override", "subscript", "postfix", "typealias", "precedence", "var", "prefix", "Protocol",
"required", "right", "set", "Type", "unowned", "weak")
);
typeMapping = new HashMap<String, String>(); cursor = matcher.end();
typeMapping.put("array", "Array"); found = matcher.find();
typeMapping.put("List", "Array"); }
typeMapping.put("map", "Dictionary");
typeMapping.put("date", "NSDate");
typeMapping.put("Date", "NSDate");
typeMapping.put("DateTime", "NSDate");
typeMapping.put("boolean", "Bool");
typeMapping.put("string", "String");
typeMapping.put("char", "Character");
typeMapping.put("short", "Int");
typeMapping.put("int", "Int");
typeMapping.put("long", "Int");
typeMapping.put("integer", "Int");
typeMapping.put("Integer", "Int");
typeMapping.put("float", "Float");
typeMapping.put("number", "Double");
typeMapping.put("double", "Double");
typeMapping.put("object", "AnyObject");
typeMapping.put("file", "NSData");
importMapping = new HashMap<String, String>(); String stringAfterMatch = path.substring(cursor);
} builder.append(stringAfterMatch);
@Override return builder.toString();
public String escapeReservedWord(String name) {
return "_" + name; // add an underscore to the name
}
@Override
public String modelFileFolder() {
return outputFolder + "/" + sourceFolder + modelPackage().replace('.', File.separatorChar);
}
@Override
public String apiFileFolder() {
return outputFolder + "/" + sourceFolder + apiPackage().replace('.', File.separatorChar);
}
@Override
public String getTypeDeclaration(Property p) {
if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
return "[" + getTypeDeclaration(inner) + "]";
} else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
return "[String:" + getTypeDeclaration(inner) + "]";
} }
return super.getTypeDeclaration(p);
}
@Override public CodegenType getTag() {
public String getSwaggerType(Property p) { return CodegenType.CLIENT;
String swaggerType = super.getSwaggerType(p); }
String type = null;
if (typeMapping.containsKey(swaggerType)) { public String getName() {
type = typeMapping.get(swaggerType); return "swift";
if (languageSpecificPrimitives.contains(type)) }
public String getHelp() {
return "Generates a swift client library.";
}
@Override
public String escapeReservedWord(String name) {
return "_" + name; // add an underscore to the name
}
@Override
public String modelFileFolder() {
return outputFolder + "/" + sourceFolder + modelPackage().replace('.', File.separatorChar);
}
@Override
public String apiFileFolder() {
return outputFolder + "/" + sourceFolder + apiPackage().replace('.', File.separatorChar);
}
@Override
public String getTypeDeclaration(Property p) {
if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
return "[" + getTypeDeclaration(inner) + "]";
} else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
return "[String:" + getTypeDeclaration(inner) + "]";
}
return super.getTypeDeclaration(p);
}
@Override
public String getSwaggerType(Property p) {
String swaggerType = super.getSwaggerType(p);
String type = null;
if (typeMapping.containsKey(swaggerType)) {
type = typeMapping.get(swaggerType);
if (languageSpecificPrimitives.contains(type)) {
return toModelName(type);
}
} else {
type = swaggerType;
}
return toModelName(type); return toModelName(type);
} else
type = swaggerType;
return toModelName(type);
}
@Override
public String toDefaultValue(Property p) {
// nil
return null;
}
@Override
public String toInstantiationType(Property p) {
if (p instanceof MapProperty) {
MapProperty ap = (MapProperty) p;
String inner = getSwaggerType(ap.getAdditionalProperties());
return "[String:" + inner + "]";
} else if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
String inner = getSwaggerType(ap.getItems());
return "[" + inner + "]";
}
return null;
}
@Override
public CodegenProperty fromProperty(String name, Property p) {
CodegenProperty codegenProperty = super.fromProperty(name, p);
if (codegenProperty.isEnum) {
List<Map<String, String>> swiftEnums = new ArrayList<Map<String, String>>();
List<String> values = (List<String>) codegenProperty.allowableValues.get("values");
for (String value : values) {
Map<String, String> map = new HashMap<String, String>();
map.put("enum", StringUtils.capitalize(value));
map.put("raw", value);
swiftEnums.add(map);
}
codegenProperty.allowableValues.put("values", swiftEnums);
codegenProperty.datatypeWithEnum =
StringUtils.left(codegenProperty.datatypeWithEnum, codegenProperty.datatypeWithEnum.length() - "Enum".length());
}
return codegenProperty;
}
@Override
public String toApiName(String name) {
if(name.length() == 0)
return "DefaultAPI";
return initialCaps(name) + "API";
}
@Override
public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map<String, Model> definitions) {
path = normalizePath(path);
List<Parameter> parameters = operation.getParameters();
parameters = Lists.newArrayList(Iterators.filter(parameters.iterator(), new Predicate<Parameter>() {
@Override
public boolean apply(@Nullable Parameter parameter) {
return !(parameter instanceof HeaderParameter);
}
}));
operation.setParameters(parameters);
return super.fromOperation(path, httpMethod, operation, definitions);
}
private static String normalizePath(String path) {
StringBuilder builder = new StringBuilder();
int cursor = 0;
Matcher matcher = PATH_PARAM_PATTERN.matcher(path);
boolean found = matcher.find();
while (found) {
String stringBeforeMatch = path.substring(cursor, matcher.start());
builder.append(stringBeforeMatch);
String group = matcher.group().substring(1, matcher.group().length() - 1);
group = camelize(group, true);
builder
.append("{")
.append(group)
.append("}");
cursor = matcher.end();
found = matcher.find();
} }
String stringAfterMatch = path.substring(cursor); @Override
builder.append(stringAfterMatch); public String toDefaultValue(Property p) {
// nil
return null;
}
return builder.toString(); @Override
} public String toInstantiationType(Property p) {
if (p instanceof MapProperty) {
MapProperty ap = (MapProperty) p;
String inner = getSwaggerType(ap.getAdditionalProperties());
return "[String:" + inner + "]";
} else if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
String inner = getSwaggerType(ap.getItems());
return "[" + inner + "]";
}
return null;
}
@Override
public CodegenProperty fromProperty(String name, Property p) {
CodegenProperty codegenProperty = super.fromProperty(name, p);
if (codegenProperty.isEnum) {
List<Map<String, String>> swiftEnums = new ArrayList<Map<String, String>>();
List<String> values = (List<String>) codegenProperty.allowableValues.get("values");
for (String value : values) {
Map<String, String> map = new HashMap<String, String>();
map.put("enum", StringUtils.capitalize(value));
map.put("raw", value);
swiftEnums.add(map);
}
codegenProperty.allowableValues.put("values", swiftEnums);
codegenProperty.datatypeWithEnum =
StringUtils.left(codegenProperty.datatypeWithEnum, codegenProperty.datatypeWithEnum.length() - "Enum".length());
}
return codegenProperty;
}
@Override
public String toApiName(String name) {
if (name.length() == 0) {
return "DefaultAPI";
}
return initialCaps(name) + "API";
}
@Override
public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map<String, Model> definitions) {
path = normalizePath(path);
List<Parameter> parameters = operation.getParameters();
parameters = Lists.newArrayList(Iterators.filter(parameters.iterator(), new Predicate<Parameter>() {
@Override
public boolean apply(@Nullable Parameter parameter) {
return !(parameter instanceof HeaderParameter);
}
}));
operation.setParameters(parameters);
return super.fromOperation(path, httpMethod, operation, definitions);
}
} }

View File

@ -1,258 +1,277 @@
package io.swagger.codegen.languages; package io.swagger.codegen.languages;
import io.swagger.util.Json; import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.*; import io.swagger.codegen.CodegenType;
import io.swagger.models.properties.*; import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.BooleanProperty;
import io.swagger.models.properties.DateProperty;
import io.swagger.models.properties.DateTimeProperty;
import io.swagger.models.properties.DecimalProperty;
import io.swagger.models.properties.DoubleProperty;
import io.swagger.models.properties.FloatProperty;
import io.swagger.models.properties.IntegerProperty;
import io.swagger.models.properties.LongProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
import io.swagger.models.properties.RefProperty;
import io.swagger.models.properties.StringProperty;
import java.util.*;
import java.io.File; import java.io.File;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class TizenClientCodegen extends DefaultCodegen implements CodegenConfig { public class TizenClientCodegen extends DefaultCodegen implements CodegenConfig {
protected Set<String> foundationClasses = new HashSet<String>(); protected static String PREFIX = "Sami";
protected String sourceFolder = "client"; protected Set<String> foundationClasses = new HashSet<String>();
protected static String PREFIX = "Sami"; protected String sourceFolder = "client";
protected Map<String, String> namespaces = new HashMap<String, String>(); protected Map<String, String> namespaces = new HashMap<String, String>();
public CodegenType getTag() { public TizenClientCodegen() {
return CodegenType.CLIENT; super();
} outputFolder = "generated-code/tizen";
modelTemplateFiles.put("model-header.mustache", ".h");
public String getName() { modelTemplateFiles.put("model-body.mustache", ".cpp");
return "tizen"; apiTemplateFiles.put("api-header.mustache", ".h");
} apiTemplateFiles.put("api-body.mustache", ".cpp");
templateDir = "tizen";
modelPackage = "";
public String getHelp() { defaultIncludes = new HashSet<String>(
return "Generates a Samsung Tizen C++ client library."; Arrays.asList(
} "bool",
"int",
"long")
);
languageSpecificPrimitives = new HashSet<String>();
public TizenClientCodegen() { additionalProperties().put("prefix", PREFIX);
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>( reservedWords = new HashSet<String>(
Arrays.asList( // VERIFY
"bool", Arrays.asList(
"int", "void", "char", "short", "int", "void", "char", "short", "int",
"long") "long", "float", "double", "signed", "unsigned", "id", "const",
); "volatile", "in", "out", "inout", "bycopy", "byref", "oneway",
languageSpecificPrimitives = new HashSet<String>(); "self", "super"
));
additionalProperties().put("prefix", PREFIX); super.typeMapping = new HashMap<String, String>();
reservedWords = new HashSet<String>( typeMapping.put("Date", "DateTime");
// VERIFY typeMapping.put("DateTime", "DateTime");
Arrays.asList( typeMapping.put("string", "String");
"void", "char", "short", "int", "void", "char", "short", "int", typeMapping.put("integer", "Integer");
"long", "float", "double", "signed", "unsigned", "id", "const", typeMapping.put("float", "Float");
"volatile", "in", "out", "inout", "bycopy", "byref", "oneway", typeMapping.put("long", "Long");
"self", "super" typeMapping.put("boolean", "Boolean");
)); typeMapping.put("double", "Double");
typeMapping.put("array", "IList");
typeMapping.put("map", "HashMap");
typeMapping.put("number", "Long");
typeMapping.put("object", PREFIX + "Object");
super.typeMapping = new HashMap<String, String>(); importMapping = new HashMap<String, String>();
typeMapping.put("Date", "DateTime"); namespaces = new HashMap<String, String>();
typeMapping.put("DateTime", "DateTime"); namespaces.put("DateTime", "Tizen::Base::DateTime");
typeMapping.put("string", "String"); namespaces.put("Integer", "Tizen::Base::Integer");
typeMapping.put("integer", "Integer"); namespaces.put("Long", "Tizen::Base::Long");
typeMapping.put("float", "Float"); namespaces.put("Boolean", "Tizen::Base::Boolean");
typeMapping.put("long", "Long"); namespaces.put("Float", "Tizen::Base::Float");
typeMapping.put("boolean", "Boolean"); namespaces.put("String", "Tizen::Base::String");
typeMapping.put("double", "Double"); namespaces.put("Double", "Tizen::Base::Double");
typeMapping.put("array", "IList"); namespaces.put("IList", "Tizen::Base::Collection::IList");
typeMapping.put("map", "HashMap"); namespaces.put("HashMap", "Tizen::Base::Collection::HashMap");
typeMapping.put("number", "Long"); namespaces.put("ArrayList", "Tizen::Base::Collection::ArrayList");
typeMapping.put("object", PREFIX + "Object"); namespaces.put("JsonNumber", "Tizen::Web::Json");
namespaces.put("JsonString", "Tizen::Web::Json");
importMapping = new HashMap<String, String>(); foundationClasses = new HashSet<String>(
Arrays.asList(
namespaces = new HashMap<String, String> (); "String",
namespaces.put("DateTime", "Tizen::Base::DateTime"); "Integer",
namespaces.put("Integer", "Tizen::Base::Integer"); "Float")
namespaces.put("Long", "Tizen::Base::Long"); );
namespaces.put("Boolean", "Tizen::Base::Boolean"); supportingFiles.clear();
namespaces.put("Float", "Tizen::Base::Float"); supportingFiles.add(new SupportingFile("modelFactory.mustache", sourceFolder, PREFIX + "ModelFactory.h"));
namespaces.put("String", "Tizen::Base::String"); supportingFiles.add(new SupportingFile("helpers-header.mustache", sourceFolder, PREFIX + "Helpers.h"));
namespaces.put("Double", "Tizen::Base::Double"); supportingFiles.add(new SupportingFile("helpers-body.mustache", sourceFolder, PREFIX + "Helpers.cpp"));
namespaces.put("IList", "Tizen::Base::Collection::IList"); supportingFiles.add(new SupportingFile("apiclient-header.mustache", sourceFolder, PREFIX + "ApiClient.h"));
namespaces.put("HashMap", "Tizen::Base::Collection::HashMap"); supportingFiles.add(new SupportingFile("apiclient-body.mustache", sourceFolder, PREFIX + "ApiClient.cpp"));
namespaces.put("ArrayList", "Tizen::Base::Collection::ArrayList"); supportingFiles.add(new SupportingFile("object.mustache", sourceFolder, PREFIX + "Object.h"));
namespaces.put("JsonNumber", "Tizen::Web::Json"); supportingFiles.add(new SupportingFile("error-header.mustache", sourceFolder, PREFIX + "Error.h"));
namespaces.put("JsonString", "Tizen::Web::Json"); supportingFiles.add(new SupportingFile("error-body.mustache", sourceFolder, PREFIX + "Error.cpp"));
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; public CodegenType getTag() {
String inner = getSwaggerType(ap.getItems()); return CodegenType.CLIENT;
return instantiationTypes.get("array");
} }
else
return null;
}
@Override public String getName() {
public String getTypeDeclaration(String name) { return "tizen";
if(languageSpecificPrimitives.contains(name) && !foundationClasses.contains(name)) }
return name;
else
return name + "*";
}
@Override public String getHelp() {
public String getSwaggerType(Property p) { return "Generates a Samsung Tizen C++ client library.";
String swaggerType = super.getSwaggerType(p); }
String type = null;
if(typeMapping.containsKey(swaggerType)) { @Override
type = typeMapping.get(swaggerType); public String toInstantiationType(Property p) {
if(languageSpecificPrimitives.contains(type) && !foundationClasses.contains(type)) 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); return toModelName(type);
} }
else
type = swaggerType;
return toModelName(type);
}
@Override @Override
public String getTypeDeclaration(Property p) { public String getTypeDeclaration(Property p) {
String swaggerType = getSwaggerType(p); String swaggerType = getSwaggerType(p);
if(languageSpecificPrimitives.contains(swaggerType) && !foundationClasses.contains(swaggerType)) if (languageSpecificPrimitives.contains(swaggerType) && !foundationClasses.contains(swaggerType)) {
return toModelName(swaggerType); return toModelName(swaggerType);
else } else {
return swaggerType + "*"; 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 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 @Override
public String toModelImport(String name) { public String toModelImport(String name) {
if(namespaces.containsKey(name)) { if (namespaces.containsKey(name)) {
return "using " + namespaces.get(name) + ";"; return "using " + namespaces.get(name) + ";";
}
return "#include \"" + name + ".h\"";
} }
return "#include \"" + name + ".h\"";
}
@Override @Override
public String toDefaultValue(Property p) { public String toDefaultValue(Property p) {
if(p instanceof StringProperty) if (p instanceof StringProperty) {
return "new String()"; return "new String()";
else if (p instanceof BooleanProperty) } else if (p instanceof BooleanProperty) {
return "new Boolean(false)"; return "new Boolean(false)";
else if(p instanceof DateProperty) } else if (p instanceof DateProperty) {
return "new DateTime()"; return "new DateTime()";
else if(p instanceof DateTimeProperty) } else if (p instanceof DateTimeProperty) {
return "new DateTime()"; return "new DateTime()";
else if (p instanceof DoubleProperty) } else if (p instanceof DoubleProperty) {
return "new Double()"; return "new Double()";
else if (p instanceof FloatProperty) } else if (p instanceof FloatProperty) {
return "new Float()"; return "new Float()";
else if (p instanceof IntegerProperty) } else if (p instanceof IntegerProperty) {
return "new Integer()"; return "new Integer()";
else if (p instanceof LongProperty) } else if (p instanceof LongProperty) {
return "new Long()"; return "new Long()";
else if (p instanceof DecimalProperty) } else if (p instanceof DecimalProperty) {
return "new Long()"; return "new Long()";
else if (p instanceof MapProperty) { } else if (p instanceof MapProperty) {
MapProperty ap = (MapProperty) p; MapProperty ap = (MapProperty) p;
String inner = getSwaggerType(ap.getAdditionalProperties()); String inner = getSwaggerType(ap.getAdditionalProperties());
return "new HashMap()"; return "new HashMap()";
} else if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
String inner = getSwaggerType(ap.getItems());
return "new ArrayList()";
}
// else
if (p instanceof RefProperty) {
RefProperty rp = (RefProperty) p;
return "new " + toModelName(rp.getSimpleRef()) + "()";
}
return "null";
} }
else if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p; @Override
String inner = getSwaggerType(ap.getItems()); public String apiFileFolder() {
return "new ArrayList()"; return outputFolder + File.separator + sourceFolder;
} }
// else
if(p instanceof RefProperty) { @Override
RefProperty rp = (RefProperty) p; public String modelFileFolder() {
return "new " + toModelName(rp.getSimpleRef()) + "()"; return outputFolder + File.separator + sourceFolder;
} }
return "null";
}
@Override @Override
public String apiFileFolder() { public String toModelFilename(String name) {
return outputFolder + File.separator + sourceFolder; return PREFIX + initialCaps(name);
} }
@Override @Override
public String modelFileFolder() { public String toApiName(String name) {
return outputFolder + File.separator + sourceFolder; return PREFIX + initialCaps(name) + "Api";
} }
@Override public String toApiFilename(String name) {
public String toModelFilename(String name) { return PREFIX + initialCaps(name) + "Api";
return PREFIX + initialCaps(name); }
}
@Override @Override
public String toApiName(String name) { public String toVarName(String name) {
return PREFIX + initialCaps(name) + "Api"; String paramName = name.replaceAll("[^a-zA-Z0-9_]", "");
} paramName = Character.toUpperCase(paramName.charAt(0)) + paramName.substring(1);
return "p" + paramName;
}
public String toApiFilename(String name) { public String escapeReservedWord(String name) {
return PREFIX + initialCaps(name) + "Api"; return "_" + name;
} }
@Override @Override
public String toVarName(String name) { public String toOperationId(String operationId) {
String paramName = name.replaceAll("[^a-zA-Z0-9_]",""); // method name cannot use reserved keyword, e.g. return$
paramName = Character.toUpperCase(paramName.charAt(0)) + paramName.substring(1); if (reservedWords.contains(operationId)) {
return "p" + paramName; throw new RuntimeException(operationId + " (reserved word) cannot be used as method name");
} }
public String escapeReservedWord(String name) { // add_pet_by_id => addPetById
return "_" + name; return camelize(operationId, true);
} }
@Override
public String toOperationId(String operationId) {
// method name cannot use reserved keyword, e.g. return$
if(reservedWords.contains(operationId))
throw new RuntimeException(operationId + " (reserved word) cannot be used as method name");
// add_pet_by_id => addPetById
return camelize(operationId, true);
}
} }

View File

@ -8,43 +8,43 @@ import static java.net.URI.create;
class ApiUtils { class ApiUtils {
def invokeApi(onSuccess, onFailure, basePath, versionPath, resourcePath, queryParams, headerParams, method, container, type) { def invokeApi(onSuccess, onFailure, basePath, versionPath, resourcePath, queryParams, headerParams, method, container, type) {
def (url, uriPath) = buildUrlAndUriPath(basePath, versionPath, resourcePath) def (url, uriPath) = buildUrlAndUriPath(basePath, versionPath, resourcePath)
println "url=$url uriPath=$uriPath" println "url=$url uriPath=$uriPath"
def http = new HTTPBuilder(url) def http = new HTTPBuilder(url)
http.request( Method.valueOf(method), JSON ) { http.request( Method.valueOf(method), JSON ) {
uri.path = uriPath uri.path = uriPath
uri.query = queryParams uri.query = queryParams
response.success = { resp, json -> response.success = { resp, json ->
if (type != null) { if (type != null) {
onSuccess(parse(json, container, type)) onSuccess(parse(json, container, type))
} }
} }
response.failure = { resp -> response.failure = { resp ->
onFailure(resp.status, resp.statusLine.reasonPhrase) onFailure(resp.status, resp.statusLine.reasonPhrase)
} }
} }
} }
def buildUrlAndUriPath(basePath, versionPath, resourcePath) { def buildUrlAndUriPath(basePath, versionPath, resourcePath) {
// HTTPBuilder expects to get as its constructor parameter an URL, // HTTPBuilder expects to get as its constructor parameter an URL,
// without any other additions like path, therefore we need to cut the path // without any other additions like path, therefore we need to cut the path
// from the basePath as it is represented by swagger APIs // from the basePath as it is represented by swagger APIs
// we use java.net.URI to manipulate the basePath // we use java.net.URI to manipulate the basePath
// then the uriPath will hold the rest of the path // then the uriPath will hold the rest of the path
URI baseUri = create(basePath) URI baseUri = create(basePath)
def pathOnly = baseUri.getPath() def pathOnly = baseUri.getPath()
[basePath-pathOnly, pathOnly+versionPath+resourcePath] [basePath-pathOnly, pathOnly+versionPath+resourcePath]
} }
def parse(object, container, clazz) { def parse(object, container, clazz) {
if (container == "List") { if (container == "List") {
return object.collect {parse(it, "", clazz)} return object.collect {parse(it, "", clazz)}
} else { } else {
return clazz.newInstance(object) return clazz.newInstance(object)
} }
} }
} }

View File

@ -1,9 +1,6 @@
package {{package}}; package {{package}};
import groovyx.net.http.* import groovyx.net.http.*
import static groovyx.net.http.ContentType.* import static groovyx.net.http.ContentType.*
import static groovyx.net.http.Method.* import static groovyx.net.http.Method.*
@ -17,40 +14,40 @@ import java.util.*;
@Mixin(ApiUtils) @Mixin(ApiUtils)
{{#operations}} {{#operations}}
class {{classname}} { class {{classname}} {
String basePath = "{{basePath}}" String basePath = "{{basePath}}"
String versionPath = "/api/v1" String versionPath = "/api/v1"
{{#operation}} {{#operation}}
def {{nickname}} ({{#allParams}} {{{dataType}}} {{paramName}},{{/allParams}} Closure onSuccess, Closure onFailure) { def {{nickname}} ({{#allParams}} {{{dataType}}} {{paramName}},{{/allParams}} Closure onSuccess, Closure onFailure) {
// create path and map variables // create path and map variables
String resourcePath = "{{path}}" String resourcePath = "{{path}}"
// query params // query params
def queryParams = [:] def queryParams = [:]
def headerParams = [:] def headerParams = [:]
{{#requiredParamCount}} {{#requiredParamCount}}
// verify required params are set // verify required params are set
if({{/requiredParamCount}}{{#requiredParams}} {{paramName}} == null {{#hasMore}}|| {{/hasMore}}{{/requiredParams}}{{#requiredParamCount}}) { if({{/requiredParamCount}}{{#requiredParams}} {{paramName}} == null {{#hasMore}}|| {{/hasMore}}{{/requiredParams}}{{#requiredParamCount}}) {
throw new RuntimeException("missing required params") throw new RuntimeException("missing required params")
}
{{/requiredParamCount}}
{{#queryParams}}if(!"null".equals(String.valueOf({{paramName}})))
queryParams.put("{{paramName}}", String.valueOf({{paramName}}))
{{/queryParams}}
{{#headerParams}}headerParams.put("{{paramName}}", {{paramName}})
{{/headerParams}}
invokeApi(onSuccess, onFailure, basePath, versionPath, resourcePath, queryParams, headerParams,
"{{httpMethod}}", "{{returnContainer}}",
{{#returnBaseType}}{{{returnBaseType}}}.class {{/returnBaseType}}{{^returnBaseType}}null {{/returnBaseType}})
}
{{/operation}}
} }
{{/requiredParamCount}}
{{#queryParams}}if(!"null".equals(String.valueOf({{paramName}})))
queryParams.put("{{paramName}}", String.valueOf({{paramName}}))
{{/queryParams}}
{{#headerParams}}headerParams.put("{{paramName}}", {{paramName}})
{{/headerParams}}
invokeApi(onSuccess, onFailure, basePath, versionPath, resourcePath, queryParams, headerParams,
"{{httpMethod}}", "{{returnContainer}}",
{{#returnBaseType}}{{{returnBaseType}}}.class {{/returnBaseType}}{{^returnBaseType}}null {{/returnBaseType}})
}
{{/operation}}
}
{{/operations}} {{/operations}}

View File

@ -6,24 +6,24 @@ archivesBaseName = 'swagger-gen-groovy'
version = '0.1' version = '0.1'
buildscript { buildscript {
repositories { repositories {
maven { url 'http://repo.jfrog.org/artifactory/gradle-plugins' } maven { url 'http://repo.jfrog.org/artifactory/gradle-plugins' }
} }
dependencies { dependencies {
classpath(group: 'org.jfrog.buildinfo', name: 'build-info-extractor-gradle', version: '2.0.16') classpath(group: 'org.jfrog.buildinfo', name: 'build-info-extractor-gradle', version: '2.0.16')
} }
} }
repositories { repositories {
mavenCentral() mavenCentral()
mavenLocal() mavenLocal()
mavenCentral(artifactUrls: ['http://maven.springframework.org/milestone']) mavenCentral(artifactUrls: ['http://maven.springframework.org/milestone'])
maven { url "http://$artifactory:8080/artifactory/repo" } maven { url "http://$artifactory:8080/artifactory/repo" }
} }
dependencies { dependencies {
groovy "org.codehaus.groovy:groovy-all:2.0.5" groovy "org.codehaus.groovy:groovy-all:2.0.5"
compile 'org.codehaus.groovy.modules.http-builder:http-builder:0.6' compile 'org.codehaus.groovy.modules.http-builder:http-builder:0.6'
} }

View File

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

View File

@ -40,468 +40,482 @@ import {{invokerPackage}}.auth.ApiKeyAuth;
import {{invokerPackage}}.auth.OAuth; import {{invokerPackage}}.auth.OAuth;
public class ApiClient { public class ApiClient {
private Map<String, Client> hostMap = new HashMap<String, Client>(); private Map
private Map<String, String> defaultHeaderMap = new HashMap<String, String>(); <String, Client> hostMap = new HashMap
private boolean debugging = false; <String, Client>();
private String basePath = "{{basePath}}"; private Map
<String, String> defaultHeaderMap = new HashMap
<String, String>();
private boolean debugging = false;
private String basePath = "{{basePath}}";
private Map<String, Authentication> authentications; private Map
<String, Authentication> authentications;
private DateFormat dateFormat; private DateFormat dateFormat;
public ApiClient() { public ApiClient() {
// Use ISO 8601 format for date and datetime. // Use ISO 8601 format for date and datetime.
// See https://en.wikipedia.org/wiki/ISO_8601 // See https://en.wikipedia.org/wiki/ISO_8601
this.dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); this.dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
// Use UTC as the default time zone. // Use UTC as the default time zone.
this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
// Set default User-Agent. // Set default User-Agent.
setUserAgent("Java-Swagger"); setUserAgent("Java-Swagger");
// Setup authentications (key: authentication name, value: authentication). // Setup authentications (key: authentication name, value: authentication).
authentications = new HashMap<String, Authentication>();{{#authMethods}}{{#isBasic}} authentications = new HashMap
<String, Authentication>();{{#authMethods}}{{#isBasic}}
authentications.put("{{name}}", new HttpBasicAuth());{{/isBasic}}{{#isApiKey}} authentications.put("{{name}}", new HttpBasicAuth());{{/isBasic}}{{#isApiKey}}
authentications.put("{{name}}", new ApiKeyAuth({{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{^isKeyInHeader}}"query"{{/isKeyInHeader}}, "{{keyParamName}}"));{{/isApiKey}}{{#isOAuth}} authentications.put("{{name}}", new ApiKeyAuth({{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{^isKeyInHeader}}"query"{{/isKeyInHeader}}, "{{keyParamName}}"));{{/isApiKey}}{{#isOAuth}}
authentications.put("{{name}}", new OAuth());{{/isOAuth}}{{/authMethods}} authentications.put("{{name}}", new OAuth());{{/isOAuth}}{{/authMethods}}
// Prevent the authentications from being modified. // Prevent the authentications from being modified.
authentications = Collections.unmodifiableMap(authentications); authentications = Collections.unmodifiableMap(authentications);
} }
public String getBasePath() { public String getBasePath() {
return basePath; return basePath;
} }
public ApiClient setBasePath(String basePath) { public ApiClient setBasePath(String basePath) {
this.basePath = basePath; this.basePath = basePath;
return this; return this;
} }
/** /**
* Get authentications (key: authentication name, value: authentication). * Get authentications (key: authentication name, value: authentication).
*/ */
public Map<String, Authentication> getAuthentications() { public Map
return authentications; <String, Authentication> getAuthentications() {
} return authentications;
}
/**
* Get authentication for the given name. /**
* * Get authentication for the given name.
* @param authName The authentication name *
* @return The authentication, null if not found * @param authName The authentication name
*/ * @return The authentication, null if not found
public Authentication getAuthentication(String authName) { */
return authentications.get(authName); public Authentication getAuthentication(String authName) {
} return authentications.get(authName);
}
/**
* Helper method to set username for the first HTTP basic authentication. /**
*/ * Helper method to set username for the first HTTP basic authentication.
public void setUsername(String username) { */
for (Authentication auth : authentications.values()) { public void setUsername(String username) {
if (auth instanceof HttpBasicAuth) { for (Authentication auth : authentications.values()) {
((HttpBasicAuth) auth).setUsername(username); if (auth instanceof HttpBasicAuth) {
return; ((HttpBasicAuth) auth).setUsername(username);
} return;
} }
throw new RuntimeException("No HTTP basic authentication configured!"); }
} throw new RuntimeException("No HTTP basic authentication configured!");
}
/**
* Helper method to set password for the first HTTP basic authentication. /**
*/ * Helper method to set password for the first HTTP basic authentication.
public void setPassword(String password) { */
for (Authentication auth : authentications.values()) { public void setPassword(String password) {
if (auth instanceof HttpBasicAuth) { for (Authentication auth : authentications.values()) {
((HttpBasicAuth) auth).setPassword(password); if (auth instanceof HttpBasicAuth) {
return; ((HttpBasicAuth) auth).setPassword(password);
} return;
} }
throw new RuntimeException("No HTTP basic authentication configured!"); }
} throw new RuntimeException("No HTTP basic authentication configured!");
}
/**
* Helper method to set API key value for the first API key authentication. /**
*/ * Helper method to set API key value for the first API key authentication.
public void setApiKey(String apiKey) { */
for (Authentication auth : authentications.values()) { public void setApiKey(String apiKey) {
if (auth instanceof ApiKeyAuth) { for (Authentication auth : authentications.values()) {
((ApiKeyAuth) auth).setApiKey(apiKey); if (auth instanceof ApiKeyAuth) {
return; ((ApiKeyAuth) auth).setApiKey(apiKey);
} return;
} }
throw new RuntimeException("No API key authentication configured!"); }
} throw new RuntimeException("No API key authentication configured!");
}
/**
* Helper method to set API key prefix for the first API key authentication. /**
*/ * Helper method to set API key prefix for the first API key authentication.
public void setApiKeyPrefix(String apiKeyPrefix) { */
for (Authentication auth : authentications.values()) { public void setApiKeyPrefix(String apiKeyPrefix) {
if (auth instanceof ApiKeyAuth) { for (Authentication auth : authentications.values()) {
((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix); if (auth instanceof ApiKeyAuth) {
return; ((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix);
} return;
} }
throw new RuntimeException("No API key authentication configured!"); }
} throw new RuntimeException("No API key authentication configured!");
}
/**
* Set the User-Agent header's value (by adding to the default header map). /**
*/ * Set the User-Agent header's value (by adding to the default header map).
public ApiClient setUserAgent(String userAgent) { */
addDefaultHeader("User-Agent", userAgent); public ApiClient setUserAgent(String userAgent) {
return this; addDefaultHeader("User-Agent", userAgent);
} return this;
}
/**
* Add a default header. /**
* * Add a default header.
* @param key The header's key *
* @param value The header's value * @param key The header's key
*/ * @param value The header's value
public ApiClient addDefaultHeader(String key, String value) { */
defaultHeaderMap.put(key, value); public ApiClient addDefaultHeader(String key, String value) {
return this; defaultHeaderMap.put(key, value);
} return this;
}
/**
* Check that whether debugging is enabled for this API client. /**
*/ * Check that whether debugging is enabled for this API client.
public boolean isDebugging() { */
return debugging; public boolean isDebugging() {
} return debugging;
}
/**
* Enable/disable debugging for this API client. /**
* * Enable/disable debugging for this API client.
* @param debugging To enable (true) or disable (false) debugging *
*/ * @param debugging To enable (true) or disable (false) debugging
public ApiClient setDebugging(boolean debugging) { */
this.debugging = debugging; public ApiClient setDebugging(boolean debugging) {
return this; this.debugging = debugging;
} return this;
}
/**
* Get the date format used to parse/format date parameters. /**
*/ * Get the date format used to parse/format date parameters.
public DateFormat getDateFormat() { */
return dateFormat; public DateFormat getDateFormat() {
} return dateFormat;
}
/**
* Set the date format used to parse/format date parameters. /**
*/ * Set the date format used to parse/format date parameters.
public ApiClient getDateFormat(DateFormat dateFormat) { */
this.dateFormat = dateFormat; public ApiClient getDateFormat(DateFormat dateFormat) {
return this; this.dateFormat = dateFormat;
} return this;
}
/**
* Parse the given string into Date object. /**
*/ * Parse the given string into Date object.
public Date parseDate(String str) { */
try { public Date parseDate(String str) {
return dateFormat.parse(str); try {
} catch (java.text.ParseException e) { return dateFormat.parse(str);
throw new RuntimeException(e); } catch (java.text.ParseException e) {
} throw new RuntimeException(e);
} }
}
/**
* Format the given Date object into string. /**
*/ * Format the given Date object into string.
public String formatDate(Date date) { */
return dateFormat.format(date); public String formatDate(Date date) {
} return dateFormat.format(date);
}
/**
* Format the given parameter object into string. /**
*/ * Format the given parameter object into string.
public String parameterToString(Object param) { */
if (param == null) { public String parameterToString(Object param) {
return ""; if (param == null) {
} else if (param instanceof Date) { return "";
return formatDate((Date) param); } else if (param instanceof Date) {
} else if (param instanceof Collection) { return formatDate((Date) param);
StringBuilder b = new StringBuilder(); } else if (param instanceof Collection) {
for(Object o : (Collection)param) { StringBuilder b = new StringBuilder();
if(b.length() > 0) { for(Object o : (Collection)param) {
b.append(","); if(b.length() > 0) {
} b.append(",");
b.append(String.valueOf(o)); }
} b.append(String.valueOf(o));
return b.toString(); }
} else { return b.toString();
return String.valueOf(param); } else {
} return String.valueOf(param);
} }
}
/**
* Select the Accept header's value from the given accepts array: /**
* if JSON exists in the given array, use it; * Select the Accept header's value from the given accepts array:
* otherwise use all of them (joining into a string) * if JSON exists in the given array, use it;
* * otherwise use all of them (joining into a string)
* @param accepts The accepts array to select from *
* @return The Accept header to use. If the given array is empty, * @param accepts The accepts array to select from
* null will be returned (not to set the Accept header explicitly). * @return The Accept header to use. If the given array is empty,
*/ * null will be returned (not to set the Accept header explicitly).
public String selectHeaderAccept(String[] accepts) { */
if (accepts.length == 0) return null; public String selectHeaderAccept(String[] accepts) {
if (StringUtil.containsIgnoreCase(accepts, "application/json")) return "application/json"; if (accepts.length == 0) return null;
return StringUtil.join(accepts, ","); if (StringUtil.containsIgnoreCase(accepts, "application/json")) return "application/json";
} return StringUtil.join(accepts, ",");
}
/**
* Select the Content-Type header's value from the given array: /**
* if JSON exists in the given array, use it; * Select the Content-Type header's value from the given array:
* otherwise use the first one of the array. * if JSON exists in the given array, use it;
* * otherwise use the first one of the array.
* @param contentTypes The Content-Type array to select from *
* @return The Content-Type header to use. If the given array is empty, * @param contentTypes The Content-Type array to select from
* JSON will be used. * @return The Content-Type header to use. If the given array is empty,
*/ * JSON will be used.
public String selectHeaderContentType(String[] contentTypes) { */
if (contentTypes.length == 0) return "application/json"; public String selectHeaderContentType(String[] contentTypes) {
if (StringUtil.containsIgnoreCase(contentTypes, "application/json")) return "application/json"; if (contentTypes.length == 0) return "application/json";
return contentTypes[0]; if (StringUtil.containsIgnoreCase(contentTypes, "application/json")) return "application/json";
} return contentTypes[0];
}
/**
* Escape the given string to be used as URL query value. /**
*/ * Escape the given string to be used as URL query value.
public String escapeString(String str) { */
try { public String escapeString(String str) {
return URLEncoder.encode(str, "utf8").replaceAll("\\+", "%20"); try {
} catch (UnsupportedEncodingException e) { return URLEncoder.encode(str, "utf8").replaceAll("\\+", "%20");
return str; } catch (UnsupportedEncodingException e) {
} return str;
} }
}
/**
* Deserialize the given JSON string to Java object. /**
* * Deserialize the given JSON string to Java object.
* @param json The JSON string *
* @param containerType The container type, one of "list", "array" or "" * @param json The JSON string
* @param cls The type of the Java object * @param containerType The container type, one of "list", "array" or ""
* @return The deserialized Java object * @param cls The type of the Java object
*/ * @return The deserialized Java object
public Object deserialize(String json, String containerType, Class cls) throws ApiException { */
if(null != containerType) { public Object deserialize(String json, String containerType, Class cls) throws ApiException {
containerType = containerType.toLowerCase(); if(null != containerType) {
} containerType = containerType.toLowerCase();
try{ }
if("list".equals(containerType) || "array".equals(containerType)) { try{
JavaType typeInfo = JsonUtil.getJsonMapper().getTypeFactory().constructCollectionType(List.class, cls); if("list".equals(containerType) || "array".equals(containerType)) {
List response = (List<?>) JsonUtil.getJsonMapper().readValue(json, typeInfo); JavaType typeInfo = JsonUtil.getJsonMapper().getTypeFactory().constructCollectionType(List.class, cls);
return response; 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) else if(String.class.equals(cls)) {
return json.substring(1, json.length() - 2); if(json != null && json.startsWith("\"") && json.endsWith("\"") && json.length() > 1)
else return json.substring(1, json.length() - 2);
return json; else
} return json;
else { }
return JsonUtil.getJsonMapper().readValue(json, cls); else {
} return JsonUtil.getJsonMapper().readValue(json, cls);
} }
catch (IOException e) { }
throw new ApiException(500, e.getMessage(), null, json); catch (IOException e) {
} throw new ApiException(500, e.getMessage(), null, json);
} }
}
/**
* Serialize the given Java object into JSON string. /**
*/ * Serialize the given Java object into JSON string.
public String serialize(Object obj) throws ApiException { */
try { public String serialize(Object obj) throws ApiException {
if (obj != null) try {
return JsonUtil.getJsonMapper().writeValueAsString(obj); if (obj != null)
else return JsonUtil.getJsonMapper().writeValueAsString(obj);
return null; else
} return null;
catch (Exception e) { }
throw new ApiException(500, e.getMessage()); catch (Exception e) {
} throw new ApiException(500, e.getMessage());
} }
}
/**
* Invoke API by sending HTTP request with the given options. /**
* * Invoke API by sending HTTP request with the given options.
* @param path The sub-path of the HTTP URL *
* @param method The request method, one of "GET", "POST", "PUT", and "DELETE" * @param path The sub-path of the HTTP URL
* @param queryParams The query parameters * @param method The request method, one of "GET", "POST", "PUT", and "DELETE"
* @param body The request body object * @param queryParams The query parameters
* @param headerParams The header parameters * @param body The request body object
* @param formParams The form parameters * @param headerParams The header parameters
* @param accept The request's Accept header * @param formParams The form parameters
* @param contentType The request's Content-Type header * @param accept The request's Accept header
* @param authNames The authentications to apply * @param contentType The request's Content-Type header
* @return The response body in type of string * @param authNames The authentications to apply
*/ * @return The response body in type of string
public String invokeAPI(String path, String method, Map<String, String> queryParams, Object body, Map<String, String> headerParams, Map<String, String> formParams, String accept, String contentType, String[] authNames) throws ApiException { */
updateParamsForAuth(authNames, queryParams, headerParams); public String invokeAPI(String path, String method, Map
<String, String> queryParams, Object body, Map
Client client = getClient(); <String, String> headerParams, Map
<String, String> formParams, String accept, String contentType, String[] authNames) throws ApiException {
StringBuilder b = new StringBuilder(); updateParamsForAuth(authNames, queryParams, headerParams);
for(String key : queryParams.keySet()) {
String value = queryParams.get(key); Client client = getClient();
if (value != null){
if(b.toString().length() == 0) StringBuilder b = new StringBuilder();
b.append("?"); for(String key : queryParams.keySet()) {
else String value = queryParams.get(key);
b.append("&"); if (value != null){
b.append(escapeString(key)).append("=").append(escapeString(value)); if(b.toString().length() == 0)
} b.append("?");
} else
String querystring = b.toString(); b.append("&");
b.append(escapeString(key)).append("=").append(escapeString(value));
Builder builder; }
if (accept == null) }
builder = client.resource(basePath + path + querystring).getRequestBuilder(); String querystring = b.toString();
else
builder = client.resource(basePath + path + querystring).accept(accept); Builder builder;
if (accept == null)
for(String key : headerParams.keySet()) { builder = client.resource(basePath + path + querystring).getRequestBuilder();
builder = builder.header(key, headerParams.get(key)); else
} builder = client.resource(basePath + path + querystring).accept(accept);
for(String key : defaultHeaderMap.keySet()) {
if(!headerParams.containsKey(key)) { for(String key : headerParams.keySet()) {
builder = builder.header(key, defaultHeaderMap.get(key)); builder = builder.header(key, headerParams.get(key));
} }
} for(String key : defaultHeaderMap.keySet()) {
if(!headerParams.containsKey(key)) {
ClientResponse response = null; builder = builder.header(key, defaultHeaderMap.get(key));
}
if("GET".equals(method)) { }
response = (ClientResponse) builder.get(ClientResponse.class);
} ClientResponse response = null;
else if ("POST".equals(method)) {
if (contentType.startsWith("application/x-www-form-urlencoded")) { if("GET".equals(method)) {
String encodedFormParams = this response = (ClientResponse) builder.get(ClientResponse.class);
.getXWWWFormUrlencodedParams(formParams); }
response = builder.type(contentType).post(ClientResponse.class, else if ("POST".equals(method)) {
encodedFormParams); if (contentType.startsWith("application/x-www-form-urlencoded")) {
} else if (body == null) { String encodedFormParams = this
response = builder.post(ClientResponse.class, null); .getXWWWFormUrlencodedParams(formParams);
} else if(body instanceof FormDataMultiPart) { response = builder.type(contentType).post(ClientResponse.class,
response = builder.type(contentType).post(ClientResponse.class, body); encodedFormParams);
} } else if (body == null) {
else response = builder.post(ClientResponse.class, null);
response = builder.type(contentType).post(ClientResponse.class, serialize(body)); } else if(body instanceof FormDataMultiPart) {
} response = builder.type(contentType).post(ClientResponse.class, body);
else if ("PUT".equals(method)) { }
if ("application/x-www-form-urlencoded".equals(contentType)) { else
String encodedFormParams = this response = builder.type(contentType).post(ClientResponse.class, serialize(body));
.getXWWWFormUrlencodedParams(formParams); }
response = builder.type(contentType).put(ClientResponse.class, else if ("PUT".equals(method)) {
encodedFormParams); if ("application/x-www-form-urlencoded".equals(contentType)) {
} else if(body == null) { String encodedFormParams = this
response = builder.put(ClientResponse.class, serialize(body)); .getXWWWFormUrlencodedParams(formParams);
} else { response = builder.type(contentType).put(ClientResponse.class,
response = builder.type(contentType).put(ClientResponse.class, serialize(body)); encodedFormParams);
} } else if(body == null) {
} response = builder.put(ClientResponse.class, serialize(body));
else if ("DELETE".equals(method)) { } else {
if ("application/x-www-form-urlencoded".equals(contentType)) { response = builder.type(contentType).put(ClientResponse.class, serialize(body));
String encodedFormParams = this }
.getXWWWFormUrlencodedParams(formParams); }
response = builder.type(contentType).delete(ClientResponse.class, else if ("DELETE".equals(method)) {
encodedFormParams); if ("application/x-www-form-urlencoded".equals(contentType)) {
} else if(body == null) { String encodedFormParams = this
response = builder.delete(ClientResponse.class); .getXWWWFormUrlencodedParams(formParams);
} else { response = builder.type(contentType).delete(ClientResponse.class,
response = builder.type(contentType).delete(ClientResponse.class, serialize(body)); encodedFormParams);
} } else if(body == null) {
} response = builder.delete(ClientResponse.class);
else { } else {
throw new ApiException(500, "unknown method type " + method); response = builder.type(contentType).delete(ClientResponse.class, serialize(body));
} }
}
if(response.getClientResponseStatus() == ClientResponse.Status.NO_CONTENT) { else {
return null; throw new ApiException(500, "unknown method type " + method);
} }
else if(response.getClientResponseStatus().getFamily() == Family.SUCCESSFUL) {
if(response.hasEntity()) { if(response.getClientResponseStatus() == ClientResponse.Status.NO_CONTENT) {
return (String) response.getEntity(String.class); return null;
} }
else { else if(response.getClientResponseStatus().getFamily() == Family.SUCCESSFUL) {
return ""; if(response.hasEntity()) {
} return (String) response.getEntity(String.class);
} }
else { else {
String message = "error"; return "";
String respBody = null; }
if(response.hasEntity()) { }
try{ else {
respBody = String.valueOf(response.getEntity(String.class)); String message = "error";
message = respBody; String respBody = null;
} if(response.hasEntity()) {
catch (RuntimeException e) { try{
// e.printStackTrace(); respBody = String.valueOf(response.getEntity(String.class));
} message = respBody;
} }
throw new ApiException( catch (RuntimeException e) {
response.getClientResponseStatus().getStatusCode(), // e.printStackTrace();
message, }
response.getHeaders(), }
respBody); throw new ApiException(
} response.getClientResponseStatus().getStatusCode(),
} message,
response.getHeaders(),
/** respBody);
* Update query and header parameters based on authentication settings. }
* }
* @param authNames The authentications to apply
*/ /**
private void updateParamsForAuth(String[] authNames, Map<String, String> queryParams, Map<String, String> headerParams) { * Update query and header parameters based on authentication settings.
for (String authName : authNames) { *
Authentication auth = authentications.get(authName); * @param authNames The authentications to apply
if (auth == null) throw new RuntimeException("Authentication undefined: " + authName); */
auth.applyToParams(queryParams, headerParams); private void updateParamsForAuth(String[] authNames, Map
} <String, String> queryParams, Map
} <String, String> headerParams) {
for (String authName : authNames) {
/** Authentication auth = authentications.get(authName);
* Encode the given form parameters as request body. if (auth == null) throw new RuntimeException("Authentication undefined: " + authName);
*/ auth.applyToParams(queryParams, headerParams);
private String getXWWWFormUrlencodedParams(Map<String, String> formParams) { }
StringBuilder formParamBuilder = new StringBuilder(); }
for (Entry<String, String> param : formParams.entrySet()) { /**
String keyStr = parameterToString(param.getKey()); * Encode the given form parameters as request body.
String valueStr = parameterToString(param.getValue()); */
private String getXWWWFormUrlencodedParams(Map
try { <String, String> formParams) {
formParamBuilder.append(URLEncoder.encode(keyStr, "utf8")) StringBuilder formParamBuilder = new StringBuilder();
.append("=")
.append(URLEncoder.encode(valueStr, "utf8")); for (Entry
formParamBuilder.append("&"); <String, String> param : formParams.entrySet()) {
} catch (UnsupportedEncodingException e) { String keyStr = parameterToString(param.getKey());
// move on to next String valueStr = parameterToString(param.getValue());
}
} try {
String encodedFormParams = formParamBuilder.toString(); formParamBuilder.append(URLEncoder.encode(keyStr, "utf8"))
if (encodedFormParams.endsWith("&")) { .append("=")
encodedFormParams = encodedFormParams.substring(0, .append(URLEncoder.encode(valueStr, "utf8"));
encodedFormParams.length() - 1); formParamBuilder.append("&");
} } catch (UnsupportedEncodingException e) {
return encodedFormParams; // move on to next
} }
}
/** String encodedFormParams = formParamBuilder.toString();
* Get an existing client or create a new client to handle HTTP request. if (encodedFormParams.endsWith("&")) {
*/ encodedFormParams = encodedFormParams.substring(0,
private Client getClient() { encodedFormParams.length() - 1);
if(!hostMap.containsKey(basePath)) { }
Client client = Client.create(); return encodedFormParams;
if (debugging) }
client.addFilter(new LoggingFilter());
hostMap.put(basePath, client); /**
} * Get an existing client or create a new client to handle HTTP request.
return hostMap.get(basePath); */
} private Client getClient() {
if(!hostMap.containsKey(basePath)) {
Client client = Client.create();
if (debugging)
client.addFilter(new LoggingFilter());
hostMap.put(basePath, client);
}
return hostMap.get(basePath);
}
} }

View File

@ -1,21 +1,21 @@
package {{invokerPackage}}; package {{invokerPackage}};
public class Configuration { public class Configuration {
private static ApiClient defaultApiClient = new ApiClient(); private static ApiClient defaultApiClient = new ApiClient();
/** /**
* Get the default API client, which would be used when creating API * Get the default API client, which would be used when creating API
* instances without providing an API client. * instances without providing an API client.
*/ */
public static ApiClient getDefaultApiClient() { public static ApiClient getDefaultApiClient() {
return defaultApiClient; return defaultApiClient;
} }
/** /**
* Set the default API client, which would be used when creating API * Set the default API client, which would be used when creating API
* instances without providing an API client. * instances without providing an API client.
*/ */
public static void setDefaultApiClient(ApiClient apiClient) { public static void setDefaultApiClient(ApiClient apiClient) {
defaultApiClient = apiClient; defaultApiClient = apiClient;
} }
} }

View File

@ -8,16 +8,16 @@ import com.fasterxml.jackson.core.JsonGenerator.Feature;
import com.fasterxml.jackson.datatype.joda.*; import com.fasterxml.jackson.datatype.joda.*;
public class JsonUtil { public class JsonUtil {
public static ObjectMapper mapper; public static ObjectMapper mapper;
static { static {
mapper = new ObjectMapper(); mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
mapper.registerModule(new JodaModule()); mapper.registerModule(new JodaModule());
} }
public static ObjectMapper getJsonMapper() { public static ObjectMapper getJsonMapper() {
return mapper; return mapper;
} }
} }

View File

@ -1,41 +1,41 @@
package {{invokerPackage}}; package {{invokerPackage}};
public class StringUtil { public class StringUtil {
/** /**
* Check if the given array contains the given value (with case-insensitive comparison). * Check if the given array contains the given value (with case-insensitive comparison).
* *
* @param array The array * @param array The array
* @param value The value to search * @param value The value to search
* @return true if the array contains the value * @return true if the array contains the value
*/ */
public static boolean containsIgnoreCase(String[] array, String value) { public static boolean containsIgnoreCase(String[] array, String value) {
for (String str : array) { for (String str : array) {
if (value == null && str == null) return true; if (value == null && str == null) return true;
if (value != null && value.equalsIgnoreCase(str)) return true; if (value != null && value.equalsIgnoreCase(str)) return true;
} }
return false; return false;
} }
/** /**
* Join an array of strings with the given separator. * Join an array of strings with the given separator.
* <p> * <p>
* Note: This might be replaced by utility method from commons-lang or guava someday * Note: This might be replaced by utility method from commons-lang or guava someday
* if one of those libraries is added as dependency. * if one of those libraries is added as dependency.
* </p> * </p>
* *
* @param array The array of strings * @param array The array of strings
* @param separator The separator * @param separator The separator
* @return the resulting string * @return the resulting string
*/ */
public static String join(String[] array, String separator) { public static String join(String[] array, String separator) {
int len = array.length; int len = array.length;
if (len == 0) return ""; if (len == 0) return "";
StringBuilder out = new StringBuilder(); StringBuilder out = new StringBuilder();
out.append(array[0]); out.append(array[0]);
for (int i = 1; i < len; i++) { for (int i = 1; i < len; i++) {
out.append(separator).append(array[i]); out.append(separator).append(array[i]);
} }
return out.toString(); return out.toString();
} }
} }

View File

@ -21,105 +21,111 @@ import java.util.Map;
import java.util.HashMap; import java.util.HashMap;
{{#operations}} {{#operations}}
public class {{classname}} { public class {{classname}} {
private ApiClient apiClient; private ApiClient apiClient;
public {{classname}}() { public {{classname}}() {
this(Configuration.getDefaultApiClient()); this(Configuration.getDefaultApiClient());
} }
public {{classname}}(ApiClient apiClient) { public {{classname}}(ApiClient apiClient) {
this.apiClient = apiClient; this.apiClient = apiClient;
} }
public ApiClient getApiClient() { public ApiClient getApiClient() {
return apiClient; return apiClient;
} }
public void setApiClient(ApiClient apiClient) { public void setApiClient(ApiClient apiClient) {
this.apiClient = apiClient; this.apiClient = apiClient;
}
{{#operation}}
/**
* {{summary}}
* {{notes}}
{{#allParams}} * @param {{paramName}} {{description}}
{{/allParams}} * @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}}
*/
public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}}{{nickname}} ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws ApiException {
Object postBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}};
{{#allParams}}{{#required}}
// verify the required parameter '{{paramName}}' is set
if ({{paramName}} == null) {
throw new ApiException(400, "Missing the required parameter '{{paramName}}' when calling {{nickname}}");
} }
{{/required}}{{/allParams}}
// create path and map variables {{#operation}}
String path = "{{path}}".replaceAll("\\{format\\}","json"){{#pathParams}} /**
.replaceAll("\\{" + "{{paramName}}" + "\\}", apiClient.escapeString({{{paramName}}}.toString())){{/pathParams}}; * {{summary}}
* {{notes}}
{{#allParams}} * @param {{paramName}} {{description}}
{{/allParams}} * @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}}
*/
public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}}{{nickname}} ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws ApiException {
Object postBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}};
{{#allParams}}{{#required}}
// verify the required parameter '{{paramName}}' is set
if ({{paramName}} == null) {
throw new ApiException(400, "Missing the required parameter '{{paramName}}' when calling {{nickname}}");
}
{{/required}}{{/allParams}}
// query params // create path and map variables
Map<String, String> queryParams = new HashMap<String, String>(); String path = "{{path}}".replaceAll("\\{format\\}","json"){{#pathParams}}
Map<String, String> headerParams = new HashMap<String, String>(); .replaceAll("\\{" + "{{paramName}}" + "\\}", apiClient.escapeString({{{paramName}}}.toString())){{/pathParams}};
Map<String, String> formParams = new HashMap<String, String>();
{{#queryParams}}if ({{paramName}} != null) // query params
queryParams.put("{{baseName}}", apiClient.parameterToString({{paramName}})); Map
{{/queryParams}} <String, String> queryParams = new HashMap
<String, String>();
Map
<String, String> headerParams = new HashMap
<String, String>();
Map
<String, String> formParams = new HashMap
<String, String>();
{{#headerParams}}if ({{paramName}} != null) {{#queryParams}}if ({{paramName}} != null)
headerParams.put("{{baseName}}", apiClient.parameterToString({{paramName}})); queryParams.put("{{baseName}}", apiClient.parameterToString({{paramName}}));
{{/headerParams}} {{/queryParams}}
final String[] accepts = { {{#headerParams}}if ({{paramName}} != null)
{{#produces}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}} headerParams.put("{{baseName}}", apiClient.parameterToString({{paramName}}));
}; {{/headerParams}}
final String accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = { final String[] accepts = {
{{#consumes}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} {{#produces}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}}
}; };
final String contentType = apiClient.selectHeaderContentType(contentTypes); final String accept = apiClient.selectHeaderAccept(accepts);
if(contentType.startsWith("multipart/form-data")) { final String[] contentTypes = {
boolean hasFields = false; {{#consumes}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/consumes}}
FormDataMultiPart mp = new FormDataMultiPart(); };
{{#formParams}}{{#notFile}} final String contentType = apiClient.selectHeaderContentType(contentTypes);
if ({{paramName}} != null) {
hasFields = true; if(contentType.startsWith("multipart/form-data")) {
mp.field("{{baseName}}", apiClient.parameterToString({{paramName}}), MediaType.MULTIPART_FORM_DATA_TYPE); boolean hasFields = false;
} FormDataMultiPart mp = new FormDataMultiPart();
{{/notFile}}{{#isFile}} {{#formParams}}{{#notFile}}
if ({{paramName}} != null) { if ({{paramName}} != null) {
hasFields = true; hasFields = true;
mp.field("{{baseName}}", {{paramName}}.getName()); mp.field("{{baseName}}", apiClient.parameterToString({{paramName}}), MediaType.MULTIPART_FORM_DATA_TYPE);
mp.bodyPart(new FileDataBodyPart("{{baseName}}", {{paramName}}, MediaType.MULTIPART_FORM_DATA_TYPE)); }
} {{/notFile}}{{#isFile}}
{{/isFile}}{{/formParams}} if ({{paramName}} != null) {
if(hasFields) hasFields = true;
mp.field("{{baseName}}", {{paramName}}.getName());
mp.bodyPart(new FileDataBodyPart("{{baseName}}", {{paramName}}, MediaType.MULTIPART_FORM_DATA_TYPE));
}
{{/isFile}}{{/formParams}}
if(hasFields)
postBody = mp; postBody = mp;
} }
else { else {
{{#formParams}}{{#notFile}}if ({{paramName}} != null) {{#formParams}}{{#notFile}}if ({{paramName}} != null)
formParams.put("{{baseName}}", apiClient.parameterToString({{paramName}}));{{/notFile}} formParams.put("{{baseName}}", apiClient.parameterToString({{paramName}}));{{/notFile}}
{{/formParams}} {{/formParams}}
} }
try { try {
String[] authNames = new String[] { {{#authMethods}}"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}} }; String[] authNames = new String[] { {{#authMethods}}"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}} };
String response = apiClient.invokeAPI(path, "{{httpMethod}}", queryParams, postBody, headerParams, formParams, accept, contentType, authNames); String response = apiClient.invokeAPI(path, "{{httpMethod}}", queryParams, postBody, headerParams, formParams, accept, contentType, authNames);
if(response != null){ if(response != null){
return {{#returnType}}({{{returnType}}}) apiClient.deserialize(response, "{{returnContainer}}", {{returnBaseType}}.class){{/returnType}}; return {{#returnType}}({{{returnType}}}) apiClient.deserialize(response, "{{returnContainer}}", {{returnBaseType}}.class){{/returnType}};
} }
else { else {
return {{#returnType}}null{{/returnType}}; return {{#returnType}}null{{/returnType}};
} }
} catch (ApiException ex) { } catch (ApiException ex) {
throw ex; throw ex;
}
}
{{/operation}}
} }
}
{{/operation}}
}
{{/operations}} {{/operations}}

View File

@ -4,44 +4,52 @@ import java.util.Map;
import java.util.List; import java.util.List;
public class ApiException extends Exception { public class ApiException extends Exception {
private int code = 0; private int code = 0;
private String message = null; private String message = null;
private Map<String, List<String>> responseHeaders = null; private Map
private String responseBody = null; <String, List
<String>> responseHeaders = null;
private String responseBody = null;
public ApiException() {} public ApiException() {}
public ApiException(int code, String message) { public ApiException(int code, String message) {
this.code = code; this.code = code;
this.message = message; this.message = message;
} }
public ApiException(int code, String message, Map<String, List<String>> responseHeaders, String responseBody) { public ApiException(int code, String message, Map
this.code = code; <String
this.message = message; , List
this.responseHeaders = responseHeaders; <String>> responseHeaders, String responseBody) {
this.responseBody = responseBody; this.code = code;
} this.message = message;
this.responseHeaders = responseHeaders;
this.responseBody = responseBody;
}
public int getCode() { public int getCode() {
return code; return code;
} }
public String getMessage() { public String getMessage() {
return message; return message;
} }
/** /**
* Get the HTTP response headers. * Get the HTTP response headers.
*/ */
public Map<String, List<String>> getResponseHeaders() { public Map
return responseHeaders; <String
} , List
<String>> getResponseHeaders() {
return responseHeaders;
}
/** /**
* Get the HTTP response body. * Get the HTTP response body.
*/ */
public String getResponseBody() { public String getResponseBody() {
return responseBody; return responseBody;
} }
} }

View File

@ -3,53 +3,55 @@ package {{invokerPackage}}.auth;
import java.util.Map; import java.util.Map;
public class ApiKeyAuth implements Authentication { public class ApiKeyAuth implements Authentication {
private final String location; private final String location;
private final String paramName; private final String paramName;
private String apiKey; private String apiKey;
private String apiKeyPrefix; private String apiKeyPrefix;
public ApiKeyAuth(String location, String paramName) { public ApiKeyAuth(String location, String paramName) {
this.location = location; this.location = location;
this.paramName = paramName; this.paramName = paramName;
} }
public String getLocation() { public String getLocation() {
return location; return location;
} }
public String getParamName() { public String getParamName() {
return paramName; return paramName;
} }
public String getApiKey() { public String getApiKey() {
return apiKey; return apiKey;
} }
public void setApiKey(String apiKey) { public void setApiKey(String apiKey) {
this.apiKey = apiKey; this.apiKey = apiKey;
} }
public String getApiKeyPrefix() { public String getApiKeyPrefix() {
return apiKeyPrefix; return apiKeyPrefix;
} }
public void setApiKeyPrefix(String apiKeyPrefix) { public void setApiKeyPrefix(String apiKeyPrefix) {
this.apiKeyPrefix = apiKeyPrefix; this.apiKeyPrefix = apiKeyPrefix;
} }
@Override @Override
public void applyToParams(Map<String, String> queryParams, Map<String, String> headerParams) { public void applyToParams(Map
String value; <String, String> queryParams, Map
if (apiKeyPrefix != null) { <String, String> headerParams) {
value = apiKeyPrefix + " " + apiKey; String value;
} else { if (apiKeyPrefix != null) {
value = apiKey; value = apiKeyPrefix + " " + apiKey;
} } else {
if (location == "query") { value = apiKey;
queryParams.put(paramName, value); }
} else if (location == "header") { if (location == "query") {
headerParams.put(paramName, value); queryParams.put(paramName, value);
} } else if (location == "header") {
} headerParams.put(paramName, value);
}
}
} }

View File

@ -3,6 +3,8 @@ package {{invokerPackage}}.auth;
import java.util.Map; import java.util.Map;
public interface Authentication { public interface Authentication {
/** Apply authentication settings to header and query params. */ /** Apply authentication settings to header and query params. */
void applyToParams(Map<String, String> queryParams, Map<String, String> headerParams); void applyToParams(Map
<String, String> queryParams, Map
<String, String> headerParams);
} }

View File

@ -6,32 +6,34 @@ import java.io.UnsupportedEncodingException;
import javax.xml.bind.DatatypeConverter; import javax.xml.bind.DatatypeConverter;
public class HttpBasicAuth implements Authentication { public class HttpBasicAuth implements Authentication {
private String username; private String username;
private String password; private String password;
public String getUsername() { public String getUsername() {
return username; return username;
} }
public void setUsername(String username) { public void setUsername(String username) {
this.username = username; this.username = username;
} }
public String getPassword() { public String getPassword() {
return password; return password;
} }
public void setPassword(String password) { public void setPassword(String password) {
this.password = password; this.password = password;
} }
@Override @Override
public void applyToParams(Map<String, String> queryParams, Map<String, String> headerParams) { public void applyToParams(Map
String str = (username == null ? "" : username) + ":" + (password == null ? "" : password); <String, String> queryParams, Map
try { <String, String> headerParams) {
headerParams.put("Authorization", "Basic " + DatatypeConverter.printBase64Binary(str.getBytes("UTF-8"))); String str = (username == null ? "" : username) + ":" + (password == null ? "" : password);
} catch (UnsupportedEncodingException e) { try {
throw new RuntimeException(e); headerParams.put("Authorization", "Basic " + DatatypeConverter.printBase64Binary(str.getBytes("UTF-8")));
} } catch (UnsupportedEncodingException e) {
} throw new RuntimeException(e);
}
}
} }

View File

@ -3,8 +3,10 @@ package {{invokerPackage}}.auth;
import java.util.Map; import java.util.Map;
public class OAuth implements Authentication { public class OAuth implements Authentication {
@Override @Override
public void applyToParams(Map<String, String> queryParams, Map<String, String> headerParams) { public void applyToParams(Map
// TODO: support oauth <String, String> queryParams, Map
} <String, String> headerParams) {
// TODO: support oauth
}
} }

View File

@ -7,45 +7,45 @@ import io.swagger.annotations.*;
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonProperty;
{{#models}} {{#models}}
{{#model}}{{#description}} {{#model}}{{#description}}
/** /**
* {{description}} * {{description}}
**/{{/description}} **/{{/description}}
@ApiModel(description = "{{{description}}}") @ApiModel(description = "{{{description}}}")
public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} { public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {
{{#vars}}{{#isEnum}} {{#vars}}{{#isEnum}}
public enum {{datatypeWithEnum}} { public enum {{datatypeWithEnum}} {
{{#allowableValues}}{{#values}} {{.}}, {{/values}}{{/allowableValues}} {{#allowableValues}}{{#values}} {{.}}, {{/values}}{{/allowableValues}}
}; };
private {{{datatypeWithEnum}}} {{name}} = {{{defaultValue}}};{{/isEnum}}{{^isEnum}} private {{{datatypeWithEnum}}} {{name}} = {{{defaultValue}}};{{/isEnum}}{{^isEnum}}
private {{{datatype}}} {{name}} = {{{defaultValue}}};{{/isEnum}}{{/vars}} private {{{datatype}}} {{name}} = {{{defaultValue}}};{{/isEnum}}{{/vars}}
{{#vars}} {{#vars}}
/**{{#description}} /**{{#description}}
* {{{description}}}{{/description}}{{#minimum}} * {{{description}}}{{/description}}{{#minimum}}
* minimum: {{minimum}}{{/minimum}}{{#maximum}} * minimum: {{minimum}}{{/minimum}}{{#maximum}}
* maximum: {{maximum}}{{/maximum}} * maximum: {{maximum}}{{/maximum}}
**/ **/
@ApiModelProperty({{#required}}required = {{required}}, {{/required}}value = "{{{description}}}") @ApiModelProperty({{#required}}required = {{required}}, {{/required}}value = "{{{description}}}")
@JsonProperty("{{baseName}}") @JsonProperty("{{baseName}}")
public {{{datatypeWithEnum}}} {{getter}}() { public {{{datatypeWithEnum}}} {{getter}}() {
return {{name}}; return {{name}};
} }
public void {{setter}}({{{datatypeWithEnum}}} {{name}}) { public void {{setter}}({{{datatypeWithEnum}}} {{name}}) {
this.{{name}} = {{name}}; this.{{name}} = {{name}};
} }
{{/vars}} {{/vars}}
@Override @Override
public String toString() { public String toString() {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
sb.append("class {{classname}} {\n"); sb.append("class {{classname}} {\n");
{{#parent}}sb.append(" " + super.toString()).append("\n");{{/parent}} {{#parent}}sb.append(" " + super.toString()).append("\n");{{/parent}}
{{#vars}}sb.append(" {{name}}: ").append({{name}}).append("\n"); {{#vars}}sb.append(" {{name}}: ").append({{name}}).append("\n");
{{/vars}}sb.append("}\n"); {{/vars}}sb.append("}\n");
return sb.toString(); return sb.toString();
} }
} }
{{/model}} {{/model}}
{{/models}} {{/models}}

View File

@ -1,167 +1,170 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" <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"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>{{groupId}}</groupId> <groupId>{{groupId}}</groupId>
<artifactId>{{artifactId}}</artifactId> <artifactId>{{artifactId}}</artifactId>
<packaging>jar</packaging> <packaging>jar</packaging>
<name>{{artifactId}}</name> <name>{{artifactId}}</name>
<version>{{artifactVersion}}</version> <version>{{artifactVersion}}</version>
<scm> <scm>
<connection>scm:git:git@github.com:swagger-api/swagger-mustache.git</connection> <connection>scm:git:git@github.com:swagger-api/swagger-mustache.git</connection>
<developerConnection>scm:git:git@github.com:swagger-api/swagger-codegen.git</developerConnection> <developerConnection>scm:git:git@github.com:swagger-api/swagger-codegen.git</developerConnection>
<url>https://github.com/swagger-api/swagger-codegen</url> <url>https://github.com/swagger-api/swagger-codegen</url>
</scm> </scm>
<prerequisites> <prerequisites>
<maven>2.2.0</maven> <maven>2.2.0</maven>
</prerequisites> </prerequisites>
<build> <build>
<plugins> <plugins>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId> <artifactId>maven-surefire-plugin</artifactId>
<version>2.12</version> <version>2.12</version>
<configuration> <configuration>
<systemProperties> <systemProperties>
<property> <property>
<name>loggerPath</name> <name>loggerPath</name>
<value>conf/log4j.properties</value> <value>conf/log4j.properties</value>
</property> </property>
</systemProperties> </systemProperties>
<argLine>-Xms512m -Xmx1500m</argLine> <argLine>-Xms512m -Xmx1500m</argLine>
<parallel>methods</parallel> <parallel>methods</parallel>
<forkMode>pertest</forkMode> <forkMode>pertest</forkMode>
</configuration> </configuration>
</plugin> </plugin>
<plugin> <plugin>
<artifactId>maven-dependency-plugin</artifactId> <artifactId>maven-dependency-plugin</artifactId>
<executions> <executions>
<execution> <execution>
<phase>package</phase> <phase>package</phase>
<goals> <goals>
<goal>copy-dependencies</goal> <goal>copy-dependencies</goal>
</goals> </goals>
<configuration> <configuration>
<outputDirectory>${project.build.directory}/lib</outputDirectory> <outputDirectory>${project.build.directory}/lib</outputDirectory>
</configuration> </configuration>
</execution> </execution>
</executions> </executions>
</plugin> </plugin>
<!-- attach test jar --> <!-- attach test jar -->
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId> <artifactId>maven-jar-plugin</artifactId>
<version>2.2</version> <version>2.2</version>
<executions> <executions>
<execution> <execution>
<goals> <goals>
<goal>jar</goal> <goal>jar</goal>
<goal>test-jar</goal> <goal>test-jar</goal>
</goals> </goals>
</execution> </execution>
</executions> </executions>
<configuration> <configuration>
</configuration> </configuration>
</plugin> </plugin>
<plugin> <plugin>
<groupId>org.codehaus.mojo</groupId> <groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId> <artifactId>build-helper-maven-plugin</artifactId>
<executions> <executions>
<execution> <execution>
<id>add_sources</id> <id>add_sources</id>
<phase>generate-sources</phase> <phase>generate-sources</phase>
<goals> <goals>
<goal>add-source</goal> <goal>add-source</goal>
</goals> </goals>
<configuration> <configuration>
<sources> <sources>
<source>src/main/java</source> <source>
</sources> src/main/java</source>
</configuration> </sources>
</execution> </configuration>
<execution> </execution>
<id>add_test_sources</id> <execution>
<phase>generate-test-sources</phase> <id>add_test_sources</id>
<goals> <phase>generate-test-sources</phase>
<goal>add-test-source</goal> <goals>
</goals> <goal>add-test-source</goal>
<configuration> </goals>
<sources> <configuration>
<source>src/test/java</source> <sources>
</sources> <source>
</configuration> src/test/java</source>
</execution> </sources>
</executions> </configuration>
</plugin> </execution>
<plugin> </executions>
<groupId>org.apache.maven.plugins</groupId> </plugin>
<artifactId>maven-compiler-plugin</artifactId> <plugin>
<version>2.3.2</version> <groupId>org.apache.maven.plugins</groupId>
<configuration> <artifactId>maven-compiler-plugin</artifactId>
<source>1.6</source> <version>2.3.2</version>
<target>1.6</target> <configuration>
</configuration> <source>
</plugin> 1.6</source>
</plugins> <target>1.6</target>
</build> </configuration>
<dependencies> </plugin>
<dependency> </plugins>
<groupId>io.swagger</groupId> </build>
<artifactId>swagger-annotations</artifactId> <dependencies>
<version>${swagger-annotations-version}</version> <dependency>
</dependency> <groupId>io.swagger</groupId>
<dependency> <artifactId>swagger-annotations</artifactId>
<groupId>com.sun.jersey</groupId> <version>${swagger-annotations-version}</version>
<artifactId>jersey-client</artifactId> </dependency>
<version>${jersey-version}</version> <dependency>
</dependency> <groupId>com.sun.jersey</groupId>
<dependency> <artifactId>jersey-client</artifactId>
<groupId>com.sun.jersey.contribs</groupId> <version>${jersey-version}</version>
<artifactId>jersey-multipart</artifactId> </dependency>
<version>${jersey-version}</version> <dependency>
</dependency> <groupId>com.sun.jersey.contribs</groupId>
<dependency> <artifactId>jersey-multipart</artifactId>
<groupId>com.fasterxml.jackson.core</groupId> <version>${jersey-version}</version>
<artifactId>jackson-core</artifactId> </dependency>
<version>${jackson-version}</version> <dependency>
</dependency> <groupId>com.fasterxml.jackson.core</groupId>
<dependency> <artifactId>jackson-core</artifactId>
<groupId>com.fasterxml.jackson.core</groupId> <version>${jackson-version}</version>
<artifactId>jackson-annotations</artifactId> </dependency>
<version>${jackson-version}</version> <dependency>
</dependency> <groupId>com.fasterxml.jackson.core</groupId>
<dependency> <artifactId>jackson-annotations</artifactId>
<groupId>com.fasterxml.jackson.core</groupId> <version>${jackson-version}</version>
<artifactId>jackson-databind</artifactId> </dependency>
<version>${jackson-version}</version> <dependency>
</dependency> <groupId>com.fasterxml.jackson.core</groupId>
<dependency> <artifactId>jackson-databind</artifactId>
<groupId>com.fasterxml.jackson.datatype</groupId> <version>${jackson-version}</version>
<artifactId>jackson-datatype-joda</artifactId> </dependency>
<version>2.1.5</version> <dependency>
</dependency> <groupId>com.fasterxml.jackson.datatype</groupId>
<dependency> <artifactId>jackson-datatype-joda</artifactId>
<groupId>joda-time</groupId> <version>2.1.5</version>
<artifactId>joda-time</artifactId> </dependency>
<version>${jodatime-version}</version> <dependency>
</dependency> <groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>${jodatime-version}</version>
</dependency>
<!-- test dependencies --> <!-- test dependencies -->
<dependency> <dependency>
<groupId>junit</groupId> <groupId>junit</groupId>
<artifactId>junit</artifactId> <artifactId>junit</artifactId>
<version>${junit-version}</version> <version>${junit-version}</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
</dependencies> </dependencies>
<properties> <properties>
<swagger-annotations-version>1.5.0</swagger-annotations-version> <swagger-annotations-version>1.5.0</swagger-annotations-version>
<jersey-version>1.18</jersey-version> <jersey-version>1.18</jersey-version>
<jackson-version>2.4.2</jackson-version> <jackson-version>2.4.2</jackson-version>
<jodatime-version>2.3</jodatime-version> <jodatime-version>2.3</jodatime-version>
<maven-plugin-version>1.0.0</maven-plugin-version> <maven-plugin-version>1.0.0</maven-plugin-version>
<junit-version>4.8.1</junit-version> <junit-version>4.8.1</junit-version>
</properties> </properties>
</project> </project>

View File

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

View File

@ -6,21 +6,21 @@ import javax.servlet.*;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
public class ApiOriginFilter implements javax.servlet.Filter { public class ApiOriginFilter implements javax.servlet.Filter {
@Override @Override
public void doFilter(ServletRequest request, ServletResponse response, public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException { FilterChain chain) throws IOException, ServletException {
HttpServletResponse res = (HttpServletResponse) response; HttpServletResponse res = (HttpServletResponse) response;
res.addHeader("Access-Control-Allow-Origin", "*"); res.addHeader("Access-Control-Allow-Origin", "*");
res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT"); res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
res.addHeader("Access-Control-Allow-Headers", "Content-Type"); res.addHeader("Access-Control-Allow-Headers", "Content-Type");
chain.doFilter(request, response); chain.doFilter(request, response);
} }
@Override @Override
public void destroy() { public void destroy() {
} }
@Override @Override
public void init(FilterConfig filterConfig) throws ServletException { public void init(FilterConfig filterConfig) throws ServletException {
} }
} }

View File

@ -4,65 +4,65 @@ import javax.xml.bind.annotation.XmlTransient;
@javax.xml.bind.annotation.XmlRootElement @javax.xml.bind.annotation.XmlRootElement
public class ApiResponseMessage { public class ApiResponseMessage {
public static final int ERROR = 1; public static final int ERROR = 1;
public static final int WARNING = 2; public static final int WARNING = 2;
public static final int INFO = 3; public static final int INFO = 3;
public static final int OK = 4; public static final int OK = 4;
public static final int TOO_BUSY = 5; public static final int TOO_BUSY = 5;
int code; int code;
String type; String type;
String message; 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 ApiResponseMessage(){}
public int getCode() {
return code;
}
public void setCode(int code) { public ApiResponseMessage(int code, String message){
this.code = code; this.code = code;
} switch(code){
case ERROR:
public String getType() { setType("error");
return type; break;
} case WARNING:
setType("warning");
public void setType(String type) { break;
this.type = type; case INFO:
} setType("info");
break;
public String getMessage() { case OK:
return message; setType("ok");
} break;
case TOO_BUSY:
public void setMessage(String message) { setType("too busy");
this.message = message; 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

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

View File

@ -1,7 +1,7 @@
# Swagger generated server # Swagger generated server
## Overview ## Overview
This server was generated by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. By using the This server was generated by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. By using the
[swagger-spec](https://github.com/swagger-api/swagger-core/wiki) from a remote server, you can easily generate a server stub. This [swagger-spec](https://github.com/swagger-api/swagger-core/wiki) from a remote server, you can easily generate a server stub. This
is an example of building a swagger-enabled scalatra server. is an example of building a swagger-enabled scalatra server.

View File

@ -27,26 +27,26 @@ import javax.ws.rs.*;
{{#hasProduces}}@Produces({ {{#produces}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }){{/hasProduces}} {{#hasProduces}}@Produces({ {{#produces}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }){{/hasProduces}}
@io.swagger.annotations.Api(value = "/{{baseName}}", description = "the {{baseName}} API") @io.swagger.annotations.Api(value = "/{{baseName}}", description = "the {{baseName}} API")
{{#operations}} {{#operations}}
public class {{classname}} { public class {{classname}} {
private final {{classname}}Service delegate = {{classname}}ServiceFactory.get{{classname}}(); private final {{classname}}Service delegate = {{classname}}ServiceFactory.get{{classname}}();
{{#operation}} {{#operation}}
@{{httpMethod}} @{{httpMethod}}
{{#subresourceOperation}}@Path("{{path}}"){{/subresourceOperation}} {{#subresourceOperation}}@Path("{{path}}"){{/subresourceOperation}}
{{#hasConsumes}}@Consumes({ {{#consumes}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} }){{/hasConsumes}} {{#hasConsumes}}@Consumes({ {{#consumes}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} }){{/hasConsumes}}
{{#hasProduces}}@Produces({ {{#produces}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }){{/hasProduces}} {{#hasProduces}}@Produces({ {{#produces}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }){{/hasProduces}}
@io.swagger.annotations.ApiOperation(value = "{{{summary}}}", notes = "{{{notes}}}", response = {{{returnType}}}.class{{#returnContainer}}, responseContainer = "{{{returnContainer}}}"{{/returnContainer}}) @io.swagger.annotations.ApiOperation(value = "{{{summary}}}", notes = "{{{notes}}}", response = {{{returnType}}}.class{{#returnContainer}}, responseContainer = "{{{returnContainer}}}"{{/returnContainer}})
@io.swagger.annotations.ApiResponses(value = { {{#responses}} @io.swagger.annotations.ApiResponses(value = { {{#responses}}
@io.swagger.annotations.ApiResponse(code = {{{code}}}, message = "{{{message}}}"){{#hasMore}}, @io.swagger.annotations.ApiResponse(code = {{{code}}}, message = "{{{message}}}"){{#hasMore}},
{{/hasMore}}{{/responses}} }) {{/hasMore}}{{/responses}} })
public Response {{nickname}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}}, public Response {{nickname}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}},
{{/hasMore}}{{/allParams}}) {{/hasMore}}{{/allParams}})
throws NotFoundException { throws NotFoundException {
return delegate.{{nickname}}({{#allParams}}{{#isFile}}fileDetail{{/isFile}}{{^isFile}}{{paramName}}{{/isFile}}{{#hasMore}},{{/hasMore}}{{/allParams}}); return delegate.{{nickname}}({{#allParams}}{{#isFile}}fileDetail{{/isFile}}{{^isFile}}{{paramName}}{{/isFile}}{{#hasMore}},{{/hasMore}}{{/allParams}});
}
{{/operation}}
} }
{{/operation}}
}
{{/operations}} {{/operations}}

View File

@ -19,10 +19,10 @@ import com.sun.jersey.multipart.FormDataParam;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
{{#operations}} {{#operations}}
public abstract class {{classname}}Service { public abstract class {{classname}}Service {
{{#operation}} {{#operation}}
public abstract Response {{nickname}}({{#allParams}}{{>serviceQueryParams}}{{>servicePathParams}}{{>serviceHeaderParams}}{{>serviceBodyParams}}{{>serviceFormParams}}{{#hasMore}},{{/hasMore}}{{/allParams}}) public abstract Response {{nickname}}({{#allParams}}{{>serviceQueryParams}}{{>servicePathParams}}{{>serviceHeaderParams}}{{>serviceBodyParams}}{{>serviceFormParams}}{{#hasMore}},{{/hasMore}}{{/allParams}})
throws NotFoundException; throws NotFoundException;
{{/operation}} {{/operation}}
} }
{{/operations}} {{/operations}}

View File

@ -5,10 +5,10 @@ import {{package}}.impl.{{classname}}ServiceImpl;
public class {{classname}}ServiceFactory { public class {{classname}}ServiceFactory {
private final static {{classname}}Service service = new {{classname}}ServiceImpl(); private final static {{classname}}Service service = new {{classname}}ServiceImpl();
public static {{classname}}Service get{{classname}}() public static {{classname}}Service get{{classname}}()
{ {
return service; return service;
} }
} }

View File

@ -19,14 +19,14 @@ import com.sun.jersey.multipart.FormDataParam;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
{{#operations}} {{#operations}}
public class {{classname}}ServiceImpl extends {{classname}}Service { public class {{classname}}ServiceImpl extends {{classname}}Service {
{{#operation}} {{#operation}}
@Override @Override
public Response {{nickname}}({{#allParams}}{{>serviceQueryParams}}{{>servicePathParams}}{{>serviceHeaderParams}}{{>serviceBodyParams}}{{>serviceFormParams}}{{#hasMore}},{{/hasMore}}{{/allParams}}) public Response {{nickname}}({{#allParams}}{{>serviceQueryParams}}{{>servicePathParams}}{{>serviceHeaderParams}}{{>serviceBodyParams}}{{>serviceFormParams}}{{#hasMore}},{{/hasMore}}{{/allParams}})
throws NotFoundException { throws NotFoundException {
// do some magic! // do some magic!
return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build();
} }
{{/operation}} {{/operation}}
} }
{{/operations}} {{/operations}}

View File

@ -1,2 +1,2 @@
{{#isFormParam}}{{#notFile}}@ApiParam(value = "{{{description}}}"{{#required}}, required=true{{/required}} {{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}})@FormParam("{{paramName}}") {{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}}@ApiParam(value = "{{{description}}}") @FormDataParam("file") InputStream inputStream, {{#isFormParam}}{{#notFile}}@ApiParam(value = "{{{description}}}"{{#required}}, required=true{{/required}} {{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}})@FormParam("{{paramName}}") {{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}}@ApiParam(value = "{{{description}}}") @FormDataParam("file") InputStream inputStream,
@ApiParam(value = "file detail") @FormDataParam("file") FormDataContentDisposition fileDetail{{/isFile}}{{/isFormParam}} @ApiParam(value = "file detail") @FormDataParam("file") FormDataContentDisposition fileDetail{{/isFile}}{{/isFormParam}}

View File

@ -7,45 +7,45 @@ import io.swagger.annotations.*;
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonProperty;
{{#models}} {{#models}}
{{#model}}{{#description}} {{#model}}{{#description}}
/** /**
* {{description}} * {{description}}
**/{{/description}} **/{{/description}}
@ApiModel(description = "{{{description}}}") @ApiModel(description = "{{{description}}}")
public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} { public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {
{{#vars}}{{#isEnum}} {{#vars}}{{#isEnum}}
public enum {{datatypeWithEnum}} { public enum {{datatypeWithEnum}} {
{{#allowableValues}}{{#values}} {{.}}, {{/values}}{{/allowableValues}} {{#allowableValues}}{{#values}} {{.}}, {{/values}}{{/allowableValues}}
}; };
private {{{datatypeWithEnum}}} {{name}} = {{{defaultValue}}};{{/isEnum}}{{^isEnum}} private {{{datatypeWithEnum}}} {{name}} = {{{defaultValue}}};{{/isEnum}}{{^isEnum}}
private {{{datatype}}} {{name}} = {{{defaultValue}}};{{/isEnum}}{{/vars}} private {{{datatype}}} {{name}} = {{{defaultValue}}};{{/isEnum}}{{/vars}}
{{#vars}} {{#vars}}
/**{{#description}} /**{{#description}}
* {{{description}}}{{/description}}{{#minimum}} * {{{description}}}{{/description}}{{#minimum}}
* minimum: {{minimum}}{{/minimum}}{{#maximum}} * minimum: {{minimum}}{{/minimum}}{{#maximum}}
* maximum: {{maximum}}{{/maximum}} * maximum: {{maximum}}{{/maximum}}
**/ **/
@ApiModelProperty({{#required}}required = {{required}}, {{/required}}value = "{{{description}}}") @ApiModelProperty({{#required}}required = {{required}}, {{/required}}value = "{{{description}}}")
@JsonProperty("{{name}}") @JsonProperty("{{name}}")
public {{{datatypeWithEnum}}} {{getter}}() { public {{{datatypeWithEnum}}} {{getter}}() {
return {{name}}; return {{name}};
} }
public void {{setter}}({{{datatypeWithEnum}}} {{name}}) { public void {{setter}}({{{datatypeWithEnum}}} {{name}}) {
this.{{name}} = {{name}}; this.{{name}} = {{name}};
} }
{{/vars}} {{/vars}}
@Override @Override
public String toString() { public String toString() {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
sb.append("class {{classname}} {\n"); sb.append("class {{classname}} {\n");
{{#parent}}sb.append(" " + super.toString()).append("\n");{{/parent}} {{#parent}}sb.append(" " + super.toString()).append("\n");{{/parent}}
{{#vars}}sb.append(" {{name}}: ").append({{name}}).append("\n"); {{#vars}}sb.append(" {{name}}: ").append({{name}}).append("\n");
{{/vars}}sb.append("}\n"); {{/vars}}sb.append("}\n");
return sb.toString(); return sb.toString();
} }
} }
{{/model}} {{/model}}
{{/models}} {{/models}}

View File

@ -1,159 +1,161 @@
<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"> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
<modelVersion>4.0.0</modelVersion> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<groupId>{{groupId}}</groupId> <modelVersion>4.0.0</modelVersion>
<artifactId>{{artifactId}}</artifactId> <groupId>{{groupId}}</groupId>
<packaging>jar</packaging> <artifactId>{{artifactId}}</artifactId>
<name>{{artifactId}}</name> <packaging>jar</packaging>
<version>{{artifactVersion}}</version> <name>{{artifactId}}</name>
<build> <version>{{artifactVersion}}</version>
<sourceDirectory>src/main/java</sourceDirectory> <build>
<plugins> <sourceDirectory>src/main/java</sourceDirectory>
<plugin> <plugins>
<groupId>org.apache.maven.plugins</groupId> <plugin>
<artifactId>maven-war-plugin</artifactId> <groupId>org.apache.maven.plugins</groupId>
<version>2.1.1</version> <artifactId>maven-war-plugin</artifactId>
</plugin> <version>2.1.1</version>
<plugin> </plugin>
<artifactId>maven-failsafe-plugin</artifactId> <plugin>
<version>2.6</version> <artifactId>maven-failsafe-plugin</artifactId>
<executions> <version>2.6</version>
<execution> <executions>
<goals> <execution>
<goal>integration-test</goal> <goals>
<goal>verify</goal> <goal>integration-test</goal>
</goals> <goal>verify</goal>
</execution> </goals>
</executions> </execution>
</plugin> </executions>
<plugin> </plugin>
<groupId>org.eclipse.jetty</groupId> <plugin>
<artifactId>jetty-maven-plugin</artifactId> <groupId>org.eclipse.jetty</groupId>
<version>${jetty-version}</version> <artifactId>jetty-maven-plugin</artifactId>
<configuration> <version>${jetty-version}</version>
<webApp> <configuration>
<contextPath>/</contextPath> <webApp>
</webApp> <contextPath>/</contextPath>
<webAppSourceDirectory>target/${project.artifactId}-${project.version}</webAppSourceDirectory> </webApp>
<stopPort>8079</stopPort> <webAppSourceDirectory>target/${project.artifactId}-${project.version}</webAppSourceDirectory>
<stopKey>stopit</stopKey> <stopPort>8079</stopPort>
<httpConnector> <stopKey>stopit</stopKey>
<port>8080</port> <httpConnector>
<idleTimeout>60000</idleTimeout> <port>8080</port>
</httpConnector> <idleTimeout>60000</idleTimeout>
</configuration> </httpConnector>
<executions> </configuration>
<execution> <executions>
<id>start-jetty</id> <execution>
<phase>pre-integration-test</phase> <id>start-jetty</id>
<goals> <phase>pre-integration-test</phase>
<goal>start</goal> <goals>
</goals> <goal>start</goal>
<configuration> </goals>
<scanIntervalSeconds>0</scanIntervalSeconds> <configuration>
<daemon>true</daemon> <scanIntervalSeconds>0</scanIntervalSeconds>
</configuration> <daemon>true</daemon>
</execution> </configuration>
<execution> </execution>
<id>stop-jetty</id> <execution>
<phase>post-integration-test</phase> <id>stop-jetty</id>
<goals> <phase>post-integration-test</phase>
<goal>stop</goal> <goals>
</goals> <goal>stop</goal>
</execution> </goals>
</executions> </execution>
</plugin> </executions>
<plugin> </plugin>
<groupId>org.codehaus.mojo</groupId> <plugin>
<artifactId>build-helper-maven-plugin</artifactId> <groupId>org.codehaus.mojo</groupId>
<version>1.9.1</version> <artifactId>build-helper-maven-plugin</artifactId>
<executions> <version>1.9.1</version>
<execution> <executions>
<id>add-source</id> <execution>
<phase>generate-sources</phase> <id>add-source</id>
<goals> <phase>generate-sources</phase>
<goal>add-source</goal> <goals>
</goals> <goal>add-source</goal>
<configuration> </goals>
<sources> <configuration>
<source>src/gen/java</source> <sources>
</sources> <source>
</configuration> src/gen/java</source>
</execution> </sources>
</executions> </configuration>
</plugin> </execution>
</plugins> </executions>
</build> </plugin>
<dependencies> </plugins>
<dependency> </build>
<groupId>io.swagger</groupId> <dependencies>
<artifactId>swagger-jersey-jaxrs</artifactId> <dependency>
<version>${swagger-core-version}</version> <groupId>io.swagger</groupId>
</dependency> <artifactId>swagger-jersey-jaxrs</artifactId>
<dependency> <version>${swagger-core-version}</version>
<groupId>org.slf4j</groupId> </dependency>
<artifactId>slf4j-log4j12</artifactId> <dependency>
<version>${slf4j-version}</version> <groupId>org.slf4j</groupId>
</dependency> <artifactId>slf4j-log4j12</artifactId>
<dependency> <version>${slf4j-version}</version>
<groupId>com.sun.jersey</groupId> </dependency>
<artifactId>jersey-core</artifactId> <dependency>
<version>${jersey-version}</version> <groupId>com.sun.jersey</groupId>
</dependency> <artifactId>jersey-core</artifactId>
<dependency> <version>${jersey-version}</version>
<groupId>com.sun.jersey</groupId> </dependency>
<artifactId>jersey-json</artifactId> <dependency>
<version>${jersey-version}</version> <groupId>com.sun.jersey</groupId>
</dependency> <artifactId>jersey-json</artifactId>
<dependency> <version>${jersey-version}</version>
<groupId>com.sun.jersey</groupId> </dependency>
<artifactId>jersey-servlet</artifactId> <dependency>
<version>${jersey-version}</version> <groupId>com.sun.jersey</groupId>
</dependency> <artifactId>jersey-servlet</artifactId>
<dependency> <version>${jersey-version}</version>
<groupId>com.sun.jersey.contribs</groupId> </dependency>
<artifactId>jersey-multipart</artifactId> <dependency>
<version>${jersey-version}</version> <groupId>com.sun.jersey.contribs</groupId>
</dependency> <artifactId>jersey-multipart</artifactId>
<dependency> <version>${jersey-version}</version>
<groupId>com.sun.jersey</groupId> </dependency>
<artifactId>jersey-server</artifactId> <dependency>
<version>${jersey-version}</version> <groupId>com.sun.jersey</groupId>
</dependency> <artifactId>jersey-server</artifactId>
<version>${jersey-version}</version>
</dependency>
<dependency> <dependency>
<groupId>org.scalatest</groupId> <groupId>org.scalatest</groupId>
<artifactId>scalatest_2.9.1</artifactId> <artifactId>scalatest_2.9.1</artifactId>
<version>${scala-test-version}</version> <version>${scala-test-version}</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>junit</groupId> <groupId>junit</groupId>
<artifactId>junit</artifactId> <artifactId>junit</artifactId>
<version>${junit-version}</version> <version>${junit-version}</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>javax.servlet</groupId> <groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId> <artifactId>servlet-api</artifactId>
<version>${servlet-api-version}</version> <version>${servlet-api-version}</version>
</dependency> </dependency>
</dependencies> </dependencies>
<repositories> <repositories>
<repository> <repository>
<id>sonatype-snapshots</id> <id>sonatype-snapshots</id>
<url>https://oss.sonatype.org/content/repositories/snapshots</url> <url>https://oss.sonatype.org/content/repositories/snapshots</url>
<snapshots> <snapshots>
<enabled>true</enabled> <enabled>true</enabled>
</snapshots> </snapshots>
</repository> </repository>
</repositories> </repositories>
<properties> <properties>
<swagger-core-version>1.5.0</swagger-core-version> <swagger-core-version>1.5.0</swagger-core-version>
<jetty-version>9.2.9.v20150224</jetty-version> <jetty-version>9.2.9.v20150224</jetty-version>
<jersey-version>1.13</jersey-version> <jersey-version>1.13</jersey-version>
<slf4j-version>1.6.3</slf4j-version> <slf4j-version>1.6.3</slf4j-version>
<scala-test-version>1.6.1</scala-test-version> <scala-test-version>1.6.1</scala-test-version>
<junit-version>4.8.1</junit-version> <junit-version>4.8.1</junit-version>
<servlet-api-version>2.5</servlet-api-version> <servlet-api-version>2.5</servlet-api-version>
</properties> </properties>
</project> </project>

View File

@ -1,54 +1,54 @@
<?xml version="1.0" encoding="ISO-8859-1"?> <?xml version="1.0" encoding="ISO-8859-1"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" <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" 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>
<servlet-name>jersey</servlet-name> <servlet-name>jersey</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class> <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param> <init-param>
<param-name>com.sun.jersey.config.property.packages</param-name> <param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>io.swagger.jaxrs.json;io.swagger.jaxrs.listing;{{apiPackage}}</param-value> <param-value>io.swagger.jaxrs.json;io.swagger.jaxrs.listing;{{apiPackage}}</param-value>
</init-param> </init-param>
<init-param> <init-param>
<param-name>com.sun.jersey.spi.container.ContainerRequestFilters</param-name> <param-name>com.sun.jersey.spi.container.ContainerRequestFilters</param-name>
<param-value>com.sun.jersey.api.container.filter.PostReplaceFilter</param-value> <param-value>com.sun.jersey.api.container.filter.PostReplaceFilter</param-value>
</init-param> </init-param>
<init-param> <init-param>
<param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name> <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
<param-value>true</param-value> <param-value>true</param-value>
</init-param> </init-param>
<load-on-startup>1</load-on-startup> <load-on-startup>1</load-on-startup>
</servlet> </servlet>
<servlet> <servlet>
<servlet-name>DefaultJaxrsConfig</servlet-name> <servlet-name>DefaultJaxrsConfig</servlet-name>
<servlet-class>io.swagger.jaxrs.config.DefaultJaxrsConfig</servlet-class> <servlet-class>io.swagger.jaxrs.config.DefaultJaxrsConfig</servlet-class>
<init-param> <init-param>
<param-name>api.version</param-name> <param-name>api.version</param-name>
<param-value>1.0.0</param-value> <param-value>1.0.0</param-value>
</init-param> </init-param>
<init-param> <init-param>
<param-name>swagger.api.title</param-name> <param-name>swagger.api.title</param-name>
<param-value>{{{title}}}</param-value> <param-value>{{{title}}}</param-value>
</init-param> </init-param>
<init-param> <init-param>
<param-name>swagger.api.basepath</param-name> <param-name>swagger.api.basepath</param-name>
<param-value>http://localhost:8080</param-value> <param-value>http://localhost:8080</param-value>
</init-param> </init-param>
<load-on-startup>2</load-on-startup> <load-on-startup>2</load-on-startup>
</servlet> </servlet>
<servlet-mapping> <servlet-mapping>
<servlet-name>jersey</servlet-name> <servlet-name>jersey</servlet-name>
<url-pattern>/*</url-pattern> <url-pattern>/*</url-pattern>
</servlet-mapping> </servlet-mapping>
<filter> <filter>
<filter-name>ApiOriginFilter</filter-name> <filter-name>ApiOriginFilter</filter-name>
<filter-class>{{apiPackage}}.ApiOriginFilter</filter-class> <filter-class>{{apiPackage}}.ApiOriginFilter</filter-class>
</filter> </filter>
<filter-mapping> <filter-mapping>
<filter-name>ApiOriginFilter</filter-name> <filter-name>ApiOriginFilter</filter-name>
<url-pattern>/*</url-pattern> <url-pattern>/*</url-pattern>
</filter-mapping> </filter-mapping>
</web-app> </web-app>

View File

@ -31,23 +31,23 @@ import static org.springframework.http.MediaType.*;
@RequestMapping(value = "/{{baseName}}", produces = {APPLICATION_JSON_VALUE}) @RequestMapping(value = "/{{baseName}}", produces = {APPLICATION_JSON_VALUE})
@Api(value = "/{{baseName}}", description = "the {{baseName}} API") @Api(value = "/{{baseName}}", description = "the {{baseName}} API")
{{#operations}} {{#operations}}
public class {{classname}} { public class {{classname}} {
{{#operation}} {{#operation}}
@ApiOperation(value = "{{{summary}}}", notes = "{{{notes}}}", response = {{{returnType}}}.class{{#returnContainer}}, responseContainer = "{{{returnContainer}}}"{{/returnContainer}}) @ApiOperation(value = "{{{summary}}}", notes = "{{{notes}}}", response = {{{returnType}}}.class{{#returnContainer}}, responseContainer = "{{{returnContainer}}}"{{/returnContainer}})
@ApiResponses(value = { {{#responses}} @ApiResponses(value = { {{#responses}}
@ApiResponse(code = {{{code}}}, message = "{{{message}}}"){{#hasMore}},{{/hasMore}}{{/responses}} }) @ApiResponse(code = {{{code}}}, message = "{{{message}}}"){{#hasMore}},{{/hasMore}}{{/responses}} })
@RequestMapping(value = "{{path}}", @RequestMapping(value = "{{path}}",
{{#hasProduces}}produces = { {{#produces}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }, {{/hasProduces}} {{#hasProduces}}produces = { {{#produces}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }, {{/hasProduces}}
{{#hasConsumes}}consumes = { {{#consumes}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} },{{/hasConsumes}} {{#hasConsumes}}consumes = { {{#consumes}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} },{{/hasConsumes}}
method = RequestMethod.{{httpMethod}}) method = RequestMethod.{{httpMethod}})
public ResponseEntity<{{returnType}}> {{nickname}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}}, public ResponseEntity<{{returnType}}> {{nickname}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}},
{{/hasMore}}{{/allParams}}) {{/hasMore}}{{/allParams}})
throws NotFoundException { throws NotFoundException {
// do some magic! // do some magic!
return new ResponseEntity<{{returnType}}>(HttpStatus.OK); return new ResponseEntity<{{returnType}}>(HttpStatus.OK);
} }
{{/operation}} {{/operation}}
} }
{{/operations}} {{/operations}}

View File

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

View File

@ -6,21 +6,21 @@ import javax.servlet.*;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
public class ApiOriginFilter implements javax.servlet.Filter { public class ApiOriginFilter implements javax.servlet.Filter {
@Override @Override
public void doFilter(ServletRequest request, ServletResponse response, public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException { FilterChain chain) throws IOException, ServletException {
HttpServletResponse res = (HttpServletResponse) response; HttpServletResponse res = (HttpServletResponse) response;
res.addHeader("Access-Control-Allow-Origin", "*"); res.addHeader("Access-Control-Allow-Origin", "*");
res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT"); res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
res.addHeader("Access-Control-Allow-Headers", "Content-Type"); res.addHeader("Access-Control-Allow-Headers", "Content-Type");
chain.doFilter(request, response); chain.doFilter(request, response);
} }
@Override @Override
public void destroy() { public void destroy() {
} }
@Override @Override
public void init(FilterConfig filterConfig) throws ServletException { public void init(FilterConfig filterConfig) throws ServletException {
} }
} }

View File

@ -4,65 +4,65 @@ import javax.xml.bind.annotation.XmlTransient;
@javax.xml.bind.annotation.XmlRootElement @javax.xml.bind.annotation.XmlRootElement
public class ApiResponseMessage { public class ApiResponseMessage {
public static final int ERROR = 1; public static final int ERROR = 1;
public static final int WARNING = 2; public static final int WARNING = 2;
public static final int INFO = 3; public static final int INFO = 3;
public static final int OK = 4; public static final int OK = 4;
public static final int TOO_BUSY = 5; public static final int TOO_BUSY = 5;
int code; int code;
String type; String type;
String message; 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 ApiResponseMessage(){}
public int getCode() {
return code;
}
public void setCode(int code) { public ApiResponseMessage(int code, String message){
this.code = code; this.code = code;
} switch(code){
case ERROR:
public String getType() { setType("error");
return type; break;
} case WARNING:
setType("warning");
public void setType(String type) { break;
this.type = type; case INFO:
} setType("info");
break;
public String getMessage() { case OK:
return message; setType("ok");
} break;
case TOO_BUSY:
public void setMessage(String message) { setType("too busy");
this.message = message; 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

@ -1,2 +1,2 @@
{{#isFormParam}}{{#notFile}} {{#isFormParam}}{{#notFile}}
@ApiParam(value = "{{{description}}}"{{#required}}, required=true{{/required}} {{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) @RequestPart(value="{{paramName}}"{{#required}}, required=true{{/required}}{{^required}}, required=false{{/required}}) {{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}}@ApiParam(value = "file detail") @RequestPart("file") MultipartFile fileDetail{{/isFile}}{{/isFormParam}} @ApiParam(value = "{{{description}}}"{{#required}}, required=true{{/required}} {{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) @RequestPart(value="{{paramName}}"{{#required}}, required=true{{/required}}{{^required}}, required=false{{/required}}) {{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}}@ApiParam(value = "file detail") @RequestPart("file") MultipartFile fileDetail{{/isFile}}{{/isFormParam}}

View File

@ -7,45 +7,45 @@ import io.swagger.annotations.*;
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonProperty;
{{#models}} {{#models}}
{{#model}}{{#description}} {{#model}}{{#description}}
/** /**
* {{description}} * {{description}}
**/{{/description}} **/{{/description}}
@ApiModel(description = "{{{description}}}") @ApiModel(description = "{{{description}}}")
public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} { public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {
{{#vars}}{{#isEnum}} {{#vars}}{{#isEnum}}
public enum {{datatypeWithEnum}} { public enum {{datatypeWithEnum}} {
{{#allowableValues}}{{#values}} {{.}}, {{/values}}{{/allowableValues}} {{#allowableValues}}{{#values}} {{.}}, {{/values}}{{/allowableValues}}
}; };
private {{{datatypeWithEnum}}} {{name}} = {{{defaultValue}}};{{/isEnum}}{{^isEnum}} private {{{datatypeWithEnum}}} {{name}} = {{{defaultValue}}};{{/isEnum}}{{^isEnum}}
private {{{datatype}}} {{name}} = {{{defaultValue}}};{{/isEnum}}{{/vars}} private {{{datatype}}} {{name}} = {{{defaultValue}}};{{/isEnum}}{{/vars}}
{{#vars}} {{#vars}}
/**{{#description}} /**{{#description}}
* {{{description}}}{{/description}}{{#minimum}} * {{{description}}}{{/description}}{{#minimum}}
* minimum: {{minimum}}{{/minimum}}{{#maximum}} * minimum: {{minimum}}{{/minimum}}{{#maximum}}
* maximum: {{maximum}}{{/maximum}} * maximum: {{maximum}}{{/maximum}}
**/ **/
@ApiModelProperty({{#required}}required = {{required}}, {{/required}}value = "{{{description}}}") @ApiModelProperty({{#required}}required = {{required}}, {{/required}}value = "{{{description}}}")
@JsonProperty("{{name}}") @JsonProperty("{{name}}")
public {{{datatypeWithEnum}}} {{getter}}() { public {{{datatypeWithEnum}}} {{getter}}() {
return {{name}}; return {{name}};
} }
public void {{setter}}({{{datatypeWithEnum}}} {{name}}) { public void {{setter}}({{{datatypeWithEnum}}} {{name}}) {
this.{{name}} = {{name}}; this.{{name}} = {{name}};
} }
{{/vars}} {{/vars}}
@Override @Override
public String toString() { public String toString() {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
sb.append("class {{classname}} {\n"); sb.append("class {{classname}} {\n");
{{#parent}}sb.append(" " + super.toString()).append("\n");{{/parent}} {{#parent}}sb.append(" " + super.toString()).append("\n");{{/parent}}
{{#vars}}sb.append(" {{name}}: ").append({{name}}).append("\n"); {{#vars}}sb.append(" {{name}}: ").append({{name}}).append("\n");
{{/vars}}sb.append("}\n"); {{/vars}}sb.append("}\n");
return sb.toString(); return sb.toString();
} }
} }
{{/model}} {{/model}}
{{/models}} {{/models}}

View File

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

View File

@ -1,229 +1,232 @@
<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"> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
<modelVersion>4.0.0</modelVersion> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<groupId>{{groupId}}</groupId> <modelVersion>4.0.0</modelVersion>
<artifactId>{{artifactId}}</artifactId> <groupId>{{groupId}}</groupId>
<packaging>jar</packaging> <artifactId>{{artifactId}}</artifactId>
<name>{{artifactId}}</name> <packaging>jar</packaging>
<version>{{artifactVersion}}</version> <name>{{artifactId}}</name>
<build> <version>{{artifactVersion}}</version>
<sourceDirectory>src/main/java</sourceDirectory> <build>
<plugins> <sourceDirectory>src/main/java</sourceDirectory>
<plugin> <plugins>
<groupId>org.apache.maven.plugins</groupId> <plugin>
<artifactId>maven-war-plugin</artifactId> <groupId>org.apache.maven.plugins</groupId>
<version>2.1.1</version> <artifactId>maven-war-plugin</artifactId>
</plugin> <version>2.1.1</version>
<plugin> </plugin>
<artifactId>maven-failsafe-plugin</artifactId> <plugin>
<version>2.6</version> <artifactId>maven-failsafe-plugin</artifactId>
<executions> <version>2.6</version>
<execution> <executions>
<goals> <execution>
<goal>integration-test</goal> <goals>
<goal>verify</goal> <goal>integration-test</goal>
</goals> <goal>verify</goal>
</execution> </goals>
</executions> </execution>
</plugin> </executions>
<plugin> </plugin>
<groupId>org.eclipse.jetty</groupId> <plugin>
<artifactId>jetty-maven-plugin</artifactId> <groupId>org.eclipse.jetty</groupId>
<version>${jetty-version}</version> <artifactId>jetty-maven-plugin</artifactId>
<configuration> <version>${jetty-version}</version>
<webAppConfig> <configuration>
<contextPath>{{^contextPath}}/{{/contextPath}}{{#contextPath}}{{contextPath}}{{/contextPath}}</contextPath> <webAppConfig>
</webAppConfig> <contextPath>{{^contextPath}}
<webAppSourceDirectory>target/${project.artifactId}-${project-version}</webAppSourceDirectory> /{{/contextPath}}{{#contextPath}}{{contextPath}}{{/contextPath}}</contextPath>
<webDefaultXml>${project.basedir}/conf/jetty/webdefault.xml</webDefaultXml> </webAppConfig>
<stopPort>8079</stopPort> <webAppSourceDirectory>target/${project.artifactId}-${project-version}</webAppSourceDirectory>
<stopKey>stopit</stopKey> <webDefaultXml>${project.basedir}/conf/jetty/webdefault.xml</webDefaultXml>
<httpConnector> <stopPort>8079</stopPort>
<port>8002</port> <stopKey>stopit</stopKey>
<idleTimeout>60000</idleTimeout> <httpConnector>
</httpConnector> <port>8002</port>
</configuration> <idleTimeout>60000</idleTimeout>
<executions> </httpConnector>
<execution> </configuration>
<id>start-jetty</id> <executions>
<phase>pre-integration-test</phase> <execution>
<goals> <id>start-jetty</id>
<goal>start</goal> <phase>pre-integration-test</phase>
</goals> <goals>
<configuration> <goal>start</goal>
<scanIntervalSeconds>0</scanIntervalSeconds> </goals>
<daemon>true</daemon> <configuration>
</configuration> <scanIntervalSeconds>0</scanIntervalSeconds>
</execution> <daemon>true</daemon>
<execution> </configuration>
<id>stop-jetty</id> </execution>
<phase>post-integration-test</phase> <execution>
<goals> <id>stop-jetty</id>
<goal>stop</goal> <phase>post-integration-test</phase>
</goals> <goals>
</execution> <goal>stop</goal>
</executions> </goals>
</plugin> </execution>
<plugin> </executions>
<groupId>com.googlecode.maven-download-plugin</groupId> </plugin>
<artifactId>download-maven-plugin</artifactId> <plugin>
<version>1.2.1</version> <groupId>com.googlecode.maven-download-plugin</groupId>
<executions> <artifactId>download-maven-plugin</artifactId>
<execution> <version>1.2.1</version>
<id>swagger-ui</id> <executions>
<goals> <execution>
<goal>wget</goal> <id>swagger-ui</id>
</goals> <goals>
<configuration> <goal>wget</goal>
<url>https://github.com/swagger-api/swagger-ui/archive/v${swagger-ui-version}.tar.gz</url> </goals>
<unpack>true</unpack> <configuration>
<outputDirectory>${project.build.directory}</outputDirectory> <url>https://github.com/swagger-api/swagger-ui/archive/v${swagger-ui-version}.tar.gz</url>
</configuration> <unpack>true</unpack>
</execution> <outputDirectory>${project.build.directory}</outputDirectory>
</executions> </configuration>
</plugin> </execution>
<plugin> </executions>
<artifactId>maven-resources-plugin</artifactId> </plugin>
<version>2.6</version> <plugin>
<executions> <artifactId>maven-resources-plugin</artifactId>
<execution> <version>2.6</version>
<id>copy-resources</id> <executions>
<phase>validate</phase> <execution>
<goals> <id>copy-resources</id>
<goal>copy-resources</goal> <phase>validate</phase>
</goals> <goals>
<configuration> <goal>copy-resources</goal>
<outputDirectory>target/${project.artifactId}-${project.version}</outputDirectory> </goals>
<resources> <configuration>
<resource> <outputDirectory>target/${project.artifactId}-${project.version}</outputDirectory>
<directory>${project.build.directory}/swagger-ui-${swagger-ui-version}/dist</directory> <resources>
<filtering>true</filtering> <resource>
<excludes> <directory>${project.build.directory}/swagger-ui-${swagger-ui-version}/dist
<exclude>index.html</exclude> </directory>
</excludes> <filtering>true</filtering>
</resource> <excludes>
</resources> <exclude>index.html</exclude>
</configuration> </excludes>
</execution> </resource>
</executions> </resources>
</plugin> </configuration>
</plugins> </execution>
</build> </executions>
<dependencies> </plugin>
<dependency> </plugins>
<groupId>io.swagger</groupId> </build>
<artifactId>swagger-jersey-jaxrs</artifactId> <dependencies>
<version>${swagger-core-version}</version> <dependency>
</dependency> <groupId>io.swagger</groupId>
<dependency> <artifactId>swagger-jersey-jaxrs</artifactId>
<groupId>org.slf4j</groupId> <version>${swagger-core-version}</version>
<artifactId>slf4j-log4j12</artifactId> </dependency>
<version>${slf4j-version}</version> <dependency>
</dependency> <groupId>org.slf4j</groupId>
<dependency> <artifactId>slf4j-log4j12</artifactId>
<groupId>com.sun.jersey</groupId> <version>${slf4j-version}</version>
<artifactId>jersey-core</artifactId> </dependency>
<version>${jersey-version}</version> <dependency>
</dependency> <groupId>com.sun.jersey</groupId>
<dependency> <artifactId>jersey-core</artifactId>
<groupId>com.sun.jersey</groupId> <version>${jersey-version}</version>
<artifactId>jersey-json</artifactId> </dependency>
<version>${jersey-version}</version> <dependency>
</dependency> <groupId>com.sun.jersey</groupId>
<dependency> <artifactId>jersey-json</artifactId>
<groupId>com.sun.jersey</groupId> <version>${jersey-version}</version>
<artifactId>jersey-servlet</artifactId> </dependency>
<version>${jersey-version}</version> <dependency>
</dependency> <groupId>com.sun.jersey</groupId>
<dependency> <artifactId>jersey-servlet</artifactId>
<groupId>com.sun.jersey.contribs</groupId> <version>${jersey-version}</version>
<artifactId>jersey-multipart</artifactId> </dependency>
<version>${jersey-version}</version> <dependency>
</dependency> <groupId>com.sun.jersey.contribs</groupId>
<dependency> <artifactId>jersey-multipart</artifactId>
<groupId>com.sun.jersey</groupId> <version>${jersey-version}</version>
<artifactId>jersey-server</artifactId> </dependency>
<version>${jersey-version}</version> <dependency>
</dependency> <groupId>com.sun.jersey</groupId>
<artifactId>jersey-server</artifactId>
<version>${jersey-version}</version>
</dependency>
<!--Spring dependencies --> <!--Spring dependencies -->
<dependency> <dependency>
<groupId>org.springframework</groupId> <groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId> <artifactId>spring-core</artifactId>
<version>${spring-version}</version> <version>${spring-version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.springframework</groupId> <groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId> <artifactId>spring-webmvc</artifactId>
<version>${spring-version}</version> <version>${spring-version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.springframework</groupId> <groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId> <artifactId>spring-web</artifactId>
<version>${spring-version}</version> <version>${spring-version}</version>
</dependency> </dependency>
<!--SpringFox dependencies--> <!--SpringFox dependencies-->
<dependency> <dependency>
<groupId>io.springfox</groupId> <groupId>io.springfox</groupId>
<artifactId>springfox-core</artifactId> <artifactId>springfox-core</artifactId>
<version>${springfox-version}</version> <version>${springfox-version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>io.springfox</groupId> <groupId>io.springfox</groupId>
<artifactId>springfox-spi</artifactId> <artifactId>springfox-spi</artifactId>
<version>${springfox-version}</version> <version>${springfox-version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>io.springfox</groupId> <groupId>io.springfox</groupId>
<artifactId>springfox-spring-web</artifactId> <artifactId>springfox-spring-web</artifactId>
<version>${springfox-version}</version> <version>${springfox-version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>io.springfox</groupId> <groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId> <artifactId>springfox-swagger2</artifactId>
<version>${springfox-version}</version> <version>${springfox-version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>io.springfox</groupId> <groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId> <artifactId>springfox-swagger-ui</artifactId>
<version>${springfox-version}</version> <version>${springfox-version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.scalatest</groupId> <groupId>org.scalatest</groupId>
<artifactId>scalatest_2.9.1</artifactId> <artifactId>scalatest_2.9.1</artifactId>
<version>${scala-test-version}</version> <version>${scala-test-version}</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>junit</groupId> <groupId>junit</groupId>
<artifactId>junit</artifactId> <artifactId>junit</artifactId>
<version>${junit-version}</version> <version>${junit-version}</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>javax.servlet</groupId> <groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId> <artifactId>servlet-api</artifactId>
<version>${servlet-api-version}</version> <version>${servlet-api-version}</version>
</dependency> </dependency>
</dependencies> </dependencies>
<repositories> <repositories>
<repository> <repository>
<id>jcenter-snapshots</id> <id>jcenter-snapshots</id>
<name>jcenter</name> <name>jcenter</name>
<url>http://oss.jfrog.org/artifactory/oss-snapshot-local/</url> <url>http://oss.jfrog.org/artifactory/oss-snapshot-local/</url>
</repository> </repository>
</repositories> </repositories>
<properties> <properties>
<swagger-core-version>1.5.0</swagger-core-version> <swagger-core-version>1.5.0</swagger-core-version>
<jetty-version>9.2.9.v20150224</jetty-version> <jetty-version>9.2.9.v20150224</jetty-version>
<swagger-ui-version>2.1.0-M2</swagger-ui-version> <swagger-ui-version>2.1.0-M2</swagger-ui-version>
<jersey-version>1.13</jersey-version> <jersey-version>1.13</jersey-version>
<slf4j-version>1.6.3</slf4j-version> <slf4j-version>1.6.3</slf4j-version>
<scala-test-version>1.6.1</scala-test-version> <scala-test-version>1.6.1</scala-test-version>
<junit-version>4.8.1</junit-version> <junit-version>4.8.1</junit-version>
<servlet-api-version>2.5</servlet-api-version> <servlet-api-version>2.5</servlet-api-version>
<springfox-version>2.0.0-SNAPSHOT</springfox-version> <springfox-version>2.0.0-SNAPSHOT</springfox-version>
<spring-version>4.0.9.RELEASE</spring-version> <spring-version>4.0.9.RELEASE</spring-version>
</properties> </properties>
</project> </project>

View File

@ -19,22 +19,22 @@ import springfox.documentation.swagger2.annotations.EnableSwagger2;
@PropertySource("classpath:swagger.properties") @PropertySource("classpath:swagger.properties")
@Import(SwaggerUiConfiguration.class) @Import(SwaggerUiConfiguration.class)
public class SwaggerConfig { public class SwaggerConfig {
@Bean @Bean
ApiInfo apiInfo() { ApiInfo apiInfo() {
ApiInfo apiInfo = new ApiInfo( ApiInfo apiInfo = new ApiInfo(
"{{appName}}", "{{appName}}",
"{{{appDescription}}}", "{{{appDescription}}}",
"{{appVersion}}", "{{appVersion}}",
"{{infoUrl}}", "{{infoUrl}}",
"{{infoEmail}}", "{{infoEmail}}",
"{{licenseInfo}}", "{{licenseInfo}}",
"{{licenseUrl}}" ); "{{licenseUrl}}" );
return apiInfo; return apiInfo;
} }
@Bean @Bean
public Docket customImplementation(){ public Docket customImplementation(){
return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()); return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo());
} }
} }

View File

@ -9,38 +9,38 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter
@Configuration @Configuration
@EnableWebMvc @EnableWebMvc
public class SwaggerUiConfiguration extends WebMvcConfigurerAdapter { public class SwaggerUiConfiguration extends WebMvcConfigurerAdapter {
private static final String[] SERVLET_RESOURCE_LOCATIONS = { "/" }; private static final String[] SERVLET_RESOURCE_LOCATIONS = { "/" };
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = { private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {
"classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/META-INF/resources/", "classpath:/resources/",
"classpath:/static/", "classpath:/public/" }; "classpath:/static/", "classpath:/public/" };
private static final String[] RESOURCE_LOCATIONS; private static final String[] RESOURCE_LOCATIONS;
static { static {
RESOURCE_LOCATIONS = new String[CLASSPATH_RESOURCE_LOCATIONS.length RESOURCE_LOCATIONS = new String[CLASSPATH_RESOURCE_LOCATIONS.length
+ SERVLET_RESOURCE_LOCATIONS.length]; + SERVLET_RESOURCE_LOCATIONS.length];
System.arraycopy(SERVLET_RESOURCE_LOCATIONS, 0, RESOURCE_LOCATIONS, 0, System.arraycopy(SERVLET_RESOURCE_LOCATIONS, 0, RESOURCE_LOCATIONS, 0,
SERVLET_RESOURCE_LOCATIONS.length); SERVLET_RESOURCE_LOCATIONS.length);
System.arraycopy(CLASSPATH_RESOURCE_LOCATIONS, 0, RESOURCE_LOCATIONS, System.arraycopy(CLASSPATH_RESOURCE_LOCATIONS, 0, RESOURCE_LOCATIONS,
SERVLET_RESOURCE_LOCATIONS.length, CLASSPATH_RESOURCE_LOCATIONS.length); SERVLET_RESOURCE_LOCATIONS.length, CLASSPATH_RESOURCE_LOCATIONS.length);
} }
private static final String[] STATIC_INDEX_HTML_RESOURCES; private static final String[] STATIC_INDEX_HTML_RESOURCES;
static { static {
STATIC_INDEX_HTML_RESOURCES = new String[RESOURCE_LOCATIONS.length]; STATIC_INDEX_HTML_RESOURCES = new String[RESOURCE_LOCATIONS.length];
for (int i = 0; i < STATIC_INDEX_HTML_RESOURCES.length; i++) { for (int i = 0; i < STATIC_INDEX_HTML_RESOURCES.length; i++) {
STATIC_INDEX_HTML_RESOURCES[i] = RESOURCE_LOCATIONS[i] + "index.html"; STATIC_INDEX_HTML_RESOURCES[i] = RESOURCE_LOCATIONS[i] + "index.html";
} }
} }
@Override @Override
public void addResourceHandlers(ResourceHandlerRegistry registry) { public void addResourceHandlers(ResourceHandlerRegistry registry) {
if (!registry.hasMappingForPattern("/webjars/**")) { if (!registry.hasMappingForPattern("/webjars/**")) {
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/"); registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
} }
if (!registry.hasMappingForPattern("/**")) { if (!registry.hasMappingForPattern("/**")) {
registry.addResourceHandler("/**").addResourceLocations(RESOURCE_LOCATIONS); registry.addResourceHandler("/**").addResourceLocations(RESOURCE_LOCATIONS);
} }
} }
} }

View File

@ -4,18 +4,18 @@ import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatche
public class WebApplication extends AbstractAnnotationConfigDispatcherServletInitializer { public class WebApplication extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override @Override
protected Class<?>[] getRootConfigClasses() { protected Class<?>[] getRootConfigClasses() {
return new Class[] { SwaggerConfig.class }; return new Class[] { SwaggerConfig.class };
} }
@Override @Override
protected Class<?>[] getServletConfigClasses() { protected Class<?>[] getServletConfigClasses() {
return new Class<?>[] { WebMvcConfiguration.class }; return new Class<?>[] { WebMvcConfiguration.class };
} }
@Override @Override
protected String[] getServletMappings() { protected String[] getServletMappings() {
return new String[] { "/" }; return new String[] { "/" };
} }
} }

View File

@ -4,8 +4,8 @@ import org.springframework.web.servlet.config.annotation.DefaultServletHandlerCo
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
public class WebMvcConfiguration extends WebMvcConfigurationSupport { public class WebMvcConfiguration extends WebMvcConfigurationSupport {
@Override @Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable(); configurer.enable();
} }
} }

View File

@ -1,43 +1,43 @@
package {{package}} package {{package}}
{{#imports}} {{#imports}}
import {{import}} import {{import}}
{{/imports}} {{/imports}}
import {{invokerPackage}}._ import {{invokerPackage}}._
import {{invokerPackage}}.CollectionFormats._ import {{invokerPackage}}.CollectionFormats._
import {{invokerPackage}}.ApiKeyLocations._ import {{invokerPackage}}.ApiKeyLocations._
{{#operations}} {{#operations}}
object {{classname}} { object {{classname}} {
{{#operation}} {{#operation}}
{{#javadocRenderer}} {{#javadocRenderer}}
{{>javadoc}} {{>javadoc}}
{{/javadocRenderer}} {{/javadocRenderer}}
def {{operationId}}({{>methodParameters}}): ApiRequest[{{>operationReturnType}}] = def {{operationId}}({{>methodParameters}}): ApiRequest[{{>operationReturnType}}] =
ApiRequest[{{>operationReturnType}}](ApiMethods.{{httpMethod.toUpperCase}}, "{{basePath}}", "{{path}}", {{#consumes.0}}"{{mediaType}}"{{/consumes.0}}{{^consumes}}"application/json"{{/consumes}}) ApiRequest[{{>operationReturnType}}](ApiMethods.{{httpMethod.toUpperCase}}, "{{basePath}}", "{{path}}", {{#consumes.0}}"{{mediaType}}"{{/consumes.0}}{{^consumes}}"application/json"{{/consumes}})
{{#authMethods}}{{#isApiKey}}.withApiKey(apiKey, "{{keyParamName}}", {{#isKeyInQuery}}QUERY{{/isKeyInQuery}}{{#isKeyInHeader}}HEADER{{/isKeyInHeader}}) {{#authMethods}}{{#isApiKey}}.withApiKey(apiKey, "{{keyParamName}}", {{#isKeyInQuery}}QUERY{{/isKeyInQuery}}{{#isKeyInHeader}}HEADER{{/isKeyInHeader}})
{{/isApiKey}}{{#isBasic}}.withCredentials(basicAuth) {{/isApiKey}}{{#isBasic}}.withCredentials(basicAuth)
{{/isBasic}}{{/authMethods}}{{#bodyParam}}.withBody({{paramName}}) {{/isBasic}}{{/authMethods}}{{#bodyParam}}.withBody({{paramName}})
{{/bodyParam}}{{#formParams}}.withFormParam({{>paramCreation}}) {{/bodyParam}}{{#formParams}}.withFormParam({{>paramCreation}})
{{/formParams}}{{#queryParams}}.withQueryParam({{>paramCreation}}) {{/formParams}}{{#queryParams}}.withQueryParam({{>paramCreation}})
{{/queryParams}}{{#pathParams}}.withPathParam({{>paramCreation}}) {{/queryParams}}{{#pathParams}}.withPathParam({{>paramCreation}})
{{/pathParams}}{{#headerParams}}.withHeaderParam({{>paramCreation}}) {{/pathParams}}{{#headerParams}}.withHeaderParam({{>paramCreation}})
{{/headerParams}}{{#responses}}{{^isWildcard}}{{#dataType}}.with{{>responseState}}Response[{{dataType}}]({{code}}) {{/headerParams}}{{#responses}}{{^isWildcard}}{{#dataType}}.with{{>responseState}}Response[{{dataType}}]({{code}})
{{/dataType}}{{^dataType}}.with{{>responseState}}Response[Unit]({{code}}) {{/dataType}}{{^dataType}}.with{{>responseState}}Response[Unit]({{code}})
{{/dataType}}{{/isWildcard}}{{/responses}}{{#responses}}{{#isWildcard}}{{#dataType}}.withDefault{{>responseState}}Response[{{dataType}}] {{/dataType}}{{/isWildcard}}{{/responses}}{{#responses}}{{#isWildcard}}{{#dataType}}.withDefault{{>responseState}}Response[{{dataType}}]
{{/dataType}}{{^dataType}}.withDefault{{>responseState}}Response[Unit] {{/dataType}}{{^dataType}}.withDefault{{>responseState}}Response[Unit]
{{/dataType}}{{/isWildcard}}{{/responses}}{{^responseHeaders.isEmpty}} {{/dataType}}{{/isWildcard}}{{/responses}}{{^responseHeaders.isEmpty}}
object {{#fnCapitalize}}{{operationId}}{{/fnCapitalize}}Headers { {{#responseHeaders}} object {{#fnCapitalize}}{{operationId}}{{/fnCapitalize}}Headers { {{#responseHeaders}}
def {{name}}(r: ApiReturnWithHeaders) = r.get{{^isContainer}}{{baseType}}{{/isContainer}}{{#isContainer}}String{{/isContainer}}Header("{{baseName}}"){{/responseHeaders}} def {{name}}(r: ApiReturnWithHeaders) = r.get{{^isContainer}}{{baseType}}{{/isContainer}}{{#isContainer}}String{{/isContainer}}Header("{{baseName}}"){{/responseHeaders}}
} }
{{/responseHeaders.isEmpty}} {{/responseHeaders.isEmpty}}
{{/operation}} {{/operation}}
{{#unknownStatusCodes}} {{#unknownStatusCodes}}
ApiInvoker.addCustomStatusCode({{value}}, isSuccess = false) ApiInvoker.addCustomStatusCode({{value}}, isSuccess = false)
{{/unknownStatusCodes}} {{/unknownStatusCodes}}
} }
{{/operations}} {{/operations}}

View File

@ -33,291 +33,292 @@ import scala.util.control.NonFatal
object ApiInvoker { object ApiInvoker {
def apply()(implicit system: ActorSystem): ApiInvoker = def apply()(implicit system: ActorSystem): ApiInvoker =
apply(DefaultFormats + DateTimeSerializer) apply(DefaultFormats + DateTimeSerializer)
def apply(serializers: Traversable[Serializer[_]])(implicit system: ActorSystem): ApiInvoker = def apply(serializers: Traversable[Serializer[_]])(implicit system: ActorSystem): ApiInvoker =
apply(DefaultFormats + DateTimeSerializer ++ serializers) apply(DefaultFormats + DateTimeSerializer ++ serializers)
def apply(formats: Formats)(implicit system: ActorSystem): ApiInvoker = new ApiInvoker(formats) def apply(formats: Formats)(implicit system: ActorSystem): ApiInvoker = new ApiInvoker(formats)
case class CustomStatusCode(value: Int, reason: String = "Application-defined status code", isSuccess: Boolean = true) case class CustomStatusCode(value: Int, reason: String = "Application-defined status code", isSuccess: Boolean = true)
def addCustomStatusCode(code: CustomStatusCode): Unit = addCustomStatusCode(code.value, code.reason, code.isSuccess) def addCustomStatusCode(code: CustomStatusCode): Unit = addCustomStatusCode(code.value, code.reason, code.isSuccess)
def addCustomStatusCode(code: Int, reason: String = "Application defined code", isSuccess: Boolean = true) = { def addCustomStatusCode(code: Int, reason: String = "Application defined code", isSuccess: Boolean = true) = {
StatusCodes.getForKey(code) foreach { c => StatusCodes.getForKey(code) foreach { c =>
StatusCodes.registerCustom(code, reason, reason, isSuccess, allowsEntity = true) StatusCodes.registerCustom(code, reason, reason, isSuccess, allowsEntity = true)
} }
} }
/** /**
* Allows request execution without calling apiInvoker.execute(request) * Allows request execution without calling apiInvoker.execute(request)
* request.response can be used to get a future of the ApiResponse generated. * request.response can be used to get a future of the ApiResponse generated.
* request.result can be used to get a future of the expected ApiResponse content. If content doesn't match, a * request.result can be used to get a future of the expected ApiResponse content. If content doesn't match, a
* Future will failed with a ClassCastException * Future will failed with a ClassCastException
* @param request the apiRequest to be executed * @param request the apiRequest to be executed
*/ */
implicit class ApiRequestImprovements[T](request: ApiRequest[T]) { implicit class ApiRequestImprovements[T](request: ApiRequest[T]) {
def response(invoker: ApiInvoker)(implicit ec: ExecutionContext, system: ActorSystem): Future[ApiResponse[T]] = def response(invoker: ApiInvoker)(implicit ec: ExecutionContext, system: ActorSystem): Future[ApiResponse[T]] =
response(ec, system, invoker) response(ec, system, invoker)
def response(implicit ec: ExecutionContext, system: ActorSystem, invoker: ApiInvoker): Future[ApiResponse[T]] = def response(implicit ec: ExecutionContext, system: ActorSystem, invoker: ApiInvoker): Future[ApiResponse[T]] =
invoker.execute(request) invoker.execute(request)
def result[U <: T](implicit c: ClassTag[U], ec: ExecutionContext, system: ActorSystem, invoker: ApiInvoker): Future[U] = def result[U
invoker.execute(request).map(_.content).mapTo[U] <: T](implicit c: ClassTag[U], ec: ExecutionContext, system: ActorSystem, invoker: ApiInvoker): Future[U]=
invoker.execute(request).map(_.content).mapTo[U]
} }
/** /**
* Allows transformation from ApiMethod to spray HttpMethods * Allows transformation from ApiMethod to spray HttpMethods
* @param method the ApiMethod to be converted * @param method the ApiMethod to be converted
*/ */
implicit class ApiMethodExtensions(val method: ApiMethod) { implicit class ApiMethodExtensions(val method: ApiMethod) {
def toSprayMethod: HttpMethod = HttpMethods.getForKey(method.value).getOrElse(HttpMethods.GET) def toSprayMethod: HttpMethod = HttpMethods.getForKey(method.value).getOrElse(HttpMethods.GET)
} }
case object DateTimeSerializer extends CustomSerializer[DateTime](format => ( { case object DateTimeSerializer extends CustomSerializer[DateTime](format => ( {
case JString(s) => case JString(s) =>
ISODateTimeFormat.dateTimeParser().parseDateTime(s) ISODateTimeFormat.dateTimeParser().parseDateTime(s)
}, { }, {
case d: DateTime => case d: DateTime =>
JString(ISODateTimeFormat.dateTimeParser().print(d)) JString(ISODateTimeFormat.dateTimeParser().print(d))
})) }))
} }
class ApiInvoker(formats: Formats)(implicit system: ActorSystem) extends UntrustedSslContext with CustomContentTypes { class ApiInvoker(formats: Formats)(implicit system: ActorSystem) extends UntrustedSslContext with CustomContentTypes {
import io.swagger.client.core.ApiInvoker._ import io.swagger.client.core.ApiInvoker._
import io.swagger.client.core.ParametersMap._ import io.swagger.client.core.ParametersMap._
implicit val ec = system.dispatcher implicit val ec = system.dispatcher
implicit val jsonFormats = formats implicit val jsonFormats = formats
def settings = ApiSettings(system) def settings = ApiSettings(system)
import spray.http.MessagePredicate._ import spray.http.MessagePredicate._
val CompressionFilter = MessagePredicate({ _ => settings.compressionEnabled}) && val CompressionFilter = MessagePredicate({ _ => settings.compressionEnabled}) &&
Encoder.DefaultFilter && Encoder.DefaultFilter &&
minEntitySize(settings.compressionSizeThreshold) minEntitySize(settings.compressionSizeThreshold)
settings.customCodes.foreach(addCustomStatusCode) settings.customCodes.foreach(addCustomStatusCode)
private def addAuthentication(credentialsSeq: Seq[Credentials]): pipelining.RequestTransformer = private def addAuthentication(credentialsSeq: Seq[Credentials]): pipelining.RequestTransformer =
request => request =>
credentialsSeq.foldLeft(request) { credentialsSeq.foldLeft(request) {
case (req, BasicCredentials(login, password)) => case (req, BasicCredentials(login, password)) =>
req ~> addCredentials(BasicHttpCredentials(login, password)) req ~> addCredentials(BasicHttpCredentials(login, password))
case (req, ApiKeyCredentials(keyValue, keyName, ApiKeyLocations.HEADER)) => case (req, ApiKeyCredentials(keyValue, keyName, ApiKeyLocations.HEADER)) =>
req ~> addHeader(RawHeader(keyName, keyValue.value)) req ~> addHeader(RawHeader(keyName, keyValue.value))
case (req, _) => req case (req, _) => req
} }
private def addHeaders(headers: Map[String, Any]): pipelining.RequestTransformer = { request => private def addHeaders(headers: Map[String, Any]): pipelining.RequestTransformer = { request =>
val rawHeaders = for { val rawHeaders = for {
(name, value) <- headers.asFormattedParams (name, value) <- headers.asFormattedParams
header = RawHeader(name, String.valueOf(value)) header = RawHeader(name, String.valueOf(value))
} yield header } yield header
request.withHeaders(rawHeaders.toList) request.withHeaders(rawHeaders.toList)
} }
private def bodyPart(name: String, value: Any): BodyPart = { private def bodyPart(name: String, value: Any): BodyPart = {
value match { value match {
case f: File => case f: File =>
BodyPart(f, name) BodyPart(f, name)
case v: String => case v: String =>
BodyPart(HttpEntity(String.valueOf(v))) BodyPart(HttpEntity(String.valueOf(v)))
case NumericValue(v) => case NumericValue(v) =>
BodyPart(HttpEntity(String.valueOf(v))) BodyPart(HttpEntity(String.valueOf(v)))
case m: ApiModel => case m: ApiModel =>
BodyPart(HttpEntity(Serialization.write(m))) BodyPart(HttpEntity(Serialization.write(m)))
} }
} }
private def formDataContent(request: ApiRequest[_]) = { private def formDataContent(request: ApiRequest[_]) = {
val params = request.formParams.asFormattedParams val params = request.formParams.asFormattedParams
if (params.isEmpty) if (params.isEmpty)
None None
else else
Some( Some(
normalizedContentType(request.contentType).mediaType match { normalizedContentType(request.contentType).mediaType match {
case MediaTypes.`multipart/form-data` => case MediaTypes.`multipart/form-data` =>
MultipartFormData(params.map { case (name, value) => (name, bodyPart(name, value))}) MultipartFormData(params.map { case (name, value) => (name, bodyPart(name, value))})
case MediaTypes.`application/x-www-form-urlencoded` => case MediaTypes.`application/x-www-form-urlencoded` =>
FormData(params.mapValues(String.valueOf)) FormData(params.mapValues(String.valueOf))
case m: MediaType => // Default : application/x-www-form-urlencoded. case m: MediaType => // Default : application/x-www-form-urlencoded.
FormData(params.mapValues(String.valueOf)) FormData(params.mapValues(String.valueOf))
} }
) )
} }
private def bodyContent(request: ApiRequest[_]): Option[Any] = { private def bodyContent(request: ApiRequest[_]): Option[Any] = {
request.bodyParam.map(Extraction.decompose).map(compact) request.bodyParam.map(Extraction.decompose).map(compact)
} }
private def createRequest(uri: Uri, request: ApiRequest[_]): HttpRequest = { private def createRequest(uri: Uri, request: ApiRequest[_]): HttpRequest = {
val builder = new RequestBuilder(request.method.toSprayMethod) val builder = new RequestBuilder(request.method.toSprayMethod)
val httpRequest = request.method.toSprayMethod match { val httpRequest = request.method.toSprayMethod match {
case HttpMethods.GET | HttpMethods.DELETE => builder.apply(uri) case HttpMethods.GET | HttpMethods.DELETE => builder.apply(uri)
case HttpMethods.POST | HttpMethods.PUT => case HttpMethods.POST | HttpMethods.PUT =>
formDataContent(request) orElse bodyContent(request) match { formDataContent(request) orElse bodyContent(request) match {
case Some(c: FormData) => case Some(c: FormData) =>
builder.apply(uri, c) builder.apply(uri, c)
case Some(c: MultipartFormData) => case Some(c: MultipartFormData) =>
builder.apply(uri, c) builder.apply(uri, c)
case Some(c: String) => case Some(c: String) =>
builder.apply(uri, HttpEntity(normalizedContentType(request.contentType), c)) builder.apply(uri, HttpEntity(normalizedContentType(request.contentType), c))
case _ => case _ =>
builder.apply(uri, HttpEntity(normalizedContentType(request.contentType), " ")) builder.apply(uri, HttpEntity(normalizedContentType(request.contentType), " "))
} }
case _ => builder.apply(uri) case _ => builder.apply(uri)
} }
httpRequest ~> httpRequest ~>
addHeaders(request.headerParams) ~> addHeaders(request.headerParams) ~>
addAuthentication(request.credentials) ~> addAuthentication(request.credentials) ~>
encode(Gzip(CompressionFilter)) encode(Gzip(CompressionFilter))
} }
def makeQuery(r: ApiRequest[_]): Query = { def makeQuery(r: ApiRequest[_]): Query = {
r.credentials.foldLeft(r.queryParams) { r.credentials.foldLeft(r.queryParams) {
case (params, ApiKeyCredentials(key, keyName, ApiKeyLocations.QUERY)) => case (params, ApiKeyCredentials(key, keyName, ApiKeyLocations.QUERY)) =>
params + (keyName -> key.value) params + (keyName -> key.value)
case (params, _) => params case (params, _) => params
}.asFormattedParams }.asFormattedParams
.mapValues(String.valueOf) .mapValues(String.valueOf)
.foldRight[Query](Uri.Query.Empty) { .foldRight[Query](Uri.Query.Empty) {
case ((name, value), acc) => acc.+:(name, value) case ((name, value), acc) => acc.+:(name, value)
} }
} }
def makeUri(r: ApiRequest[_]): Uri = { def makeUri(r: ApiRequest[_]): Uri = {
val opPath = r.operationPath.replaceAll("\\{format\\}", "json") val opPath = r.operationPath.replaceAll("\\{format\\}", "json")
val opPathWithParams = r.pathParams.asFormattedParams val opPathWithParams = r.pathParams.asFormattedParams
.mapValues(String.valueOf) .mapValues(String.valueOf)
.foldLeft(opPath) { .foldLeft(opPath) {
case (path, (name, value)) => path.replaceAll(s"\\{$name\\}", value) case (path, (name, value)) => path.replaceAll(s"\\{$name\\}", value)
} }
val query = makeQuery(r) val query = makeQuery(r)
Uri(r.basePath + opPathWithParams).withQuery(query) Uri(r.basePath + opPathWithParams).withQuery(query)
} }
def execute[T](r: ApiRequest[T]): Future[ApiResponse[T]] = { def execute[T](r: ApiRequest[T]): Future[ApiResponse[T]] = {
try { try {
implicit val timeout: Timeout = settings.connectionTimeout implicit val timeout: Timeout = settings.connectionTimeout
val uri = makeUri(r) val uri = makeUri(r)
val connector = HostConnectorSetup( val connector = HostConnectorSetup(
uri.authority.host.toString, uri.authority.host.toString,
uri.effectivePort, uri.effectivePort,
sslEncryption = "https".equals(uri.scheme), sslEncryption = "https".equals(uri.scheme),
defaultHeaders = settings.defaultHeaders ++ List(`Accept-Encoding`(gzip, deflate))) defaultHeaders = settings.defaultHeaders ++ List(`Accept-Encoding`(gzip, deflate)))
val request = createRequest(uri, r) val request = createRequest(uri, r)
for { for {
Http.HostConnectorInfo(hostConnector, _) <- IO(Http) ? connector Http.HostConnectorInfo(hostConnector, _) <- IO(Http) ? connector
response <- hostConnector.ask(request).mapTo[HttpResponse] response <- hostConnector.ask(request).mapTo[HttpResponse]
} yield { } yield {
response ~> decode(Deflate) ~> decode(Gzip) ~> unmarshallApiResponse(r) response ~> decode(Deflate) ~> decode(Gzip) ~> unmarshallApiResponse(r)
} }
} }
catch { catch {
case NonFatal(x) => Future.failed(x) case NonFatal(x) => Future.failed(x)
} }
} }
def unmarshallApiResponse[T](request: ApiRequest[T])(response: HttpResponse): ApiResponse[T] = { def unmarshallApiResponse[T](request: ApiRequest[T])(response: HttpResponse): ApiResponse[T] = {
request.responseForCode(response.status.intValue) match { request.responseForCode(response.status.intValue) match {
case Some( (manifest: Manifest[T], state: ResponseState) ) => case Some( (manifest: Manifest[T], state: ResponseState) ) =>
entityUnmarshaller(manifest)(response.entity) match { entityUnmarshaller(manifest)(response.entity) match {
case Right(value) ⇒ case Right(value) ⇒
state match { state match {
case ResponseState.Success => case ResponseState.Success =>
ApiResponse(response.status.intValue, value, response.headers.map(header => (header.name, header.value)).toMap) ApiResponse(response.status.intValue, value, response.headers.map(header => (header.name, header.value)).toMap)
case ResponseState.Error => case ResponseState.Error =>
throw new ApiError(response.status.intValue, "Error response received", throw new ApiError(response.status.intValue, "Error response received",
Some(value), Some(value),
headers = response.headers.map(header => (header.name, header.value)).toMap) headers = response.headers.map(header => (header.name, header.value)).toMap)
} }
case Left(MalformedContent(error, Some(cause))) ⇒ case Left(MalformedContent(error, Some(cause))) ⇒
throw new ApiError(response.status.intValue, s"Unable to unmarshall content to [$manifest]", Some(response.entity.toString), cause) throw new ApiError(response.status.intValue, s"Unable to unmarshall content to [$manifest]", Some(response.entity.toString), cause)
case Left(MalformedContent(error, None)) ⇒ case Left(MalformedContent(error, None)) ⇒
throw new ApiError(response.status.intValue, s"Unable to unmarshall content to [$manifest]", Some(response.entity.toString)) throw new ApiError(response.status.intValue, s"Unable to unmarshall content to [$manifest]", Some(response.entity.toString))
case Left(ContentExpected) ⇒ case Left(ContentExpected) ⇒
throw new ApiError(response.status.intValue, s"Unable to unmarshall empty response to [$manifest]", Some(response.entity.toString)) throw new ApiError(response.status.intValue, s"Unable to unmarshall empty response to [$manifest]", Some(response.entity.toString))
} }
case _ => throw new ApiError(response.status.intValue, "Unexpected response code", Some(response.entity.toString)) case _ => throw new ApiError(response.status.intValue, "Unexpected response code", Some(response.entity.toString))
} }
} }
def entityUnmarshaller[T](implicit mf: Manifest[T]): Unmarshaller[T] = def entityUnmarshaller[T](implicit mf: Manifest[T]): Unmarshaller[T] =
Unmarshaller[T](MediaTypes.`application/json`) { Unmarshaller[T](MediaTypes.`application/json`) {
case x: HttpEntity.NonEmpty ⇒ case x: HttpEntity.NonEmpty ⇒
parse(x.asString(defaultCharset = HttpCharsets.`UTF-8`)) parse(x.asString(defaultCharset = HttpCharsets.`UTF-8`))
.noNulls .noNulls
.camelizeKeys .camelizeKeys
.extract[T] .extract[T]
} }
} }
sealed trait CustomContentTypes { sealed trait CustomContentTypes {
def normalizedContentType(original: String): ContentType = def normalizedContentType(original: String): ContentType =
MediaTypes.forExtension(original) map (ContentType(_)) getOrElse parseContentType(original) MediaTypes.forExtension(original) map (ContentType(_)) getOrElse parseContentType(original)
def parseContentType(contentType: String): ContentType = { def parseContentType(contentType: String): ContentType = {
val contentTypeAsRawHeader = HttpHeaders.RawHeader("Content-Type", contentType) val contentTypeAsRawHeader = HttpHeaders.RawHeader("Content-Type", contentType)
val parsedContentTypeHeader = HttpParser.parseHeader(contentTypeAsRawHeader) val parsedContentTypeHeader = HttpParser.parseHeader(contentTypeAsRawHeader)
(parsedContentTypeHeader: @unchecked) match { (parsedContentTypeHeader: @unchecked) match {
case Right(ct: HttpHeaders.`Content-Type`) => case Right(ct: HttpHeaders.`Content-Type`) =>
ct.contentType ct.contentType
case Left(error: ErrorInfo) => case Left(error: ErrorInfo) =>
throw new IllegalArgumentException( throw new IllegalArgumentException(
s"Error converting '$contentType' to a ContentType header: '${error.summary}'") s"Error converting '$contentType' to a ContentType header: '${error.summary}'")
} }
} }
} }
sealed trait UntrustedSslContext { sealed trait UntrustedSslContext {
this: ApiInvoker => this: ApiInvoker =>
implicit lazy val trustfulSslContext: SSLContext = { implicit lazy val trustfulSslContext: SSLContext = {
settings.alwaysTrustCertificates match { settings.alwaysTrustCertificates match {
case false => case false =>
SSLContext.getDefault SSLContext.getDefault
case true => case true =>
class IgnoreX509TrustManager extends X509TrustManager { class IgnoreX509TrustManager extends X509TrustManager {
def checkClientTrusted(chain: Array[X509Certificate], authType: String): Unit = {} def checkClientTrusted(chain: Array[X509Certificate], authType: String): Unit = {}
def checkServerTrusted(chain: Array[X509Certificate], authType: String): Unit = {} def checkServerTrusted(chain: Array[X509Certificate], authType: String): Unit = {}
def getAcceptedIssuers = null def getAcceptedIssuers = null
} }
val context = SSLContext.getInstance("TLS") val context = SSLContext.getInstance("TLS")
context.init(null, Array(new IgnoreX509TrustManager), null) context.init(null, Array(new IgnoreX509TrustManager), null)
context context
} }
} }
implicit val clientSSLEngineProvider = implicit val clientSSLEngineProvider =
ClientSSLEngineProvider { ClientSSLEngineProvider {
_ => _ =>
val engine = trustfulSslContext.createSSLEngine() val engine = trustfulSslContext.createSSLEngine()
engine.setUseClientMode(true) engine.setUseClientMode(true)
engine engine
} }
} }

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