Merge pull request #1138 from Helmsdown/cli-enhancements

Expose more configuration items in the CLI
This commit is contained in:
wing328 2015-08-30 22:46:25 +08:00
commit adee62da7d
33 changed files with 927 additions and 264 deletions

View File

@ -70,33 +70,34 @@
<artifactId>swagger-codegen</artifactId> <artifactId>swagger-codegen</artifactId>
<version>${project.version}</version> <version>${project.version}</version>
</dependency> </dependency>
<!--https://github.com/airlift/airline--> <!--https://github.com/airlift/airline-->
<dependency> <dependency>
<groupId>io.airlift</groupId> <groupId>io.airlift</groupId>
<artifactId>airline</artifactId> <artifactId>airline</artifactId>
<version>0.7</version> <version>0.7</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.googlecode.lambdaj</groupId> <groupId>com.googlecode.lambdaj</groupId>
<artifactId>lambdaj</artifactId> <artifactId>lambdaj</artifactId>
<version>2.3.3</version> <version>2.3.3</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.slf4j</groupId> <groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId> <artifactId>slf4j-simple</artifactId>
<version>${slf4j-version}</version> <version>${slf4j-version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>junit</groupId> <groupId>org.testng</groupId>
<artifactId>junit</artifactId> <artifactId>testng</artifactId>
<version>${junit-version}</version> <version>${testng-version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jmockit</groupId>
<artifactId>jmockit</artifactId>
<version>${jmockit-version}</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
</dependencies> </dependencies>
</project> </project>

View File

@ -4,10 +4,7 @@ import io.airlift.airline.Command;
import io.airlift.airline.Option; import io.airlift.airline.Option;
import io.swagger.codegen.CliOption; import io.swagger.codegen.CliOption;
import io.swagger.codegen.CodegenConfig; import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenConfigLoader;
import java.util.ServiceLoader;
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 {
@ -16,32 +13,10 @@ public class ConfigHelp implements Runnable {
description = "language to get config help for") description = "language to get config help for")
private String lang; private String lang;
/**
* 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() {
System.out.println(); System.out.println();
CodegenConfig config = forName(lang); CodegenConfig config = CodegenConfigLoader.forName(lang);
System.out.println("CONFIG OPTIONS"); System.out.println("CONFIG OPTIONS");
for (CliOption langCliOption : config.cliOptions()) { for (CliOption langCliOption : config.cliOptions()) {
System.out.println("\t" + langCliOption.getOpt()); System.out.println("\t" + langCliOption.getOpt());

View File

@ -8,16 +8,21 @@ 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.CodegenConfigLoader;
import io.swagger.codegen.CodegenConstants;
import io.swagger.codegen.DefaultGenerator; import io.swagger.codegen.DefaultGenerator;
import io.swagger.codegen.cmd.utils.OptionUtils;
import io.swagger.models.Swagger; import io.swagger.models.Swagger;
import io.swagger.parser.SwaggerParser; import io.swagger.parser.SwaggerParser;
import org.apache.commons.lang3.tuple.Pair;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.io.File; import java.io.File;
import java.util.ServiceLoader; import java.util.List;
import java.util.Map;
import java.util.Set;
import static java.util.ServiceLoader.load;
import static org.apache.commons.lang3.StringUtils.isNotEmpty; import static org.apache.commons.lang3.StringUtils.isNotEmpty;
/** /**
@ -31,8 +36,6 @@ public class Generate implements Runnable {
public static final Logger LOG = LoggerFactory.getLogger(Generate.class); public static final Logger LOG = LoggerFactory.getLogger(Generate.class);
public static final String TEMPLATE_DIR_PARAM = "templateDir";
@Option(name = {"-v", "--verbose"}, description = "verbose mode") @Option(name = {"-v", "--verbose"}, description = "verbose mode")
private boolean verbose; private boolean verbose;
@ -70,29 +73,42 @@ public class Generate implements Runnable {
"overwritten during the generation.") "overwritten during the generation.")
private boolean skipOverwrite; private boolean skipOverwrite;
/** @Option(name = {"--api-package"}, title = "api package", description = CodegenConstants.API_PACKAGE_DESC)
* Tries to load config class with SPI first, then with class name directly from classpath private String apiPackage;
*
* @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);
String available = "";
for (CodegenConfig config : loader) {
if (config.getName().equals(name)) {
return config;
}
available = available + config.getName() + "\n";
}
// else try to load directly @Option(name = {"--model-package"}, title = "model package", description = CodegenConstants.MODEL_PACKAGE_DESC)
try { private String modelPackage;
return (CodegenConfig) Class.forName(name).newInstance();
} catch (Exception e) { @Option(name = {"--instantiation-types"}, title = "instantiation types", description = "sets instantiation type mappings in the format of type=instantiatedType,type=instantiatedType." +
throw new RuntimeException("Can't load config class with name ".concat(name) + "Available: "+available, e); "For example (in Java): array=ArrayList,map=HashMap. In other words array types will get instantiated as ArrayList in generated code.")
} private String instantiationTypes;
}
@Option(name = {"--type-mappings"}, title = "type mappings", description = "sets mappings between swagger spec types and generated code types " +
"in the format of swaggerType=generatedType,swaggerType=generatedType. For example: array=List,map=Map,string=String")
private String typeMappings;
@Option(name = {"--additional-properties"}, title = "additional properties", description = "sets additional properties that can be referenced by the mustache templates in the format of name=value,name=value")
private String additionalProperties;
@Option(name = {"--language-specific-primitives"}, title = "language specific primitives",
description = "specifies additional language specific primitive types in the format of type1,type2,type3,type3. For example: String,boolean,Boolean,Double")
private String languageSpecificPrimitives;
@Option(name = {"--import-mappings"}, title = "import mappings",
description = "specifies mappings between a given class and the import that should be used for that class in the format of type=import,type=import")
private String importMappings;
@Option(name = {"--invoker-package"}, title = "invoker package", description = CodegenConstants.INVOKER_PACKAGE_DESC)
private String invokerPackage;
@Option(name = {"--group-id"}, title = "group id", description = CodegenConstants.GROUP_ID_DESC)
private String groupId;
@Option(name = {"--artifact-id"}, title = "artifact id", description = CodegenConstants.ARTIFACT_ID_DESC)
private String artifactId;
@Option(name = {"--artifact-version"}, title = "artifact version", description = CodegenConstants.ARTIFACT_VERSION_DESC)
private String artifactVersion;
@Override @Override
public void run() { public void run() {
@ -100,19 +116,30 @@ public class Generate implements Runnable {
setSystemProperties(); setSystemProperties();
ClientOptInput input = new ClientOptInput(); CodegenConfig config = CodegenConfigLoader.forName(lang);
if (isNotEmpty(auth)) {
input.setAuth(auth);
}
CodegenConfig config = forName(lang);
config.setOutputDir(new File(output).getAbsolutePath()); config.setOutputDir(new File(output).getAbsolutePath());
config.setSkipOverwrite(skipOverwrite);
if (null != templateDir) { putKeyValuePairsInMap(config.instantiationTypes(), instantiationTypes);
config.additionalProperties().put(TEMPLATE_DIR_PARAM, new File(templateDir).getAbsolutePath()); putKeyValuePairsInMap(config.typeMapping(), typeMappings);
putKeyValuePairsInMap(config.additionalProperties(), additionalProperties);
putKeyValuePairsInMap(config.importMapping(), importMappings);
addValuesToSet(config.languageSpecificPrimitives(), languageSpecificPrimitives);
checkAndSetAdditionalProperty(config, apiPackage, CodegenConstants.API_PACKAGE);
checkAndSetAdditionalProperty(config, modelPackage, CodegenConstants.MODEL_PACKAGE);
if(isNotEmpty(templateDir)) {
config.additionalProperties().put(CodegenConstants.TEMPLATE_DIR, new File(templateDir).getAbsolutePath());
} }
checkAndSetAdditionalProperty(config, invokerPackage, CodegenConstants.INVOKER_PACKAGE);
checkAndSetAdditionalProperty(config, groupId, CodegenConstants.GROUP_ID);
checkAndSetAdditionalProperty(config, artifactId, CodegenConstants.ARTIFACT_ID);
checkAndSetAdditionalProperty(config, artifactVersion, CodegenConstants.ARTIFACT_VERSION);
if (null != configFile) { if (null != configFile) {
Config genConfig = ConfigParser.read(configFile); Config genConfig = ConfigParser.read(configFile);
if (null != genConfig) { if (null != genConfig) {
@ -129,24 +156,52 @@ public class Generate implements Runnable {
} }
} }
config.setSkipOverwrite(skipOverwrite); ClientOptInput input = new ClientOptInput().config(config);
input.setConfig(config);
if (isNotEmpty(auth)) {
input.setAuth(auth);
}
Swagger swagger = new SwaggerParser().read(spec, input.getAuthorizationValues(), true); Swagger swagger = new SwaggerParser().read(spec, input.getAuthorizationValues(), true);
new DefaultGenerator().opts(input.opts(new ClientOpts()).swagger(swagger)).generate(); new DefaultGenerator().opts(input.opts(new ClientOpts()).swagger(swagger)).generate();
} }
private void addValuesToSet(Set<String> set, String csvProperty) {
final List<String> values = OptionUtils.splitCommaSeparatedList(csvProperty);
for (String value : values) {
set.add(value);
}
}
private void checkAndSetAdditionalProperty(CodegenConfig config, String property, String propertyKey) {
checkAndSetAdditionalProperty(config, property, property, propertyKey);
}
private void checkAndSetAdditionalProperty(CodegenConfig config, String property, String valueToSet, String propertyKey) {
if(isNotEmpty(property)) {
config.additionalProperties().put(propertyKey, valueToSet);
}
}
private void setSystemProperties() { private void setSystemProperties() {
if (systemProperties != null && systemProperties.length() > 0) {
for (String property : systemProperties.split(",")) { final List<Pair<String, String>> systemPropertyPairs = OptionUtils.parseCommaSeparatedTuples(systemProperties);
int ix = property.indexOf('=');
if (ix > 0 && ix < property.length() - 1) { for (Pair<String, String> pair : systemPropertyPairs) {
System.setProperty(property.substring(0, ix), property.substring(ix + 1)); System.setProperty(pair.getLeft(), pair.getRight());
} }
} }
private void putKeyValuePairsInMap(Map map, String commaSeparatedKVPairs) {
final List<Pair<String, String>> pairs = OptionUtils.parseCommaSeparatedTuples(commaSeparatedKVPairs);
for (Pair<String, String> pair : pairs) {
map.put(pair.getLeft(), pair.getRight());
} }
} }
/** /**
* If true parameter, adds system properties which enables debug mode in generator * If true parameter, adds system properties which enables debug mode in generator
* *

View File

@ -0,0 +1,43 @@
package io.swagger.codegen.cmd.utils;
import org.apache.commons.lang3.tuple.Pair;
import java.util.ArrayList;
import java.util.List;
import static org.apache.commons.lang3.StringUtils.isNotEmpty;
public class OptionUtils {
public static List<Pair<String, String>> parseCommaSeparatedTuples(String input) {
List<Pair<String, String>> results = new ArrayList<Pair<String, String>>();
final List<String> tuples = splitCommaSeparatedList(input);
for (String tuple : tuples) {
int ix = tuple.indexOf('=');
if (ix > 0 && ix < tuple.length() - 1) {
final Pair<String, String> pair = Pair.of(tuple.substring(0, ix), tuple.substring(ix + 1));
results.add(pair);
}
}
return results;
}
public static List<String> splitCommaSeparatedList(String input) {
List<String> results = new ArrayList<String>();
if(input != null && !input.isEmpty()) {
for (String value : input.split(",")) {
if(isNotEmpty(value))
results.add(value);
}
}
return results;
}
}

View File

@ -0,0 +1,352 @@
package io.swagger.codegen.cmd;
import config.Config;
import config.ConfigParser;
import io.swagger.codegen.ClientOptInput;
import io.swagger.codegen.ClientOpts;
import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenConstants;
import io.swagger.codegen.DefaultGenerator;
import io.swagger.codegen.SwaggerCodegen;
import io.swagger.codegen.CodegenConfigLoader;
import io.swagger.codegen.languages.JavaClientCodegen;
import io.swagger.models.Swagger;
import io.swagger.models.auth.AuthorizationValue;
import io.swagger.parser.SwaggerParser;
import mockit.Expectations;
import mockit.FullVerifications;
import mockit.Injectable;
import mockit.Mocked;
import mockit.StrictExpectations;
import org.apache.commons.lang3.ArrayUtils;
import org.testng.annotations.Test;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;
public class GenerateTest {
@Mocked
SwaggerParser parser;
@Injectable
Swagger swagger;
@Mocked
DefaultGenerator defaultGenerator;
@Mocked
CodegenConfigLoader codegenConfigLoader;
@Mocked
ClientOptInput clientOptInput;
@Injectable
List<AuthorizationValue> authorizationValues;
@Test
public void testVerbose_ShortArg() throws Exception {
doVerboseTest("-v");
}
@Test
public void testVerbose_LongArg() throws Exception {
doVerboseTest("--verbose");
}
@Test
public void testRequiredArgs_ShortArgs() throws Exception {
doRequiredArgsTest("-l", "-o", "-i");
}
@Test
public void testRequiredArgs_LongArgs() throws Exception {
doRequiredArgsTest("--lang", "--output", "--input-spec");
}
@Test
public void testTemplateDir() throws Exception {
final String absolutePath = new File("src").getAbsolutePath();
doSingleAdditionalPropertyTest("--template-dir", CodegenConstants.TEMPLATE_DIR, "src", absolutePath);
doSingleAdditionalPropertyTest("--template-dir", CodegenConstants.TEMPLATE_DIR, absolutePath, absolutePath);
doSingleAdditionalPropertyTest("-t", CodegenConstants.TEMPLATE_DIR, "src", absolutePath);
doSingleAdditionalPropertyTest("-t", CodegenConstants.TEMPLATE_DIR, absolutePath, absolutePath);
}
@Test
public void testAuth() throws Exception {
final String auth = "hello:world";
new StrictExpectations() {{
clientOptInput.setAuth(auth);
times = 1;
}};
setupAndRunGenericTest("-a", auth);
new StrictExpectations() {{
clientOptInput.setAuth(auth);
times = 1;
}};
setupAndRunGenericTest("--auth", auth);
}
@Test
public void testSystemProperties() throws Exception {
new StrictExpectations(System.class) {{
System.setProperty("hello", "world");
times = 1;
System.setProperty("foo", "bar");
times = 1;
}};
setupAndRunGenericTest("-D", "hello=world,foo=bar");
}
@Test
public void testConfig(@Mocked final ConfigParser parser) throws Exception {
final String configFilePath = "config.json";
final String invokerPackage = "com.foo.bar.invoker";
final String groupId = "com.foo.bar";
Map<String, String> configMap = new HashMap<String, String>();
configMap.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage);
configMap.put(CodegenConstants.GROUP_ID, groupId);
final Config config = new Config(configMap);
final String[] configArgs = {"-c", "--config"};
for (String configArg : configArgs) {
new StrictExpectations() {{
parser.read(configFilePath);
times = 1;
result = config;
}};
final CodegenConfig codegenConfig = setupAndRunGenericTest(configArg, configFilePath);
assertValueInMap(codegenConfig.additionalProperties(), CodegenConstants.INVOKER_PACKAGE, invokerPackage);
assertValueInMap(codegenConfig.additionalProperties(), CodegenConstants.GROUP_ID, groupId);
}
}
@Test
public void testSkipOverwrite() throws Exception {
CodegenConfig codegenConfig1 = setupAndRunGenericTest();
assertFalse(codegenConfig1.isSkipOverwrite());
CodegenConfig codegenConfig2 = setupAndRunGenericTest("-s");
assertTrue(codegenConfig2.isSkipOverwrite());
CodegenConfig codegenConfig3 = setupAndRunGenericTest("--skip-overwrite");
assertTrue(codegenConfig3.isSkipOverwrite());
}
@Test
public void testApiPackage() throws Exception {
doSingleAdditionalPropertyTest("--api-package", CodegenConstants.API_PACKAGE, "io.foo.bar.api");
}
@Test
public void testModelPackage() throws Exception {
doSingleAdditionalPropertyTest("--model-package", CodegenConstants.MODEL_PACKAGE, "io.foo.bar.models");
}
@Test
public void testInstantiationTypes() throws Exception {
final CodegenConfig codegenConfig = setupAndRunGenericTest("--instantiation-types", "foo=bar,hello=world");
assertValueInMap(codegenConfig.instantiationTypes(), "foo", "bar");
assertValueInMap(codegenConfig.instantiationTypes(), "hello", "world");
}
@Test
public void testTypeMappings() throws Exception {
final CodegenConfig codegenConfig = setupAndRunGenericTest("--type-mappings", "foo=bar,hello=world");
assertValueInMap(codegenConfig.typeMapping(), "foo", "bar");
assertValueInMap(codegenConfig.typeMapping(), "hello", "world");
}
@Test
public void testAdditionalProperties() throws Exception {
final CodegenConfig codegenConfig = setupAndRunGenericTest("--additional-properties", "foo=bar,hello=world");
assertValueInMap(codegenConfig.additionalProperties(), "foo", "bar");
assertValueInMap(codegenConfig.additionalProperties(), "hello", "world");
}
@Test
public void testLanguageSpecificPrimitives() throws Exception {
final CodegenConfig codegenConfig = setupAndRunGenericTest("--language-specific-primitives", "foo,bar,hello,world");
final Set<String> languageSpecificPrimitives = codegenConfig.languageSpecificPrimitives();
assertTrue(languageSpecificPrimitives.contains("foo"));
assertTrue(languageSpecificPrimitives.contains("bar"));
assertTrue(languageSpecificPrimitives.contains("hello"));
assertTrue(languageSpecificPrimitives.contains("world"));
}
@Test
public void testImportMappings() throws Exception {
final CodegenConfig codegenConfig = setupAndRunGenericTest("--import-mappings", "foo=bar,hello=world");
assertValueInMap(codegenConfig.importMapping(), "foo", "bar");
assertValueInMap(codegenConfig.importMapping(), "hello", "world");
}
@Test
public void testInvokerPackage() throws Exception {
doSingleAdditionalPropertyTest("--invoker-package", CodegenConstants.INVOKER_PACKAGE, "io.foo.bar.invoker");
}
@Test
public void testGroupId() throws Exception {
doSingleAdditionalPropertyTest("--group-id", CodegenConstants.GROUP_ID, "io.foo.bar");
}
@Test
public void testArtifactId() throws Exception {
doSingleAdditionalPropertyTest("--artifact-id", CodegenConstants.ARTIFACT_ID, "awesome-api");
}
@Test
public void testArtifactVersion() throws Exception {
doSingleAdditionalPropertyTest("--artifact-version", CodegenConstants.ARTIFACT_VERSION, "1.2.3");
}
private void doVerboseTest(String verboseFlag) {
new StrictExpectations(System.class) {{
System.setProperty("debugSwagger", "");
times = 1;
System.setProperty("debugModels", "");
times = 1;
System.setProperty("debugOperations", "");
times = 1;
System.setProperty("debugSupportingFiles", "");
times = 1;
}};
setupAndRunGenericTest(verboseFlag);
}
private void doRequiredArgsTest(String langFlag, String outputDirFlag, String inputSpecFlag) {
final String spec = "swagger.yaml";
final String lang = "java";
final String outputDir = "src/main/java";
final String[] args = {"generate", langFlag, lang, outputDirFlag, outputDir, inputSpecFlag, spec};
final CodegenConfig config = new JavaClientCodegen();
setupStandardExpectations(spec, lang, config);
SwaggerCodegen.main(args);
new FullVerifications() {{
}};
assertEquals(config.getOutputDir(), new File(outputDir).getAbsolutePath());
}
private void doSingleAdditionalPropertyTest(String cliArg, String additionalPropertyKey, String expectedValue) {
doSingleAdditionalPropertyTest(cliArg, additionalPropertyKey, expectedValue, expectedValue);
}
private void doSingleAdditionalPropertyTest(String cliArg, String additionalPropertyKey, String cliValue, String additionalPropertyValue) {
final CodegenConfig config = setupAndRunGenericTest(cliArg, cliValue);
assertValueInMap(config.additionalProperties(), additionalPropertyKey, additionalPropertyValue);
}
private CodegenConfig setupAndRunGenericTest(String... additionalParameters) {
final String spec = "swagger.yaml";
final String lang = "java";
final String[] commonArgs = {"generate", "-l", lang, "-o", "path/to/some/directory", "-i", spec};
String[] argsToUse = ArrayUtils.addAll(commonArgs, additionalParameters);
final CodegenConfig config = new JavaClientCodegen();
setupStandardExpectations(spec, lang, config);
SwaggerCodegen.main(argsToUse);
new FullVerifications() {{
}};
return config;
}
private void assertValueInMap(Map map, String propertyKey, String expectedPropertyValue) {
assertTrue(map.containsKey(propertyKey));
assertEquals(map.get(propertyKey), expectedPropertyValue);
}
private void setupStandardExpectations(final String spec, final String languageName, final CodegenConfig config) {
new Expectations() {{
CodegenConfigLoader.forName(languageName);
times = 1;
result = config;
new ClientOptInput();
times = 1;
result = clientOptInput;
clientOptInput.config(config);
times = 1;
result = clientOptInput;
new SwaggerParser();
times = 1;
result = parser;
clientOptInput.getAuthorizationValues();
times = 1;
result = authorizationValues;
parser.read(spec, authorizationValues, true);
times = 1;
result = swagger;
new DefaultGenerator();
times = 1;
result = defaultGenerator;
clientOptInput.opts((ClientOpts) any);
times = 1;
result = clientOptInput;
clientOptInput.swagger(swagger);
times = 1;
result = clientOptInput;
defaultGenerator.opts(clientOptInput);
times = 1;
result = defaultGenerator;
defaultGenerator.generate();
times = 1;
}};
}
}

View File

@ -0,0 +1,52 @@
package io.swagger.codegen.cmd.utils;
import org.apache.commons.lang3.tuple.Pair;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
public class OptionUtilsTest {
@Test
public void splitCommaSeparatedList() throws Exception {
doCommaSeparatedListTest("a,b,c", Arrays.asList("a", "b", "c"));
doCommaSeparatedListTest("a,,c", Arrays.asList("a", "c"));
doCommaSeparatedListTest("", new ArrayList<String>());
doCommaSeparatedListTest(null, new ArrayList<String>());
}
@Test
public void testParseCommaSeparatedTuples() throws Exception {
doTupleListTest("a=1,b=2,c=3", Arrays.asList(Pair.of("a", "1"), Pair.of("b", "2"), Pair.of("c", "3")));
doTupleListTest("a=1,,c=3", Arrays.asList(Pair.of("a", "1"), Pair.of("c", "3")));
doTupleListTest("a=1,xyz,c=3", Arrays.asList(Pair.of("a", "1"), Pair.of("c", "3")));
doTupleListTest("a=1,=,c=3", Arrays.asList(Pair.of("a", "1"), Pair.of("c", "3")));
doTupleListTest("", new ArrayList<Pair<String, String>>());
doTupleListTest(null, new ArrayList<Pair<String, String>>());
}
private void doTupleListTest(String input, List<Pair<String, String>> expectedResults) {
final List<Pair<String, String>> result = OptionUtils.parseCommaSeparatedTuples(input);
assertNotNull(result);
assertEquals(result.size(), expectedResults.size());
for (int i = 0; i < expectedResults.size(); i++) {
final Pair<String, String> actualPair = result.get(i);
final Pair<String, String> expected = expectedResults.get(i);
assertEquals(actualPair, expected);
}
}
private void doCommaSeparatedListTest(String csvStr, List<String> expectedResults) {
final List<String> result = OptionUtils.splitCommaSeparatedList(csvStr);
assertNotNull(result);
assertEquals(result.size(), expectedResults.size());
for (int i = 0; i < expectedResults.size(); i++) {
assertEquals(result.get(i), expectedResults.get(i));
}
}
}

View File

@ -20,6 +20,7 @@ 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.CodegenConfigLoader;
import io.swagger.codegen.DefaultGenerator; import io.swagger.codegen.DefaultGenerator;
import io.swagger.models.Swagger; import io.swagger.models.Swagger;
import io.swagger.parser.SwaggerParser; import io.swagger.parser.SwaggerParser;
@ -121,7 +122,7 @@ public class CodeGenMojo extends AbstractMojo {
public void execute() throws MojoExecutionException { public void execute() throws MojoExecutionException {
Swagger swagger = new SwaggerParser().read(inputSpec); Swagger swagger = new SwaggerParser().read(inputSpec);
CodegenConfig config = forName(language); CodegenConfig config = CodegenConfigLoader.forName(language);
config.setOutputDir(output.getAbsolutePath()); config.setOutputDir(output.getAbsolutePath());
if (null != templateDirectory) { if (null != templateDirectory) {
@ -167,20 +168,4 @@ public class CodeGenMojo extends AbstractMojo {
project.addCompileSourceRoot(output.toString()); project.addCompileSourceRoot(output.toString());
} }
} }
private CodegenConfig forName(String name) {
ServiceLoader<CodegenConfig> loader = ServiceLoader.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

@ -334,6 +334,18 @@
<version>${scala-version}</version> <version>${scala-version}</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>${testng-version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.reflections</groupId>
<artifactId>reflections</artifactId>
<version>${reflections-version}</version>
<scope>test</scope>
</dependency>
</dependencies> </dependencies>
<repositories> <repositories>
<repository> <repository>

View File

@ -10,7 +10,7 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
public class ClientOptInput { public class ClientOptInput {
protected CodegenConfig config; private CodegenConfig config;
private ClientOpts opts; private ClientOpts opts;
private Swagger swagger; private Swagger swagger;
private List<AuthorizationValue> auths; private List<AuthorizationValue> auths;
@ -25,6 +25,11 @@ public class ClientOptInput {
return this; return this;
} }
public ClientOptInput config(CodegenConfig codegenConfig) {
this.setConfig(codegenConfig);
return this;
}
public String getAuth() { public String getAuth() {
if (auths != null) { if (auths != null) {
StringBuilder b = new StringBuilder(); StringBuilder b = new StringBuilder();

View File

@ -85,7 +85,7 @@ public class Codegen extends DefaultGenerator {
swagger = new SwaggerParser().read(cmd.getOptionValue("i"), clientOptInput.getAuthorizationValues(), true); swagger = new SwaggerParser().read(cmd.getOptionValue("i"), clientOptInput.getAuthorizationValues(), true);
} }
if (cmd.hasOption("t")) { if (cmd.hasOption("t")) {
clientOpts.getProperties().put("templateDir", String.valueOf(cmd.getOptionValue("t"))); clientOpts.getProperties().put(CodegenConstants.TEMPLATE_DIR, String.valueOf(cmd.getOptionValue("t")));
} }
} catch (Exception e) { } catch (Exception e) {
usage(options); usage(options);

View File

@ -83,6 +83,8 @@ public interface CodegenConfig {
Map<String, String> modelTemplateFiles(); Map<String, String> modelTemplateFiles();
Set<String> languageSpecificPrimitives();
void processSwagger(Swagger swagger); void processSwagger(Swagger swagger);
String toApiFilename(String name); String toApiFilename(String name);

View File

@ -0,0 +1,34 @@
package io.swagger.codegen;
import java.util.ServiceLoader;
import static java.util.ServiceLoader.load;
public class CodegenConfigLoader {
/**
* 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
*/
public static CodegenConfig forName(String name) {
ServiceLoader<CodegenConfig> loader = load(CodegenConfig.class);
StringBuilder availableConfigs = new StringBuilder();
for (CodegenConfig config : loader) {
if (config.getName().equals(name)) {
return config;
}
availableConfigs.append(config.getName()).append("\n");
}
// 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) + " Available: " + availableConfigs.toString(), e);
}
}
}

View File

@ -0,0 +1,36 @@
package io.swagger.codegen;
/**
* A class for storing constants that are used throughout the project.
*/
public class CodegenConstants {
public static final String API_PACKAGE = "apiPackage";
public static final String API_PACKAGE_DESC = "package for generated api classes";
public static final String MODEL_PACKAGE = "modelPackage";
public static final String MODEL_PACKAGE_DESC = "package for generated models";
public static final String TEMPLATE_DIR = "templateDir";
public static final String INVOKER_PACKAGE = "invokerPackage";
public static final String INVOKER_PACKAGE_DESC = "root package for generated code";
public static final String GROUP_ID = "groupId";
public static final String GROUP_ID_DESC = "groupId in generated pom.xml";
public static final String ARTIFACT_ID = "artifactId";
public static final String ARTIFACT_ID_DESC = "artifactId in generated pom.xml";
public static final String ARTIFACT_VERSION = "artifactVersion";
public static final String ARTIFACT_VERSION_DESC = "artifact version in generated pom.xml";
public static final String SOURCE_FOLDER = "sourceFolder";
public static final String SOURCE_FOLDER_DESC = "source folder for generated code";
public static final String LOCAL_VARIABLE_PREFIX = "localVariablePrefix";
public static final String LOCAL_VARIABLE_PREFIX_DESC = "prefix for generated code members and local variables";
public static final String SERIALIZABLE_MODEL = "serializableModel";
public static final String SERIALIZABLE_MODEL_DESC = "boolean - toggle \"implements Serializable\" for generated models";
}

View File

@ -91,16 +91,16 @@ public class DefaultCodegen {
} }
public void processOpts() { public void processOpts() {
if (additionalProperties.containsKey("templateDir")) { if (additionalProperties.containsKey(CodegenConstants.TEMPLATE_DIR)) {
this.setTemplateDir((String) additionalProperties.get("templateDir")); this.setTemplateDir((String) additionalProperties.get(CodegenConstants.TEMPLATE_DIR));
} }
if (additionalProperties.containsKey("modelPackage")) { if (additionalProperties.containsKey(CodegenConstants.MODEL_PACKAGE)) {
this.setModelPackage((String) additionalProperties.get("modelPackage")); this.setModelPackage((String) additionalProperties.get(CodegenConstants.MODEL_PACKAGE));
} }
if (additionalProperties.containsKey("apiPackage")) { if (additionalProperties.containsKey(CodegenConstants.API_PACKAGE)) {
this.setApiPackage((String) additionalProperties.get("apiPackage")); this.setApiPackage((String) additionalProperties.get(CodegenConstants.API_PACKAGE));
} }
} }
@ -336,8 +336,8 @@ public class DefaultCodegen {
importMapping.put("LocalDate", "org.joda.time.*"); importMapping.put("LocalDate", "org.joda.time.*");
importMapping.put("LocalTime", "org.joda.time.*"); importMapping.put("LocalTime", "org.joda.time.*");
cliOptions.add(new CliOption("modelPackage", "package for generated models")); cliOptions.add(new CliOption(CodegenConstants.MODEL_PACKAGE, CodegenConstants.MODEL_PACKAGE_DESC));
cliOptions.add(new CliOption("apiPackage", "package for generated api classes")); cliOptions.add(new CliOption(CodegenConstants.API_PACKAGE, CodegenConstants.API_PACKAGE_DESC));
} }

View File

@ -4,6 +4,7 @@ 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.CodegenConfig; import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenConstants;
import io.swagger.codegen.CodegenOperation; import io.swagger.codegen.CodegenOperation;
import io.swagger.codegen.CodegenProperty; import io.swagger.codegen.CodegenProperty;
import io.swagger.codegen.CodegenResponse; import io.swagger.codegen.CodegenResponse;
@ -80,10 +81,10 @@ public class AkkaScalaClientCodegen extends DefaultCodegen implements CodegenCon
"trait", "try", "true", "type", "val", "var", "while", "with", "yield") "trait", "try", "true", "type", "val", "var", "while", "with", "yield")
); );
additionalProperties.put("invokerPackage", invokerPackage); additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage);
additionalProperties.put("groupId", groupId); additionalProperties.put(CodegenConstants.GROUP_ID, groupId);
additionalProperties.put("artifactId", artifactId); additionalProperties.put(CodegenConstants.ARTIFACT_ID, artifactId);
additionalProperties.put("artifactVersion", artifactVersion); additionalProperties.put(CodegenConstants.ARTIFACT_VERSION, artifactVersion);
additionalProperties.put("configKey", configKey); additionalProperties.put("configKey", configKey);
additionalProperties.put("configKeyPath", configKeyPath); additionalProperties.put("configKeyPath", configKeyPath);
additionalProperties.put("defaultTimeout", defaultTimeoutInMs); additionalProperties.put("defaultTimeout", defaultTimeoutInMs);

View File

@ -2,6 +2,7 @@ package io.swagger.codegen.languages;
import io.swagger.codegen.CliOption; import io.swagger.codegen.CliOption;
import io.swagger.codegen.CodegenConfig; import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenConstants;
import io.swagger.codegen.CodegenType; 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;
@ -58,11 +59,11 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi
instantiationTypes.put("array", "ArrayList"); instantiationTypes.put("array", "ArrayList");
instantiationTypes.put("map", "HashMap"); instantiationTypes.put("map", "HashMap");
cliOptions.add(new CliOption("invokerPackage", "root package to use for the generated code")); cliOptions.add(new CliOption(CodegenConstants.INVOKER_PACKAGE, CodegenConstants.INVOKER_PACKAGE_DESC));
cliOptions.add(new CliOption("groupId", "groupId for use in the generated build.gradle and pom.xml")); cliOptions.add(new CliOption(CodegenConstants.GROUP_ID, "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(CodegenConstants.ARTIFACT_ID, "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(CodegenConstants.ARTIFACT_VERSION, "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(CodegenConstants.SOURCE_FOLDER, CodegenConstants.SOURCE_FOLDER_DESC));
cliOptions.add(new CliOption("useAndroidMavenGradlePlugin", "A flag to toggle android-maven gradle plugin. Default is true.")); cliOptions.add(new CliOption("useAndroidMavenGradlePlugin", "A flag to toggle android-maven gradle plugin. Default is true."));
} }
@ -187,36 +188,36 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi
public void processOpts() { public void processOpts() {
super.processOpts(); super.processOpts();
if (additionalProperties.containsKey("invokerPackage")) { if (additionalProperties.containsKey(CodegenConstants.INVOKER_PACKAGE)) {
this.setInvokerPackage((String) additionalProperties.get("invokerPackage")); this.setInvokerPackage((String) additionalProperties.get(CodegenConstants.INVOKER_PACKAGE));
} else { } else {
//not set, use default to be passed to template //not set, use default to be passed to template
additionalProperties.put("invokerPackage", invokerPackage); additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage);
} }
if (additionalProperties.containsKey("groupId")) { if (additionalProperties.containsKey(CodegenConstants.GROUP_ID)) {
this.setGroupId((String) additionalProperties.get("groupId")); this.setGroupId((String) additionalProperties.get(CodegenConstants.GROUP_ID));
} else { } else {
//not set, use to be passed to template //not set, use to be passed to template
additionalProperties.put("groupId", groupId); additionalProperties.put(CodegenConstants.GROUP_ID, groupId);
} }
if (additionalProperties.containsKey("artifactId")) { if (additionalProperties.containsKey(CodegenConstants.ARTIFACT_ID)) {
this.setArtifactId((String) additionalProperties.get("artifactId")); this.setArtifactId((String) additionalProperties.get(CodegenConstants.ARTIFACT_ID));
} else { } else {
//not set, use to be passed to template //not set, use to be passed to template
additionalProperties.put("artifactId", artifactId); additionalProperties.put(CodegenConstants.ARTIFACT_ID, artifactId);
} }
if (additionalProperties.containsKey("artifactVersion")) { if (additionalProperties.containsKey(CodegenConstants.ARTIFACT_VERSION)) {
this.setArtifactVersion((String) additionalProperties.get("artifactVersion")); this.setArtifactVersion((String) additionalProperties.get(CodegenConstants.ARTIFACT_VERSION));
} else { } else {
//not set, use to be passed to template //not set, use to be passed to template
additionalProperties.put("artifactVersion", artifactVersion); additionalProperties.put(CodegenConstants.ARTIFACT_VERSION, artifactVersion);
} }
if (additionalProperties.containsKey("sourceFolder")) { if (additionalProperties.containsKey(CodegenConstants.SOURCE_FOLDER)) {
this.setSourceFolder((String) additionalProperties.get("sourceFolder")); this.setSourceFolder((String) additionalProperties.get(CodegenConstants.SOURCE_FOLDER));
} }
if (additionalProperties.containsKey("useAndroidMavenGradlePlugin")) { if (additionalProperties.containsKey("useAndroidMavenGradlePlugin")) {

View File

@ -1,6 +1,7 @@
package io.swagger.codegen.languages; package io.swagger.codegen.languages;
import io.swagger.codegen.CodegenConfig; import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenConstants;
import io.swagger.codegen.CodegenType; 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;
@ -52,10 +53,10 @@ public class AsyncScalaClientCodegen extends DefaultCodegen implements CodegenCo
"trait", "try", "true", "type", "val", "var", "while", "with", "yield") "trait", "try", "true", "type", "val", "var", "while", "with", "yield")
); );
additionalProperties.put("invokerPackage", invokerPackage); additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage);
additionalProperties.put("groupId", groupId); additionalProperties.put(CodegenConstants.GROUP_ID, groupId);
additionalProperties.put("artifactId", artifactId); additionalProperties.put(CodegenConstants.ARTIFACT_ID, artifactId);
additionalProperties.put("artifactVersion", artifactVersion); additionalProperties.put(CodegenConstants.ARTIFACT_VERSION, artifactVersion);
additionalProperties.put("asyncHttpClient", asyncHttpClient); additionalProperties.put("asyncHttpClient", asyncHttpClient);
additionalProperties.put("authScheme", authScheme); additionalProperties.put("authScheme", authScheme);
additionalProperties.put("authPreemptive", authPreemptive); additionalProperties.put("authPreemptive", authPreemptive);

View File

@ -2,34 +2,27 @@ package io.swagger.codegen.languages;
import io.swagger.codegen.CliOption; import io.swagger.codegen.CliOption;
import io.swagger.codegen.CodegenConfig; import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenConstants;
import io.swagger.codegen.CodegenType; 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 io.swagger.models.properties.ArrayProperty; import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
import io.swagger.models.properties.AbstractNumericProperty;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.BooleanProperty; import io.swagger.models.properties.BooleanProperty;
import io.swagger.models.properties.DateProperty; import io.swagger.models.properties.DateProperty;
import io.swagger.models.properties.DateTimeProperty; import io.swagger.models.properties.DateTimeProperty;
import io.swagger.models.properties.DecimalProperty;
import io.swagger.models.properties.DoubleProperty; import io.swagger.models.properties.DoubleProperty;
import io.swagger.models.properties.FloatProperty; import io.swagger.models.properties.FloatProperty;
import io.swagger.models.properties.IntegerProperty; import io.swagger.models.properties.IntegerProperty;
import io.swagger.models.properties.LongProperty; import io.swagger.models.properties.LongProperty;
import io.swagger.models.properties.MapProperty; import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property; import io.swagger.models.properties.Property;
import io.swagger.models.properties.PropertyBuilder;
import io.swagger.models.properties.RefProperty;
import io.swagger.models.properties.StringProperty; import io.swagger.models.properties.StringProperty;
import org.apache.commons.lang.StringUtils;
import java.io.File; import java.io.File;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashSet;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet;
import org.apache.commons.lang.StringUtils;
public class FlashClientCodegen extends DefaultCodegen implements CodegenConfig { public class FlashClientCodegen extends DefaultCodegen implements CodegenConfig {
protected String packageName = "io.swagger"; protected String packageName = "io.swagger";
@ -82,8 +75,8 @@ public class FlashClientCodegen extends DefaultCodegen implements CodegenConfig
cliOptions.clear(); cliOptions.clear();
cliOptions.add(new CliOption("packageName", "flash package name (convention: package.name), default: io.swagger")); cliOptions.add(new CliOption("packageName", "flash package name (convention: package.name), default: io.swagger"));
cliOptions.add(new CliOption("packageVersion", "flash package version, default: 1.0.0")); cliOptions.add(new CliOption("packageVersion", "flash package version, default: 1.0.0"));
cliOptions.add(new CliOption("invokerPackage", "root package for generated code")); cliOptions.add(new CliOption(CodegenConstants.INVOKER_PACKAGE, CodegenConstants.INVOKER_PACKAGE_DESC));
cliOptions.add(new CliOption("sourceFolder", "source folder for generated code. e.g. src/main/flex")); cliOptions.add(new CliOption(CodegenConstants.SOURCE_FOLDER, "source folder for generated code. e.g. src/main/flex"));
} }
@ -91,15 +84,15 @@ public class FlashClientCodegen extends DefaultCodegen implements CodegenConfig
public void processOpts() { public void processOpts() {
super.processOpts(); super.processOpts();
if (additionalProperties.containsKey("invokerPackage")) { if (additionalProperties.containsKey(CodegenConstants.INVOKER_PACKAGE)) {
this.setInvokerPackage((String) additionalProperties.get("invokerPackage")); this.setInvokerPackage((String) additionalProperties.get(CodegenConstants.INVOKER_PACKAGE));
} else { } else {
//not set, use default to be passed to template //not set, use default to be passed to template
additionalProperties.put("invokerPackage", invokerPackage); additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage);
} }
if (additionalProperties.containsKey("sourceFolder")) { if (additionalProperties.containsKey(CodegenConstants.SOURCE_FOLDER)) {
this.setSourceFolder((String) additionalProperties.get("sourceFolder")); this.setSourceFolder((String) additionalProperties.get(CodegenConstants.SOURCE_FOLDER));
} }
if (additionalProperties.containsKey("packageName")) { if (additionalProperties.containsKey("packageName")) {

View File

@ -3,19 +3,16 @@ package io.swagger.codegen.languages;
import com.google.common.base.Strings; import com.google.common.base.Strings;
import io.swagger.codegen.CliOption; import io.swagger.codegen.CliOption;
import io.swagger.codegen.CodegenConfig; import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenConstants;
import io.swagger.codegen.CodegenModel; import io.swagger.codegen.CodegenModel;
import io.swagger.codegen.CodegenProperty; import io.swagger.codegen.CodegenProperty;
import io.swagger.codegen.CodegenType; 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 io.swagger.models.ComposedModel;
import io.swagger.models.Model; import io.swagger.models.Model;
import io.swagger.models.ModelImpl;
import io.swagger.models.RefModel;
import io.swagger.models.properties.ArrayProperty; import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.MapProperty; import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property; import io.swagger.models.properties.Property;
import io.swagger.models.properties.StringProperty;
import java.io.File; import java.io.File;
import java.util.ArrayList; import java.util.ArrayList;
@ -76,14 +73,13 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
instantiationTypes.put("array", "ArrayList"); instantiationTypes.put("array", "ArrayList");
instantiationTypes.put("map", "HashMap"); instantiationTypes.put("map", "HashMap");
cliOptions.add(new CliOption("invokerPackage", "root package for generated code")); cliOptions.add(new CliOption(CodegenConstants.INVOKER_PACKAGE, CodegenConstants.INVOKER_PACKAGE_DESC));
cliOptions.add(new CliOption("groupId", "groupId in generated pom.xml")); cliOptions.add(new CliOption(CodegenConstants.GROUP_ID, CodegenConstants.GROUP_ID_DESC));
cliOptions.add(new CliOption("artifactId", "artifactId in generated pom.xml")); cliOptions.add(new CliOption(CodegenConstants.ARTIFACT_ID, CodegenConstants.ARTIFACT_ID_DESC));
cliOptions.add(new CliOption("artifactVersion", "artifact version in generated pom.xml")); cliOptions.add(new CliOption(CodegenConstants.ARTIFACT_VERSION, CodegenConstants.ARTIFACT_VERSION_DESC));
cliOptions.add(new CliOption("sourceFolder", "source folder for generated code")); cliOptions.add(new CliOption(CodegenConstants.SOURCE_FOLDER, CodegenConstants.SOURCE_FOLDER_DESC));
cliOptions.add(new CliOption("localVariablePrefix", "prefix for generated code members and local variables")); cliOptions.add(new CliOption(CodegenConstants.LOCAL_VARIABLE_PREFIX, CodegenConstants.LOCAL_VARIABLE_PREFIX_DESC));
cliOptions.add(new CliOption(CodegenConstants.SERIALIZABLE_MODEL, CodegenConstants.SERIALIZABLE_MODEL_DESC));
cliOptions.add(new CliOption("serializableModel", "boolean - toggle \"implements Serializable\" for generated models"));
supportedLibraries.put("<default>", "HTTP client: Jersey client 1.18. JSON processing: Jackson 2.4.2"); supportedLibraries.put("<default>", "HTTP client: Jersey client 1.18. JSON processing: Jackson 2.4.2");
supportedLibraries.put("jersey2", "HTTP client: Jersey client 2.6"); supportedLibraries.put("jersey2", "HTTP client: Jersey client 2.6");
@ -109,49 +105,49 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
public void processOpts() { public void processOpts() {
super.processOpts(); super.processOpts();
if (additionalProperties.containsKey("invokerPackage")) { if (additionalProperties.containsKey(CodegenConstants.INVOKER_PACKAGE)) {
this.setInvokerPackage((String) additionalProperties.get("invokerPackage")); this.setInvokerPackage((String) additionalProperties.get(CodegenConstants.INVOKER_PACKAGE));
} else { } else {
//not set, use default to be passed to template //not set, use default to be passed to template
additionalProperties.put("invokerPackage", invokerPackage); additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage);
} }
if (additionalProperties.containsKey("groupId")) { if (additionalProperties.containsKey(CodegenConstants.GROUP_ID)) {
this.setGroupId((String) additionalProperties.get("groupId")); this.setGroupId((String) additionalProperties.get(CodegenConstants.GROUP_ID));
} else { } else {
//not set, use to be passed to template //not set, use to be passed to template
additionalProperties.put("groupId", groupId); additionalProperties.put(CodegenConstants.GROUP_ID, groupId);
} }
if (additionalProperties.containsKey("artifactId")) { if (additionalProperties.containsKey(CodegenConstants.ARTIFACT_ID)) {
this.setArtifactId((String) additionalProperties.get("artifactId")); this.setArtifactId((String) additionalProperties.get(CodegenConstants.ARTIFACT_ID));
} else { } else {
//not set, use to be passed to template //not set, use to be passed to template
additionalProperties.put("artifactId", artifactId); additionalProperties.put(CodegenConstants.ARTIFACT_ID, artifactId);
} }
if (additionalProperties.containsKey("artifactVersion")) { if (additionalProperties.containsKey(CodegenConstants.ARTIFACT_VERSION)) {
this.setArtifactVersion((String) additionalProperties.get("artifactVersion")); this.setArtifactVersion((String) additionalProperties.get(CodegenConstants.ARTIFACT_VERSION));
} else { } else {
//not set, use to be passed to template //not set, use to be passed to template
additionalProperties.put("artifactVersion", artifactVersion); additionalProperties.put(CodegenConstants.ARTIFACT_VERSION, artifactVersion);
} }
if (additionalProperties.containsKey("sourceFolder")) { if (additionalProperties.containsKey(CodegenConstants.SOURCE_FOLDER)) {
this.setSourceFolder((String) additionalProperties.get("sourceFolder")); this.setSourceFolder((String) additionalProperties.get(CodegenConstants.SOURCE_FOLDER));
} }
if (additionalProperties.containsKey("localVariablePrefix")) { if (additionalProperties.containsKey(CodegenConstants.LOCAL_VARIABLE_PREFIX)) {
this.setLocalVariablePrefix((String) additionalProperties.get("localVariablePrefix")); this.setLocalVariablePrefix((String) additionalProperties.get(CodegenConstants.LOCAL_VARIABLE_PREFIX));
} }
if (additionalProperties.containsKey("serializableModel")) { if (additionalProperties.containsKey(CodegenConstants.SERIALIZABLE_MODEL)) {
this.setSerializableModel(Boolean.valueOf((String)additionalProperties.get("serializableModel").toString())); this.setSerializableModel(Boolean.valueOf((String)additionalProperties.get(CodegenConstants.SERIALIZABLE_MODEL).toString()));
} }
// need to put back serializableModel (boolean) into additionalProperties as value in additionalProperties is string // need to put back serializableModel (boolean) into additionalProperties as value in additionalProperties is string
additionalProperties.put("serializableModel", serializableModel); additionalProperties.put(CodegenConstants.SERIALIZABLE_MODEL, serializableModel);
this.sanitizeConfig(); this.sanitizeConfig();
@ -177,18 +173,18 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
// the whole additionalProperties object is injected into the main object passed to the mustache layer // the whole additionalProperties object is injected into the main object passed to the mustache layer
this.setApiPackage(sanitizePackageName(apiPackage)); this.setApiPackage(sanitizePackageName(apiPackage));
if (additionalProperties.containsKey("apiPackage")) { if (additionalProperties.containsKey(CodegenConstants.API_PACKAGE)) {
this.additionalProperties.put("apiPackage", apiPackage); this.additionalProperties.put(CodegenConstants.API_PACKAGE, apiPackage);
} }
this.setModelPackage(sanitizePackageName(modelPackage)); this.setModelPackage(sanitizePackageName(modelPackage));
if (additionalProperties.containsKey("modelPackage")) { if (additionalProperties.containsKey(CodegenConstants.MODEL_PACKAGE)) {
this.additionalProperties.put("modelPackage", modelPackage); this.additionalProperties.put(CodegenConstants.MODEL_PACKAGE, modelPackage);
} }
this.setInvokerPackage(sanitizePackageName(invokerPackage)); this.setInvokerPackage(sanitizePackageName(invokerPackage));
if (additionalProperties.containsKey("invokerPackage")) { if (additionalProperties.containsKey(CodegenConstants.INVOKER_PACKAGE)) {
this.additionalProperties.put("invokerPackage", invokerPackage); this.additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage);
} }
} }

View File

@ -1,6 +1,7 @@
package io.swagger.codegen.languages; package io.swagger.codegen.languages;
import io.swagger.codegen.CodegenConfig; import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenConstants;
import io.swagger.codegen.CodegenOperation; import io.swagger.codegen.CodegenOperation;
import io.swagger.codegen.CodegenType; import io.swagger.codegen.CodegenType;
import io.swagger.codegen.SupportingFile; import io.swagger.codegen.SupportingFile;
@ -38,10 +39,10 @@ public class JavaInflectorServerCodegen extends JavaClientCodegen implements Cod
apiPackage = System.getProperty("swagger.codegen.inflector.apipackage", "io.swagger.handler"); apiPackage = System.getProperty("swagger.codegen.inflector.apipackage", "io.swagger.handler");
modelPackage = System.getProperty("swagger.codegen.inflector.modelpackage", "io.swagger.model"); modelPackage = System.getProperty("swagger.codegen.inflector.modelpackage", "io.swagger.model");
additionalProperties.put("invokerPackage", invokerPackage); additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage);
additionalProperties.put("groupId", groupId); additionalProperties.put(CodegenConstants.GROUP_ID, groupId);
additionalProperties.put("artifactId", artifactId); additionalProperties.put(CodegenConstants.ARTIFACT_ID, artifactId);
additionalProperties.put("artifactVersion", artifactVersion); additionalProperties.put(CodegenConstants.ARTIFACT_VERSION, artifactVersion);
additionalProperties.put("title", title); additionalProperties.put("title", title);
languageSpecificPrimitives = new HashSet<String>( languageSpecificPrimitives = new HashSet<String>(

View File

@ -1,14 +1,12 @@
package io.swagger.codegen.languages; package io.swagger.codegen.languages;
import io.swagger.codegen.CodegenConfig; import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenResponse; import io.swagger.codegen.CodegenConstants;
import io.swagger.codegen.CodegenOperation; import io.swagger.codegen.CodegenOperation;
import io.swagger.codegen.CodegenResponse;
import io.swagger.codegen.CodegenType; import io.swagger.codegen.CodegenType;
import io.swagger.codegen.SupportingFile; import io.swagger.codegen.SupportingFile;
import io.swagger.models.Operation; import io.swagger.models.Operation;
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.ArrayList; import java.util.ArrayList;
@ -39,10 +37,10 @@ public class JaxRSServerCodegen extends JavaClientCodegen implements CodegenConf
apiPackage = System.getProperty("swagger.codegen.jaxrs.apipackage", "io.swagger.api"); apiPackage = System.getProperty("swagger.codegen.jaxrs.apipackage", "io.swagger.api");
modelPackage = System.getProperty("swagger.codegen.jaxrs.modelpackage", "io.swagger.model"); modelPackage = System.getProperty("swagger.codegen.jaxrs.modelpackage", "io.swagger.model");
additionalProperties.put("invokerPackage", invokerPackage); additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage);
additionalProperties.put("groupId", groupId); additionalProperties.put(CodegenConstants.GROUP_ID, groupId);
additionalProperties.put("artifactId", artifactId); additionalProperties.put(CodegenConstants.ARTIFACT_ID, artifactId);
additionalProperties.put("artifactVersion", artifactVersion); additionalProperties.put(CodegenConstants.ARTIFACT_VERSION, artifactVersion);
additionalProperties.put("title", title); additionalProperties.put("title", title);

View File

@ -2,6 +2,7 @@ package io.swagger.codegen.languages;
import io.swagger.codegen.CliOption; import io.swagger.codegen.CliOption;
import io.swagger.codegen.CodegenConfig; import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenConstants;
import io.swagger.codegen.CodegenType; 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;
@ -86,12 +87,12 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig {
typeMapping.put("DateTime", "\\DateTime"); typeMapping.put("DateTime", "\\DateTime");
cliOptions.add(new CliOption("variableNamingConvention", "naming convention of variable name, e.g. camelCase. Default: snake_case")); cliOptions.add(new CliOption("variableNamingConvention", "naming convention of variable name, e.g. camelCase. Default: snake_case"));
cliOptions.add(new CliOption("invokerPackage", "The main namespace to use for all classes. e.g. Yay\\Pets")); cliOptions.add(new CliOption(CodegenConstants.INVOKER_PACKAGE, "The main namespace to use for all classes. e.g. Yay\\Pets"));
cliOptions.add(new CliOption("packagePath", "The main package name for classes. e.g. GeneratedPetstore")); cliOptions.add(new CliOption("packagePath", "The main package name for classes. e.g. GeneratedPetstore"));
cliOptions.add(new CliOption("srcBasePath", "The directory under packagePath to serve as source root.")); cliOptions.add(new CliOption("srcBasePath", "The directory under packagePath to serve as source root."));
cliOptions.add(new CliOption("composerVendorName", "The vendor name used in the composer package name. The template uses {{composerVendorName}}/{{composerProjectName}} for the composer package name. e.g. yaypets")); cliOptions.add(new CliOption("composerVendorName", "The vendor name used in the composer package name. The template uses {{composerVendorName}}/{{composerProjectName}} for the composer package name. e.g. yaypets"));
cliOptions.add(new CliOption("composerProjectName", "The project name used in the composer package name. The template uses {{composerVendorName}}/{{composerProjectName}} for the composer package name. e.g. petstore-client")); cliOptions.add(new CliOption("composerProjectName", "The project name used in the composer package name. The template uses {{composerVendorName}}/{{composerProjectName}} for the composer package name. e.g. petstore-client"));
cliOptions.add(new CliOption("artifactVersion", "The version to use in the composer package version field. e.g. 1.2.3")); cliOptions.add(new CliOption(CodegenConstants.ARTIFACT_VERSION, "The version to use in the composer package version field. e.g. 1.2.3"));
} }
public String getPackagePath() { public String getPackagePath() {
@ -155,22 +156,22 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig {
additionalProperties.put("srcBasePath", srcBasePath); additionalProperties.put("srcBasePath", srcBasePath);
} }
if (additionalProperties.containsKey("invokerPackage")) { if (additionalProperties.containsKey(CodegenConstants.INVOKER_PACKAGE)) {
this.setInvokerPackage((String) additionalProperties.get("invokerPackage")); this.setInvokerPackage((String) additionalProperties.get(CodegenConstants.INVOKER_PACKAGE));
} else { } else {
additionalProperties.put("invokerPackage", invokerPackage); additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage);
} }
if (additionalProperties.containsKey("modelPackage")) { if (additionalProperties.containsKey(CodegenConstants.MODEL_PACKAGE)) {
this.setModelPackage((String) additionalProperties.get("modelPackage")); this.setModelPackage((String) additionalProperties.get(CodegenConstants.MODEL_PACKAGE));
} else { } else {
additionalProperties.put("modelPackage", modelPackage); additionalProperties.put(CodegenConstants.MODEL_PACKAGE, modelPackage);
} }
if (additionalProperties.containsKey("apiPackage")) { if (additionalProperties.containsKey(CodegenConstants.API_PACKAGE)) {
this.setApiPackage((String) additionalProperties.get("apiPackage")); this.setApiPackage((String) additionalProperties.get(CodegenConstants.API_PACKAGE));
} else { } else {
additionalProperties.put("apiPackage", apiPackage); additionalProperties.put(CodegenConstants.API_PACKAGE, apiPackage);
} }
if (additionalProperties.containsKey("composerProjectName")) { if (additionalProperties.containsKey("composerProjectName")) {
@ -185,10 +186,10 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig {
additionalProperties.put("composerVendorName", composerVendorName); additionalProperties.put("composerVendorName", composerVendorName);
} }
if (additionalProperties.containsKey("artifactVersion")) { if (additionalProperties.containsKey(CodegenConstants.ARTIFACT_VERSION)) {
this.setArtifactVersion((String) additionalProperties.get("artifactVersion")); this.setArtifactVersion((String) additionalProperties.get(CodegenConstants.ARTIFACT_VERSION));
} else { } else {
additionalProperties.put("artifactVersion", artifactVersion); additionalProperties.put(CodegenConstants.ARTIFACT_VERSION, artifactVersion);
} }
additionalProperties.put("escapedInvokerPackage", invokerPackage.replace("\\", "\\\\")); additionalProperties.put("escapedInvokerPackage", invokerPackage.replace("\\", "\\\\"));

View File

@ -1,6 +1,7 @@
package io.swagger.codegen.languages; package io.swagger.codegen.languages;
import io.swagger.codegen.CodegenConfig; import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenConstants;
import io.swagger.codegen.CodegenOperation; import io.swagger.codegen.CodegenOperation;
import io.swagger.codegen.CodegenType; import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen; import io.swagger.codegen.DefaultCodegen;
@ -44,10 +45,10 @@ public class RetrofitClientCodegen extends DefaultCodegen implements CodegenConf
"native", "super", "while") "native", "super", "while")
); );
additionalProperties.put("invokerPackage", invokerPackage); additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage);
additionalProperties.put("groupId", groupId); additionalProperties.put(CodegenConstants.GROUP_ID, groupId);
additionalProperties.put("artifactId", artifactId); additionalProperties.put(CodegenConstants.ARTIFACT_ID, artifactId);
additionalProperties.put("artifactVersion", artifactVersion); additionalProperties.put(CodegenConstants.ARTIFACT_VERSION, artifactVersion);
supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml")); supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml"));
supportingFiles.add(new SupportingFile("service.mustache", supportingFiles.add(new SupportingFile("service.mustache",

View File

@ -1,6 +1,7 @@
package io.swagger.codegen.languages; package io.swagger.codegen.languages;
import io.swagger.codegen.CodegenConfig; import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenConstants;
import io.swagger.codegen.CodegenType; 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;
@ -54,10 +55,10 @@ public class ScalaClientCodegen extends DefaultCodegen implements CodegenConfig
"trait", "try", "true", "type", "val", "var", "while", "with", "yield") "trait", "try", "true", "type", "val", "var", "while", "with", "yield")
); );
additionalProperties.put("invokerPackage", invokerPackage); additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage);
additionalProperties.put("groupId", groupId); additionalProperties.put(CodegenConstants.GROUP_ID, groupId);
additionalProperties.put("artifactId", artifactId); additionalProperties.put(CodegenConstants.ARTIFACT_ID, artifactId);
additionalProperties.put("artifactVersion", artifactVersion); additionalProperties.put(CodegenConstants.ARTIFACT_VERSION, artifactVersion);
additionalProperties.put("asyncHttpClient", asyncHttpClient); additionalProperties.put("asyncHttpClient", asyncHttpClient);
additionalProperties.put("authScheme", authScheme); additionalProperties.put("authScheme", authScheme);
additionalProperties.put("authPreemptive", authPreemptive); additionalProperties.put("authPreemptive", authPreemptive);

View File

@ -1,6 +1,7 @@
package io.swagger.codegen.languages; package io.swagger.codegen.languages;
import io.swagger.codegen.CodegenConfig; import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenConstants;
import io.swagger.codegen.CodegenOperation; import io.swagger.codegen.CodegenOperation;
import io.swagger.codegen.CodegenType; import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen; import io.swagger.codegen.DefaultCodegen;
@ -73,10 +74,10 @@ public class ScalatraServerCodegen extends DefaultCodegen implements CodegenConf
additionalProperties.put("infoEmail", "apiteam@swagger.io"); additionalProperties.put("infoEmail", "apiteam@swagger.io");
additionalProperties.put("licenseInfo", "All rights reserved"); additionalProperties.put("licenseInfo", "All rights reserved");
additionalProperties.put("licenseUrl", "http://apache.org/licenses/LICENSE-2.0.html"); additionalProperties.put("licenseUrl", "http://apache.org/licenses/LICENSE-2.0.html");
additionalProperties.put("invokerPackage", invokerPackage); additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage);
additionalProperties.put("groupId", groupId); additionalProperties.put(CodegenConstants.GROUP_ID, groupId);
additionalProperties.put("artifactId", artifactId); additionalProperties.put(CodegenConstants.ARTIFACT_ID, artifactId);
additionalProperties.put("artifactVersion", artifactVersion); additionalProperties.put(CodegenConstants.ARTIFACT_VERSION, artifactVersion);
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
supportingFiles.add(new SupportingFile("build.sbt", "", "build.sbt")); supportingFiles.add(new SupportingFile("build.sbt", "", "build.sbt"));

View File

@ -1,6 +1,7 @@
package io.swagger.codegen.languages; package io.swagger.codegen.languages;
import io.swagger.codegen.CodegenConfig; import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenConstants;
import io.swagger.codegen.CodegenType; 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;
@ -41,10 +42,10 @@ public class SilexServerCodegen extends DefaultCodegen implements CodegenConfig
"__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") "__halt_compiler", "abstract", "and", "array", "as", "break", "callable", "case", "catch", "class", "clone", "const", "continue", "declare", "default", "die", "do", "echo", "else", "elseif", "empty", "enddeclare", "endfor", "endforeach", "endif", "endswitch", "endwhile", "eval", "exit", "extends", "final", "for", "foreach", "function", "global", "goto", "if", "implements", "include", "include_once", "instanceof", "insteadof", "interface", "isset", "list", "namespace", "new", "or", "print", "private", "protected", "public", "require", "require_once", "return", "static", "switch", "throw", "trait", "try", "unset", "use", "var", "while", "xor")
); );
additionalProperties.put("invokerPackage", invokerPackage); additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage);
additionalProperties.put("groupId", groupId); additionalProperties.put(CodegenConstants.GROUP_ID, groupId);
additionalProperties.put("artifactId", artifactId); additionalProperties.put(CodegenConstants.ARTIFACT_ID, artifactId);
additionalProperties.put("artifactVersion", artifactVersion); additionalProperties.put(CodegenConstants.ARTIFACT_VERSION, artifactVersion);
// ref: http://php.net/manual/en/language.types.intro.php // ref: http://php.net/manual/en/language.types.intro.php
languageSpecificPrimitives = new HashSet<String>( languageSpecificPrimitives = new HashSet<String>(

View File

@ -34,12 +34,12 @@ public class SpringMVCServerCodegen extends JavaClientCodegen implements Codegen
configPackage = "io.swagger.configuration"; configPackage = "io.swagger.configuration";
additionalProperties.put("invokerPackage", invokerPackage); additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage);
additionalProperties.put("groupId", groupId); additionalProperties.put(CodegenConstants.GROUP_ID, groupId);
additionalProperties.put("artifactId", artifactId); additionalProperties.put(CodegenConstants.ARTIFACT_ID, artifactId);
additionalProperties.put("artifactVersion", artifactVersion); additionalProperties.put(CodegenConstants.ARTIFACT_VERSION, artifactVersion);
additionalProperties.put("title", title); additionalProperties.put("title", title);
additionalProperties.put("apiPackage", apiPackage); additionalProperties.put(CodegenConstants.API_PACKAGE, apiPackage);
additionalProperties.put("configPackage", configPackage); additionalProperties.put("configPackage", configPackage);
languageSpecificPrimitives = new HashSet<String>( languageSpecificPrimitives = new HashSet<String>(

View File

@ -1,6 +1,7 @@
package io.swagger.codegen.languages; package io.swagger.codegen.languages;
import io.swagger.codegen.CodegenConfig; import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenConstants;
import io.swagger.codegen.CodegenType; 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;
@ -21,10 +22,10 @@ public class StaticDocCodegen extends DefaultCodegen implements CodegenConfig {
apiTemplateFiles.put("operation.mustache", ".html"); apiTemplateFiles.put("operation.mustache", ".html");
templateDir = "swagger-static"; templateDir = "swagger-static";
additionalProperties.put("invokerPackage", invokerPackage); additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage);
additionalProperties.put("groupId", groupId); additionalProperties.put(CodegenConstants.GROUP_ID, groupId);
additionalProperties.put("artifactId", artifactId); additionalProperties.put(CodegenConstants.ARTIFACT_ID, artifactId);
additionalProperties.put("artifactVersion", artifactVersion); additionalProperties.put(CodegenConstants.ARTIFACT_VERSION, artifactVersion);
supportingFiles.add(new SupportingFile("package.mustache", "", "package.json")); supportingFiles.add(new SupportingFile("package.mustache", "", "package.json"));
supportingFiles.add(new SupportingFile("main.mustache", "", "main.js")); supportingFiles.add(new SupportingFile("main.mustache", "", "main.js"));

View File

@ -1,6 +1,7 @@
package io.swagger.codegen.languages; package io.swagger.codegen.languages;
import io.swagger.codegen.CodegenConfig; import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenConstants;
import io.swagger.codegen.CodegenOperation; import io.swagger.codegen.CodegenOperation;
import io.swagger.codegen.CodegenType; import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen; import io.swagger.codegen.DefaultCodegen;
@ -37,10 +38,10 @@ public class StaticHtmlGenerator extends DefaultCodegen implements CodegenConfig
additionalProperties.put("infoEmail", "hello@helloreverb.com"); additionalProperties.put("infoEmail", "hello@helloreverb.com");
additionalProperties.put("licenseInfo", "All rights reserved"); additionalProperties.put("licenseInfo", "All rights reserved");
additionalProperties.put("licenseUrl", "http://apache.org/licenses/LICENSE-2.0.html"); additionalProperties.put("licenseUrl", "http://apache.org/licenses/LICENSE-2.0.html");
additionalProperties.put("invokerPackage", invokerPackage); additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage);
additionalProperties.put("groupId", groupId); additionalProperties.put(CodegenConstants.GROUP_ID, groupId);
additionalProperties.put("artifactId", artifactId); additionalProperties.put(CodegenConstants.ARTIFACT_ID, artifactId);
additionalProperties.put("artifactVersion", artifactVersion); additionalProperties.put(CodegenConstants.ARTIFACT_VERSION, artifactVersion);
supportingFiles.add(new SupportingFile("index.mustache", "", "index.html")); supportingFiles.add(new SupportingFile("index.mustache", "", "index.html"));
reservedWords = new HashSet<String>(); reservedWords = new HashSet<String>();

View File

@ -0,0 +1,57 @@
package io.swagger.codegen;
import org.reflections.Reflections;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import static org.testng.Assert.assertEquals;
public class CodegenConfigLoaderTest {
@DataProvider(name = "codegenConfig")
public Object[][] createCodegenConfigDataSet() throws Exception {
Reflections reflections = new Reflections("io.swagger.codegen.languages");
final Set<Class<? extends DefaultCodegen>> subTypesOf = reflections.getSubTypesOf(DefaultCodegen.class);
List<CodegenConfig> codegenConfigList = new ArrayList<CodegenConfig>();
for (Class<? extends DefaultCodegen> aClass : subTypesOf) {
if (!Modifier.isAbstract(aClass.getModifiers())) {
final DefaultCodegen defaultCodegen = aClass.newInstance();
codegenConfigList.add((CodegenConfig) defaultCodegen);
}
}
Object[][] result = new Object[codegenConfigList.size()][1];
for (int i = 0; i < codegenConfigList.size(); i++) {
result[i]= new Object[]{codegenConfigList.get(i)};
}
return result;
}
@Test(dataProvider = "codegenConfig")
public void testLoadByName(CodegenConfig codegenConfig) throws Exception {
final CodegenConfig loadedConfig = CodegenConfigLoader.forName(codegenConfig.getName());
assertEquals(loadedConfig.getClass(), codegenConfig.getClass());
assertEquals(loadedConfig.getName(), codegenConfig.getName());
}
@Test(dataProvider = "codegenConfig")
public void testLoadByFullQualifiedName(CodegenConfig codegenConfig) throws Exception {
final CodegenConfig loadedConfig = CodegenConfigLoader.forName(codegenConfig.getClass().getName());
assertEquals(loadedConfig.getClass(), codegenConfig.getClass());
assertEquals(loadedConfig.getName(), codegenConfig.getName());
}
}

View File

@ -1,15 +1,13 @@
package io.swagger.codegen; package io.swagger.codegen;
import static org.junit.Assert.assertEquals; import io.swagger.codegen.languages.JavaClientCodegen;
import static org.junit.Assert.assertTrue; import io.swagger.models.Swagger;
import io.swagger.parser.SwaggerParser;
import org.apache.commons.io.FileUtils; import org.apache.commons.io.FileUtils;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder; import org.junit.rules.TemporaryFolder;
import org.testng.annotations.AfterMethod;
import static java.nio.charset.StandardCharsets.UTF_8; import org.testng.annotations.BeforeMethod;
import static org.junit.Assert.fail; import org.testng.annotations.Test;
import java.io.BufferedWriter; import java.io.BufferedWriter;
import java.io.File; import java.io.File;
@ -20,34 +18,53 @@ import java.io.Writer;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.Arrays; import java.util.Arrays;
public class GenerateTest { import static java.nio.charset.StandardCharsets.UTF_8;
import static org.junit.Assert.fail;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
/**
* Tests for DefaultGenerator logic
*/
public class DefaultGeneratorTest {
private static final String TEST_SKIP_OVERWRITE = "testSkipOverwrite"; private static final String TEST_SKIP_OVERWRITE = "testSkipOverwrite";
private static final String POM_FILE = "pom.xml"; private static final String POM_FILE = "pom.xml";
private static final String MODEL_ORDER_FILE = "/src/main/java/io/swagger/client/model/Order.java"; private static final String MODEL_ORDER_FILE = "/src/main/java/io/swagger/client/model/Order.java";
@Rule
public TemporaryFolder folder = new TemporaryFolder(); public TemporaryFolder folder = new TemporaryFolder();
@BeforeMethod
public void setUp() throws Exception {
folder.create();
}
@AfterMethod
public void tearDown() throws Exception {
folder.delete();
}
@Test @Test
public void testSkipOverwrite() throws IOException { public void testSkipOverwrite() throws Exception {
final File output = folder.getRoot(); final File output = folder.getRoot();
String[] args = {"generate", "-i", "src/test/resources/petstore.json", "-l", "java", "-o", output.getAbsolutePath()}; final Swagger swagger = new SwaggerParser().read("src/test/resources/petstore.json");
String[] argsWithSparam = Arrays.copyOf(args, args.length + 1); CodegenConfig codegenConfig = new JavaClientCodegen();
argsWithSparam[args.length] = "-s"; codegenConfig.setOutputDir(output.getAbsolutePath());
//generate content first time without -s flag, so all generated files should be recorded ClientOptInput clientOptInput = new ClientOptInput().opts(new ClientOpts()).swagger(swagger).config(codegenConfig);
SwaggerCodegen.main(args);
//generate content first time without skipOverwrite flag, so all generated files should be recorded
new DefaultGenerator().opts(clientOptInput).generate();
final File order = new File(output, MODEL_ORDER_FILE); final File order = new File(output, MODEL_ORDER_FILE);
assertTrue(order.exists()); assertTrue(order.exists());
//change content of one file //change content of one file
changeContent(order); changeContent(order);
//generate content second time without -s flag, so changed file should be rewritten //generate content second time without skipOverwrite flag, so changed file should be rewritten
SwaggerCodegen.main(args); new DefaultGenerator().opts(clientOptInput).generate();
//order = new File(output, MODEL_ORDER_FILE);
assertTrue(!TEST_SKIP_OVERWRITE.equals(FileUtils.readFileToString(order, StandardCharsets.UTF_8))); assertTrue(!TEST_SKIP_OVERWRITE.equals(FileUtils.readFileToString(order, StandardCharsets.UTF_8)));
//change content again //change content again
@ -58,9 +75,10 @@ public class GenerateTest {
fail(); fail();
} }
//generate content third time with -s flag, so changed file should not be rewritten //generate content third time with skipOverwrite flag, so changed file should not be rewritten
//and deleted file should be recorded //and deleted file should be recorded
SwaggerCodegen.main(argsWithSparam); codegenConfig.setSkipOverwrite(true);
new DefaultGenerator().opts(clientOptInput).generate();
assertEquals(FileUtils.readFileToString(order, StandardCharsets.UTF_8), TEST_SKIP_OVERWRITE); assertEquals(FileUtils.readFileToString(order, StandardCharsets.UTF_8), TEST_SKIP_OVERWRITE);
assertTrue(pom.exists()); assertTrue(pom.exists());
} }
@ -70,4 +88,5 @@ public class GenerateTest {
out.write(TEST_SKIP_OVERWRITE); out.write(TEST_SKIP_OVERWRITE);
out.close(); out.close();
} }
} }

37
pom.xml
View File

@ -68,6 +68,27 @@
<directory>target</directory> <directory>target</directory>
<finalName>${project.artifactId}-${project.version}</finalName> <finalName>${project.artifactId}-${project.version}</finalName>
<plugins> <plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${surefire-version}</version>
<configuration>
<testNGArtifactName>none:none</testNGArtifactName>
</configuration>
<executions>
<execution>
<id>test-testng</id>
<phase>test</phase>
<goals>
<goal>test</goal>
</goals>
<configuration>
<junitArtifactName>none:none</junitArtifactName>
<testNGArtifactName>org.testng:testng</testNGArtifactName>
</configuration>
</execution>
</executions>
</plugin>
<plugin> <plugin>
<artifactId>maven-dependency-plugin</artifactId> <artifactId>maven-dependency-plugin</artifactId>
<executions> <executions>
@ -457,6 +478,18 @@
<version>${junit-version}</version> <version>${junit-version}</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>${testng-version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jmockit</groupId>
<artifactId>jmockit</artifactId>
<version>${jmockit-version}</version>
<scope>test</scope>
</dependency>
</dependencies> </dependencies>
</dependencyManagement> </dependencyManagement>
<repositories> <repositories>
@ -482,5 +515,9 @@
<slf4j-version>1.6.3</slf4j-version> <slf4j-version>1.6.3</slf4j-version>
<scala-maven-plugin-version>3.2.1</scala-maven-plugin-version> <scala-maven-plugin-version>3.2.1</scala-maven-plugin-version>
<jmustache-version>1.9</jmustache-version> <jmustache-version>1.9</jmustache-version>
<testng-version>6.9.6</testng-version>
<surefire-version>2.18.1</surefire-version>
<jmockit-version>1.18</jmockit-version>
<reflections-version>0.9.10</reflections-version>
</properties> </properties>
</project> </project>