Merge branch 'master' into ruby-binary

This commit is contained in:
xhh
2016-01-25 12:48:25 +08:00
195 changed files with 3487 additions and 1121 deletions

View File

@@ -2,7 +2,7 @@
## Before submitting an issue
- Before submitting an issue, search the [open issue](https://github.com/swagger-api/swagger-codegen/issues) and [closed issue](https://github.com/swagger-api/swagger-codegen/issues?q=is%3Aissue+is%3Aclosed) to ensure no one else has reported something similar before.
- Search the [open issue](https://github.com/swagger-api/swagger-codegen/issues) and [closed issue](https://github.com/swagger-api/swagger-codegen/issues?q=is%3Aissue+is%3Aclosed) to ensure no one else has reported something similar before.
- The issue should contain details on how to repeat the issue, e.g.
- the OpenAPI Spec for reproducing the issue (:bulb: use [Gist](https://gist.github.com) to share). If the OpenAPI Spec cannot be shared publicly, it will be hard for the community to help
- version of Swagger Codegen
@@ -31,7 +31,7 @@ For a list of variables available in the template, please refer to this [page](h
Code change should conform to the programming style guide of the respective langauages:
- C#: https://msdn.microsoft.com/en-us/library/vstudio/ff926074.aspx
- Java: https://google.github.io/styleguide/javaguide.html
- JavaScript - https://github.com/airbnb/javascript
- JavaScript - https://github.com/airbnb/javascript/tree/master/es5
- ObjC: https://github.com/NYTimes/objective-c-style-guide
- PHP: https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md
- Python: https://www.python.org/dev/peps/pep-0008/

View File

@@ -1,12 +1,13 @@
# Swagger Code Generator
[![Build Status](https://travis-ci.org/swagger-api/swagger-codegen.png)](https://travis-ci.org/swagger-api/swagger-codegen)
[![Build Status](https://travis-ci.org/swagger-api/swagger-codegen.svg)](https://travis-ci.org/swagger-api/swagger-codegen)
[![Maven Central](https://maven-badges.herokuapp.com/maven-central/io.swagger/swagger-codegen-project/badge.svg?style=plastic)](https://maven-badges.herokuapp.com/maven-central/io.swagger/swagger-codegen-project)
[![PR Stats](http://issuestats.com/github/swagger-api/swagger-codegen/badge/pr)](http://issuestats.com/github/swagger-api/swagger-codegen) [![Issue Stats](http://issuestats.com/github/swagger-api/swagger-codegen/badge/issue)](http://issuestats.com/github/swagger-api/swagger-codegen)
:star::star::star: If you would like to contribute, please refer to [guidelines](https://github.com/swagger-api/swagger-codegen/blob/master/CONTRIBUTING.md) and a list of [open tasks](https://github.com/swagger-api/swagger-codegen/issues?q=is%3Aopen+is%3Aissue+label%3A%22Need+community+contribution%22).:star::star::star:
## Overview
This is the swagger codegen project, which allows generation of client libraries automatically from a Swagger-compliant server.
This is the swagger codegen project, which allows generation of client libraries automatically from a Swagger-compliant server.
Check out [Swagger-Spec](https://github.com/OAI/OpenAPI-Specification) for additional information about the Swagger project, including additional libraries with support for other languages and more.
@@ -351,7 +352,7 @@ java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \
-o samples/client/petstore/java \
-c path/to/config.json
```
Supported config options can be different per language. Running `config-help -l {lang}` will show available options. **These options are applied
Supported config options can be different per language. Running `config-help -l {lang}` will show available options. **These options are applied
by passing them with `-D{optionName}={optionValue}**.
```
@@ -402,9 +403,9 @@ CONFIG OPTIONS
retrofit2 - HTTP client: OkHttp 2.5.0. JSON processing: Gson 2.4 (Retrofit 2.0.0-beta2)
```
Your config file for java can look like
Your config file for Java can look like
```
```json
{
"groupId":"com.my.company",
"artifactId":"MyClent",
@@ -418,15 +419,15 @@ For all the unspecified options default values will be used.
Another way to override default options is to extend the config class for the specific language.
To change, for example, the prefix for the Objective-C generated files, simply subclass the ObjcClientCodegen.java:
```
```java
package com.mycompany.swagger.codegen;
import io.swagger.codegen.languages.*;
public class MyObjcCodegen extends ObjcClientCodegen {
static {
PREFIX = "HELO";
}
static {
PREFIX = "HELO";
}
}
```
@@ -512,7 +513,7 @@ java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \
```
java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \
-i http://petstore.swagger.io/v2/swagger.json \
-l flaskConnexion \
-l python-flask \
-o samples/server/petstore/flaskConnexion
```
@@ -553,7 +554,7 @@ java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \
### To build the codegen library
This will create the swagger-codegen library from source.
This will create the swagger-codegen library from source.
```
mvn package

31
bin/go-petstore.sh Normal file
View File

@@ -0,0 +1,31 @@
#!/bin/sh
SCRIPT="$0"
while [ -h "$SCRIPT" ] ; do
ls=`ls -ld "$SCRIPT"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
SCRIPT="$link"
else
SCRIPT=`dirname "$SCRIPT"`/"$link"
fi
done
if [ ! -d "${APP_DIR}" ]; then
APP_DIR=`dirname "$SCRIPT"`/..
APP_DIR=`cd "${APP_DIR}"; pwd`
fi
executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar"
if [ ! -f "$executable" ]
then
mvn clean package
fi
# if you've executed sbt assembly previously it will use that instead.
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="$@ generate -t modules/swagger-codegen/src/main/resources/go -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l go -o samples/client/petstore/go"
java $JAVA_OPTS -jar $executable $ags

View File

@@ -0,0 +1,10 @@
set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar
If Not Exist %executable% (
mvn clean package
)
set JAVA_OPTS=%JAVA_OPTS% -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties
set ags=generate -t modules\swagger-codegen\src\main\resources\go -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l go -o samples\client\petstore\go
java %JAVA_OPTS% -jar %executable% %ags%

View File

@@ -89,13 +89,13 @@
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>${testng-version}</version>
<!-- <version>${testng-version}</version> -->
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jmockit</groupId>
<artifactId>jmockit</artifactId>
<version>${jmockit-version}</version>
<!-- <version>${jmockit-version}</version> -->
<scope>test</scope>
</dependency>
</dependencies>

View File

@@ -21,6 +21,7 @@ public class SwaggerCodegen {
public static void main(String[] args) {
@SuppressWarnings("unchecked")
Cli.CliBuilder<Runnable> builder = Cli.<Runnable>builder("swagger-codegen-cli")
.withDescription("Swagger code generator CLI. More info on swagger.io")
.withDefaultCommand(Langs.class)

View File

@@ -230,15 +230,15 @@ public class Generate implements Runnable {
}
}
private Set<String> createSetFromCsvList(String csvProperty) {
private static Set<String> createSetFromCsvList(String csvProperty) {
final List<String> values = OptionUtils.splitCommaSeparatedList(csvProperty);
return new HashSet<String>(values);
}
private Map createMapFromKeyValuePairs(String commaSeparatedKVPairs) {
private static Map<String, String> createMapFromKeyValuePairs(String commaSeparatedKVPairs) {
final List<Pair<String, String>> pairs = OptionUtils.parseCommaSeparatedTuples(commaSeparatedKVPairs);
Map result = new HashMap();
Map<String, String> result = new HashMap<String, String>();
for (Pair<String, String> pair : pairs) {
result.put(pair.getLeft(), pair.getRight());

View File

@@ -93,7 +93,7 @@ public class Meta implements Runnable {
* @param data - map with additional params needed to process templates
* @return converter object to pass to lambdaj
*/
private Converter<SupportingFile, File> processFiles(final File targetDir, final Map<String, Object> data) {
private static Converter<SupportingFile, File> processFiles(final File targetDir, final Map<String, Object> data) {
return new Converter<SupportingFile, File>() {
private DefaultGenerator generator = new DefaultGenerator();
@@ -133,7 +133,7 @@ public class Meta implements Runnable {
* @param generator - class with reader getter
* @return loader for template
*/
private Mustache.TemplateLoader loader(final DefaultGenerator generator) {
private static Mustache.TemplateLoader loader(final DefaultGenerator generator) {
return new Mustache.TemplateLoader() {
@Override
public Reader getTemplate(String name) {
@@ -149,7 +149,7 @@ public class Meta implements Runnable {
* @param packageName - package name to convert
* @return relative path
*/
private String asPath(String packageName) {
private static String asPath(String packageName) {
return packageName.replace(".", File.separator);
}
}

View File

@@ -12,6 +12,7 @@ import mockit.Verifications;
import org.apache.commons.lang3.ArrayUtils;
import org.testng.annotations.Test;
@SuppressWarnings("unused")
public class GenerateTest {
@Mocked

View File

@@ -10,6 +10,7 @@ import java.util.List;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
@SuppressWarnings("static-method")
public class OptionUtilsTest {
@Test
@@ -30,7 +31,7 @@ public class OptionUtilsTest {
doTupleListTest(null, new ArrayList<Pair<String, String>>());
}
private void doTupleListTest(String input, List<Pair<String, String>> expectedResults) {
private static 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());
@@ -41,7 +42,7 @@ public class OptionUtilsTest {
}
}
private void doCommaSeparatedListTest(String csvStr, List<String> expectedResults) {
private static void doCommaSeparatedListTest(String csvStr, List<String> expectedResults) {
final List<String> result = OptionUtils.splitCommaSeparatedList(csvStr);
assertNotNull(result);
assertEquals(result.size(), expectedResults.size());

View File

@@ -51,7 +51,7 @@
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<!-- <version>4.12</version> -->
<scope>test</scope>
</dependency>
</dependencies>

View File

@@ -99,7 +99,7 @@ public class CodeGenMojo extends AbstractMojo {
* A map of language-specific parameters as passed with the -c option to the command line
*/
@Parameter(name = "configOptions")
private Map configOptions;
private Map<?, ?> configOptions;
/**
* Add the output directory to the project as a source root, so that the

View File

@@ -101,7 +101,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-release-plugin</artifactId>
<version>2.1</version>
<!-- <version>2.1</version> -->
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
@@ -256,7 +256,7 @@
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>${testng-version}</version>
<!-- <version>${testng-version}</version> -->
<scope>test</scope>
</dependency>
<dependency>
@@ -268,7 +268,7 @@
<dependency>
<groupId>org.jmockit</groupId>
<artifactId>jmockit</artifactId>
<version>${jmockit-version}</version>
<!-- <version>${jmockit-version}</version> -->
<scope>test</scope>
</dependency>
</dependencies>

View File

@@ -14,6 +14,7 @@ import java.util.regex.Pattern;
public abstract class AbstractGenerator {
@SuppressWarnings("static-method")
public File writeToFile(String filename, String contents) throws IOException {
System.out.println("writing file " + filename);
File output = new File(filename);
@@ -48,10 +49,7 @@ public abstract class AbstractGenerator {
try {
InputStream is = this.getClass().getClassLoader().getResourceAsStream(getCPResourcePath(name));
if (is == null) {
is = new FileInputStream(new File(name));
}
if (is == null) {
throw new RuntimeException("no file found");
is = new FileInputStream(new File(name)); // May throw but never return a null value
}
return new InputStreamReader(is);
} catch (Exception e) {
@@ -96,6 +94,7 @@ public abstract class AbstractGenerator {
return this.getClass().getClassLoader().getResource(getCPResourcePath(name)) != null;
}
@SuppressWarnings("static-method")
public String getCPResourcePath(String name) {
if (!"/".equals(File.separator)) {
return name.replaceAll(Pattern.quote(File.separator), "/");

View File

@@ -5,13 +5,8 @@ import io.swagger.codegen.auth.AuthParser;
import io.swagger.models.Swagger;
import io.swagger.models.auth.AuthorizationValue;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import static org.apache.commons.lang3.StringUtils.isNotEmpty;
public class ClientOptInput {
private CodegenConfig config;
private ClientOpts opts;

View File

@@ -11,7 +11,6 @@ import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
@@ -32,10 +31,9 @@ public class Codegen extends DefaultGenerator {
"\n -DdebugOperations prints operations passed to the template engine" +
"\n -DdebugSupportingFiles prints additional data passed to the template engine";
@SuppressWarnings("deprecation")
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 + "]");
@@ -139,7 +137,7 @@ public class Codegen extends DefaultGenerator {
// see if it's a class
try {
System.out.println("loading class " + name);
Class customClass = Class.forName(name);
Class<?> customClass = Class.forName(name);
System.out.println("loaded");
return (CodegenConfig) customClass.newInstance();
} catch (Exception e) {

View File

@@ -62,4 +62,10 @@ public class CodegenConstants {
public static final String OPTIONAL_ASSEMBLY_INFO = "optionalAssemblyInfo";
public static final String OPTIONAL_ASSEMBLY_INFO_DESC = "Generate AssemblyInfo.cs (Default: true).";
public static final String OPTIONAL_PROJECT_FILE = "optionalProjectFile";
public static final String OPTIONAL_PROJECT_FILE_DESC = "Generate {PackageName}.csproj (Default: false).";
public static final String OPTIONAL_PROJECT_GUID = "packageGuid";
public static final String OPTIONAL_PROJECT_GUID_DESC = "The GUID that will be associated with the C# project";
}

View File

@@ -38,7 +38,7 @@ public class CodegenOperation {
*
* @return true if parameter exists, false otherwise
*/
private boolean nonempty(List<CodegenParameter> params) {
private static boolean nonempty(List<CodegenParameter> params) {
return params != null && params.size() > 0;
}

View File

@@ -40,6 +40,50 @@ public class CodegenProperty {
public CodegenProperty items;
public Map<String, Object> vendorExtensions;
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + ((_enum == null) ? 0 : _enum.hashCode());
result = prime * result + ((allowableValues == null) ? 0 : allowableValues.hashCode());
result = prime * result + ((baseName == null) ? 0 : baseName.hashCode());
result = prime * result + ((baseType == null) ? 0 : baseType.hashCode());
result = prime * result + ((complexType == null) ? 0 : complexType.hashCode());
result = prime * result + ((containerType == null) ? 0 : containerType.hashCode());
result = prime * result + ((datatype == null) ? 0 : datatype.hashCode());
result = prime * result + ((datatypeWithEnum == null) ? 0 : datatypeWithEnum.hashCode());
result = prime * result + ((defaultValue == null) ? 0 : defaultValue.hashCode());
result = prime * result + ((defaultValueWithParam == null) ? 0 : defaultValueWithParam.hashCode());
result = prime * result + ((description == null) ? 0 : description.hashCode());
result = prime * result + ((example == null) ? 0 : example.hashCode());
result = prime * result + ((exclusiveMaximum == null) ? 0 : exclusiveMaximum.hashCode());
result = prime * result + ((exclusiveMinimum == null) ? 0 : exclusiveMinimum.hashCode());
result = prime * result + ((getter == null) ? 0 : getter.hashCode());
result = prime * result + ((hasMore == null) ? 0 : hasMore.hashCode());
result = prime * result + ((isContainer == null) ? 0 : isContainer.hashCode());
result = prime * result + (isEnum ? 1231 : 1237);
result = prime * result + ((isNotContainer == null) ? 0 : isNotContainer.hashCode());
result = prime * result + ((isPrimitiveType == null) ? 0 : isPrimitiveType.hashCode());
result = prime * result + ((isReadOnly == null) ? 0 : isReadOnly.hashCode());
result = prime * result + ((items == null) ? 0 : items.hashCode());
result = prime * result + ((jsonSchema == null) ? 0 : jsonSchema.hashCode());
result = prime * result + ((max == null) ? 0 : max.hashCode());
result = prime * result + ((maxLength == null) ? 0 : maxLength.hashCode());
result = prime * result + ((maximum == null) ? 0 : maximum.hashCode());
result = prime * result + ((min == null) ? 0 : min.hashCode());
result = prime * result + ((minLength == null) ? 0 : minLength.hashCode());
result = prime * result + ((minimum == null) ? 0 : minimum.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((pattern == null) ? 0 : pattern.hashCode());
result = prime * result + ((required == null) ? 0 : required.hashCode());
result = prime * result + ((secondaryParam == null) ? 0 : secondaryParam.hashCode());
result = prime * result + ((setter == null) ? 0 : setter.hashCode());
result = prime * result + ((unescapedDescription == null) ? 0 : unescapedDescription.hashCode());
result = prime * result + ((vendorExtensions == null) ? 0 : vendorExtensions.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {

View File

@@ -109,38 +109,48 @@ public class DefaultCodegen {
}
// override with any special post-processing
@SuppressWarnings("static-method")
public Map<String, Object> postProcessModels(Map<String, Object> objs) {
return objs;
}
// override with any special post-processing
@SuppressWarnings("static-method")
public Map<String, Object> postProcessOperations(Map<String, Object> objs) {
return objs;
}
// override with any special post-processing
@SuppressWarnings("static-method")
public Map<String, Object> postProcessSupportingFileData(Map<String, Object> objs) {
return objs;
}
// override to post-process any model properties
public void postProcessModelProperty(CodegenModel model, CodegenProperty property){}
@SuppressWarnings("unused")
public void postProcessModelProperty(CodegenModel model, CodegenProperty property){
}
// override to post-process any parameters
public void postProcessParameter(CodegenParameter parameter){}
@SuppressWarnings("unused")
public void postProcessParameter(CodegenParameter parameter){
}
//override with any special handling of the entire swagger spec
@SuppressWarnings("unused")
public void preprocessSwagger(Swagger swagger) {
}
// override with any special handling of the entire swagger spec
@SuppressWarnings("unused")
public void processSwagger(Swagger swagger) {
}
// override with any special text escaping logic
@SuppressWarnings("static-method")
public String escapeText(String input) {
if (input != null) {
input = input.trim();
if (input != null) {
input = input.trim(); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
String output = input.replaceAll("\n", "\\\\n");
output = output.replace("\r", "\\r");
output = output.replace("\"", "\\\"");
@@ -274,7 +284,7 @@ public class DefaultCodegen {
}
/**
* Return the file name of the Api
* Return the file name of the Api Test
*
* @param name the file name of the Api
* @return the file name of the Api
@@ -304,7 +314,7 @@ public class DefaultCodegen {
}
/**
* Return the capitalized file name of the model
* Return the capitalized file name of the model test
*
* @param name the model name
* @return the file name of the model
@@ -322,13 +332,14 @@ public class DefaultCodegen {
public String toModelTestFilename(String name) {
return initialCaps(name) + "Test";
}
/**
* Return the operation ID (method name)
*
* @param operationId operation ID
* @return the sanitized method name
*/
@SuppressWarnings("static-method")
public String toOperationId(String operationId) {
// throw exception if method name is empty
if (StringUtils.isEmpty(operationId)) {
@@ -361,7 +372,7 @@ public class DefaultCodegen {
* @return the sanitized parameter name
*/
public String toParamName(String name) {
name = removeNonNameElementToCamelCase(name);
name = removeNonNameElementToCamelCase(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
if (reservedWords.contains(name)) {
return escapeReservedWord(name);
}
@@ -374,6 +385,7 @@ public class DefaultCodegen {
* @param property Codegen property object
* @return the Enum name
*/
@SuppressWarnings("static-method")
public String toEnumName(CodegenProperty property) {
return StringUtils.capitalize(property.name) + "Enum";
}
@@ -386,6 +398,7 @@ public class DefaultCodegen {
*
* throws Runtime exception as reserved word is not allowed (default behavior)
*/
@SuppressWarnings("static-method")
public String escapeReservedWord(String name) {
throw new RuntimeException("reserved word " + name + " not allowed");
}
@@ -495,6 +508,7 @@ public class DefaultCodegen {
* @param operation Swagger operation object
* @return string presentation of the example path
*/
@SuppressWarnings("static-method")
public String generateExamplePath(String path, Operation operation) {
StringBuilder sb = new StringBuilder();
sb.append(path);
@@ -577,6 +591,7 @@ public class DefaultCodegen {
* @param p Swagger property object
* @return string presentation of the default value of the property
*/
@SuppressWarnings("static-method")
public String toDefaultValue(Property p) {
if (p instanceof StringProperty) {
return "null";
@@ -623,42 +638,9 @@ public class DefaultCodegen {
* @param p Swagger property object
* @return string presentation of the default value of the property
*/
@SuppressWarnings("static-method")
public String toDefaultValueWithParam(String name, Property p) {
if (p instanceof StringProperty) {
return " = data." + name + ";";
} else if (p instanceof BooleanProperty) {
return " = data." + name + ";";
} else if (p instanceof DateProperty) {
return " = data." + name + ";";
} else if (p instanceof DateTimeProperty) {
return " = data." + name + ";";
} else if (p instanceof DoubleProperty) {
DoubleProperty dp = (DoubleProperty) p;
if (dp.getDefault() != null) {
return dp.getDefault().toString();
}
return " = data." + name + ";";
} else if (p instanceof FloatProperty) {
FloatProperty dp = (FloatProperty) p;
if (dp.getDefault() != null) {
return dp.getDefault().toString();
}
return " = data." + name + ";";
} else if (p instanceof IntegerProperty) {
IntegerProperty dp = (IntegerProperty) p;
if (dp.getDefault() != null) {
return dp.getDefault().toString();
}
return " = data." + name + ";";
} else if (p instanceof LongProperty) {
LongProperty dp = (LongProperty) p;
if (dp.getDefault() != null) {
return dp.getDefault().toString();
}
return " = data." + name + ";";
} else {
return " = data." + name + ";";
}
return " = data." + name + ";";
}
/**
@@ -666,6 +648,7 @@ public class DefaultCodegen {
* @param p Swagger property object
* @return string presentation of the type
**/
@SuppressWarnings("static-method")
public String getSwaggerType(Property p) {
String datatype = null;
if (p instanceof StringProperty && "number".equals(p.getFormat())) {
@@ -694,6 +677,8 @@ public class DefaultCodegen {
datatype = "map";
} else if (p instanceof DecimalProperty) {
datatype = "number";
} else if ( p instanceof UUIDProperty) {
datatype = "UUID";
} else if (p instanceof RefProperty) {
try {
RefProperty r = (RefProperty) p;
@@ -720,6 +705,7 @@ public class DefaultCodegen {
* @param name string to be snake-cased
* @return snake-cased string
*/
@SuppressWarnings("static-method")
public String snakeCase(String name) {
return (name.length() > 0) ? (Character.toLowerCase(name.charAt(0)) + name.substring(1)) : "";
}
@@ -730,6 +716,7 @@ public class DefaultCodegen {
* @param name string to be capitalized
* @return capitalized string
*/
@SuppressWarnings("static-method")
public String initialCaps(String name) {
return StringUtils.capitalize(name);
}
@@ -740,6 +727,7 @@ public class DefaultCodegen {
* @param name name
* @return a string presentation of the type
*/
@SuppressWarnings("static-method")
public String getTypeDeclaration(String name) {
return name;
}
@@ -1145,7 +1133,7 @@ public class DefaultCodegen {
}
}
private Response findMethodResponse(Map<String, Response> responses) {
private static Response findMethodResponse(Map<String, Response> responses) {
String code = null;
for (String responseCode : responses.keySet()) {
@@ -1618,7 +1606,6 @@ public class DefaultCodegen {
// to use the built-in model parsing, we unwrap the ArrayModel
// and get a single property from it
ArrayModel impl = (ArrayModel) model;
CodegenModel cm = fromModel(bp.getName(), impl);
// get the single property
ArrayProperty ap = new ArrayProperty().items(impl.getItems());
ap.setRequired(param.getRequired());
@@ -1659,6 +1646,7 @@ public class DefaultCodegen {
* @param schemes a map of Swagger SecuritySchemeDefinition object
* @return a list of Codegen Security objects
*/
@SuppressWarnings("static-method")
public List<CodegenSecurity> fromSecurity(Map<String, SecuritySchemeDefinition> schemes) {
if (schemes == null) {
return Collections.emptyList();
@@ -1765,6 +1753,7 @@ public class DefaultCodegen {
&& !languageSpecificPrimitives.contains(type);
}
@SuppressWarnings("static-method")
protected List<Map<String, Object>> toExamples(Map<String, Object> examples) {
if (examples == null) {
return null;
@@ -1788,7 +1777,7 @@ public class DefaultCodegen {
}
}
private List<CodegenParameter> addHasMore(List<CodegenParameter> objs) {
private static List<CodegenParameter> addHasMore(List<CodegenParameter> objs) {
if (objs != null) {
for (int i = 0; i < objs.size(); i++) {
if (i > 0) {
@@ -1802,7 +1791,7 @@ public class DefaultCodegen {
return objs;
}
private Map<String, Object> addHasMore(Map<String, Object> objs) {
private static Map<String, Object> addHasMore(Map<String, Object> objs) {
if (objs != null) {
for (int i = 0; i < objs.size() - 1; i++) {
if (i > 0) {
@@ -1825,6 +1814,7 @@ public class DefaultCodegen {
* @param co Codegen Operation object
* @param operations map of Codegen operations
*/
@SuppressWarnings("static-method")
public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, Map<String, List<CodegenOperation>> operations) {
List<CodegenOperation> opList = operations.get(tag);
if (opList == null) {
@@ -1849,8 +1839,6 @@ public class DefaultCodegen {
co.baseName = tag;
}
private void addParentContainer(CodegenModel m, String name, Property property) {
final CodegenProperty tmp = fromProperty(name, property);
addImport(m, tmp.complexType);
@@ -1879,7 +1867,7 @@ public class DefaultCodegen {
String secondPattern = "([a-z\\d])([A-Z])";
String replacementPattern = "$1_$2";
// Replace package separator with slash.
word = word.replaceAll("\\.", "/");
word = word.replaceAll("\\.", "/"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
// Replace $ with two underscores for inner classes.
word = word.replaceAll("\\$", "__");
// Replace capital letter with _ plus lowercase letter.
@@ -1896,6 +1884,7 @@ public class DefaultCodegen {
* @param word The word
* @return The dashized version of the word, e.g. "my-name"
*/
@SuppressWarnings("static-method")
protected String dashize(String word) {
return underscore(word).replaceAll("[_ ]", "-");
}
@@ -1910,7 +1899,7 @@ public class DefaultCodegen {
* @param name The base name
* @return The next name for the base name
*/
private String generateNextName(String name) {
private static String generateNextName(String name) {
Pattern pattern = Pattern.compile("\\d+\\z");
Matcher matcher = pattern.matcher(name);
if (matcher.find()) {
@@ -1975,9 +1964,10 @@ public class DefaultCodegen {
* @param name string to be camelize
* @return camelized string
*/
@SuppressWarnings("static-method")
public String removeNonNameElementToCamelCase(String name) {
String nonNameElementPattern = "[-_:;#]";
name = StringUtils.join(Lists.transform(Lists.newArrayList(name.split(nonNameElementPattern)), new Function<String, String>() {
name = StringUtils.join(Lists.transform(Lists.newArrayList(name.split(nonNameElementPattern)), new Function<String, String>() { // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
@Nullable
@Override
public String apply(String input) {
@@ -2014,7 +2004,7 @@ public class DefaultCodegen {
Pattern p = Pattern.compile("\\/(.?)");
Matcher m = p.matcher(word);
while (m.find()) {
word = m.replaceFirst("." + m.group(1)/*.toUpperCase()*/);
word = m.replaceFirst("." + m.group(1)/*.toUpperCase()*/); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
m = p.matcher(word);
}
@@ -2118,6 +2108,7 @@ public class DefaultCodegen {
return library;
}
@SuppressWarnings("static-method")
protected CliOption buildLibraryCliOption(Map<String, String> supportedLibraries) {
StringBuilder sb = new StringBuilder("library template (sub-template) to use:");
for (String lib : supportedLibraries.keySet()) {
@@ -2132,6 +2123,7 @@ public class DefaultCodegen {
* @param name string to be sanitize
* @return sanitized string
*/
@SuppressWarnings("static-method")
public String sanitizeName(String name) {
// NOTE: performance wise, we should have written with 2 replaceAll to replace desired
// character with _ or empty character. Below aims to spell out different cases we've
@@ -2145,7 +2137,7 @@ public class DefaultCodegen {
}
// input[] => input
name = name.replaceAll("\\[\\]", "");
name = name.replaceAll("\\[\\]", ""); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
// input[a][b] => input_a_b
name = name.replaceAll("\\[", "_");
@@ -2167,6 +2159,5 @@ public class DefaultCodegen {
// remove everything else other than word, number and _
// $php_variable => php_variable
return name.replaceAll("[^a-zA-Z0-9_]", "");
}
}

View File

@@ -19,7 +19,7 @@ import static org.apache.commons.lang3.StringUtils.capitalize;
import static org.apache.commons.lang3.StringUtils.isNotEmpty;
public class DefaultGenerator extends AbstractGenerator implements Generator {
Logger LOGGER = LoggerFactory.getLogger(DefaultGenerator.class);
protected Logger LOGGER = LoggerFactory.getLogger(DefaultGenerator.class);
protected CodegenConfig config;
protected ClientOptInput opts;
@@ -438,18 +438,12 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
}
File outputFile = new File(outputFilename);
OutputStream out = new FileOutputStream(outputFile, false);
if (in != null && out != null) {
if (in != null) {
System.out.println("writing file " + outputFile);
IOUtils.copy(in, out);
} else {
if (in == null) {
System.out.println("can't open " + templateFile + " for input");
}
if (out == null) {
System.out.println("can't open " + outputFile + " for output");
}
System.out.println("can't open " + templateFile + " for input"); // FIXME: use LOGGER instead of standart output
}
files.add(outputFile);
}
}
@@ -458,13 +452,11 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
}
}
}
config.processSwagger(swagger);
return files;
}
private void processMimeTypes(List<String> mimeTypeList, Map<String, Object> operation, String source) {
private static void processMimeTypes(List<String> mimeTypeList, Map<String, Object> operation, String source) {
if (mimeTypeList != null && mimeTypeList.size() > 0) {
List<Map<String, String>> c = new ArrayList<Map<String, String>>();
int count = 0;
@@ -485,7 +477,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
}
}
private List<String> sortModelsByInheritance(final Map<String, Model> definitions) {
private static List<String> sortModelsByInheritance(final Map<String, Model> definitions) {
List<String> sortedModelKeys = new ArrayList<String>(definitions.keySet());
Comparator<String> cmp = new Comparator<String>() {
@Override
@@ -655,10 +647,11 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
}
}
private String generateParameterId(Parameter parameter) {
private static String generateParameterId(Parameter parameter) {
return parameter.getName() + ":" + parameter.getIn();
}
@SuppressWarnings("static-method")
protected String sanitizeTag(String tag) {
// remove spaces and make strong case
String[] parts = tag.split(" ");
@@ -671,6 +664,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
return buf.toString().replaceAll("[^a-zA-Z ]", "");
}
@SuppressWarnings("static-method")
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>();
@@ -731,6 +725,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
return operations;
}
@SuppressWarnings("static-method")
public Map<String, Object> processModels(CodegenConfig config, Map<String, Model> definitions, Map<String, Model> allDefinitions) {
Map<String, Object> objs = new HashMap<String, Object>();
objs.put("package", config.modelPackage());
@@ -750,7 +745,6 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
Set<String> importSet = new TreeSet<String>();
for (String nextImport : allImports) {
Map<String, String> im = new HashMap<String, String>();
String mapping = config.importMapping().get(nextImport);
if (mapping == null) {
mapping = config.toModelImport(nextImport);

View File

@@ -1,10 +1,8 @@
package io.swagger.codegen;
import com.sun.org.apache.xpath.internal.operations.Mod;
import io.swagger.models.*;
import io.swagger.models.parameters.BodyParameter;
import io.swagger.models.parameters.Parameter;
import io.swagger.models.parameters.RefParameter;
import io.swagger.models.properties.*;
import io.swagger.util.Json;
@@ -174,9 +172,7 @@ public class InlineModelResolver {
m.setItems(new RefProperty(existing));
}
}
} else if (model instanceof ComposedModel) {
ComposedModel m = (ComposedModel) model;
}
}
}
}
}
@@ -199,7 +195,7 @@ public class InlineModelResolver {
public String uniqueName(String key) {
int count = 0;
boolean done = false;
key = key.replaceAll("[^a-z_\\.A-Z0-9 ]", "");
key = key.replaceAll("[^a-z_\\.A-Z0-9 ]", ""); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
while (!done) {
String name = key;
if (count > 0) {
@@ -295,53 +291,26 @@ public class InlineModelResolver {
}
}
public Model modelFromProperty(ArrayProperty object, String path) {
String access = object.getAccess();
@SuppressWarnings("static-method")
public Model modelFromProperty(ArrayProperty object, @SuppressWarnings("unused") String path) {
String description = object.getDescription();
String example = object.getExample();
String name = object.getName();
Integer position = object.getPosition();
Boolean readOnly = object.getReadOnly();
Boolean required = object.getRequired();
String title = object.getTitle();
Map<String, Object> extensions = object.getVendorExtensions();
Xml xml = object.getXml();
// object.getItems()
// Map<String, Property> properties = object.getProperties();
Property inner = object.getItems();
if (inner instanceof ObjectProperty) {
ArrayModel model = new ArrayModel();
model.setDescription(description);
model.setExample(example);
// model.setName(name);
// model.setXml(xml);
model.setItems(object.getItems());
return model;
}
// if(properties != null) {
// flattenProperties(properties, path);
// model.setProperties(properties);
// }
return null;
}
public Model modelFromProperty(ObjectProperty object, String path) {
String access = object.getAccess();
String description = object.getDescription();
String example = object.getExample();
String name = object.getName();
Integer position = object.getPosition();
Boolean readOnly = object.getReadOnly();
Boolean required = object.getRequired();
String title = object.getTitle();
Map<String, Object> extensions = object.getVendorExtensions();
Xml xml = object.getXml();
Map<String, Property> properties = object.getProperties();
ModelImpl model = new ModelImpl();
@@ -358,17 +327,10 @@ public class InlineModelResolver {
return model;
}
public Model modelFromProperty(MapProperty object, String path) {
String access = object.getAccess();
@SuppressWarnings("static-method")
public Model modelFromProperty(MapProperty object, @SuppressWarnings("unused") String path) {
String description = object.getDescription();
String example = object.getExample();
String name = object.getName();
Integer position = object.getPosition();
Boolean readOnly = object.getReadOnly();
Boolean required = object.getRequired();
String title = object.getTitle();
Map<String, Object> extensions = object.getVendorExtensions();
Xml xml = object.getXml();
ArrayModel model = new ArrayModel();
model.setDescription(description);

View File

@@ -2,7 +2,6 @@ package io.swagger.codegen;
import com.samskivert.mustache.Mustache;
import com.samskivert.mustache.Template;
import io.swagger.models.Swagger;
import org.apache.commons.cli.BasicParser;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
@@ -57,8 +56,6 @@ public class MetaGenerator extends AbstractGenerator {
}
protected void generate(String[] args) {
StringBuilder sb = new StringBuilder();
String targetLanguage = null;
String outputFolder = null;
String name = null;
String targetPackage = "io.swagger.codegen";
@@ -71,12 +68,9 @@ public class MetaGenerator extends AbstractGenerator {
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);
@@ -85,12 +79,11 @@ public class MetaGenerator extends AbstractGenerator {
if (cmd.hasOption("n")) {
name = cmd.getOptionValue("n");
} else {
System.out.println("name is required");
System.out.println("name is required"); //FIXME replace by LOGGER
usage(options);
return;
}
if (cmd.hasOption("l")) {
targetLanguage = cmd.getOptionValue("l");
}
if (cmd.hasOption("p")) {
targetPackage = cmd.getOptionValue("p");
@@ -98,7 +91,7 @@ public class MetaGenerator extends AbstractGenerator {
if (cmd.hasOption("o")) {
outputFolder = cmd.getOptionValue("o");
} else {
System.out.println("output folder is required");
System.out.println("output folder is required"); // FIXME replace by LOGGER
usage(options);
return;
}
@@ -161,8 +154,6 @@ public class MetaGenerator extends AbstractGenerator {
public Reader getTemplate(String name) {
return getTemplateReader(templateDir + File.separator + name + ".mustache");
}
;
})
.defaultValue("")
.compile(template);

View File

@@ -11,6 +11,7 @@ public class SupportingFile {
this.destinationFilename = destinationFilename;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("SupportingFile:").append("\n");

View File

@@ -18,7 +18,7 @@ public class AuthParser {
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"));
auths.add(new AuthorizationValue(URLDecoder.decode(kvPair[0]), URLDecoder.decode(kvPair[1]), "header")); // FIXME replace the deprecated method by decode(string, encoding). Which encoding is used ? Default UTF-8 ?
}
}
}

View File

@@ -42,7 +42,7 @@ public class ExampleGenerator {
if (examples == null) {
if (mediaTypes == null) {
// assume application/json for this
mediaTypes = Arrays.asList("application/json");
mediaTypes = Arrays.asList("application/json"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
}
for (String mediaType : mediaTypes) {
Map<String, String> kv = new HashMap<String, String>();
@@ -127,7 +127,7 @@ public class ExampleGenerator {
return resolveModelToExample(simpleName, mediaType, model, processedModels);
}
} else if (property instanceof UUIDProperty) {
return "046b6c7f-0b8a-43b9-b35d-6489e6daee91";
return "046b6c7f-0b8a-43b9-b35d-6489e6daee91";
}
return "";
@@ -142,16 +142,14 @@ public class ExampleGenerator {
ModelImpl impl = (ModelImpl) model;
Map<String, Object> values = new HashMap<String, Object>();
if (impl != null && impl.getProperties() != null) {
if (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

@@ -39,7 +39,7 @@ public class XmlExampleGenerator {
public XmlExampleGenerator(Map<String, Model> examples) {
this.examples = examples;
if (examples == null) {
examples = new HashMap<String, Model>();
this.examples = new HashMap<String, Model>();
}
}
@@ -74,10 +74,6 @@ public class XmlExampleGenerator {
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) {
@@ -117,6 +113,7 @@ public class XmlExampleGenerator {
return sb.toString();
}
@SuppressWarnings("static-method")
protected String quote(String string) {
return "\"" + string + "\"";
}
@@ -211,14 +208,17 @@ public class XmlExampleGenerator {
return "not implemented " + property;
}
@SuppressWarnings("static-method")
protected String openTag(String name) {
return "<" + name + ">";
}
@SuppressWarnings("static-method")
protected String closeTag(String name) {
return "</" + name + ">";
}
@SuppressWarnings("static-method")
protected String indent(int indent) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < indent; i++) {

View File

@@ -9,10 +9,6 @@ import java.io.File;
import org.apache.commons.lang.StringUtils;
public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen implements CodegenConfig {
@Override
public CodegenType getTag() {
return CodegenType.CLIENT;
}
public AbstractTypeScriptClientCodegen() {
super();
@@ -56,6 +52,11 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp
// mapped to String as a workaround
typeMapping.put("binary", "string");
}
@Override
public CodegenType getTag() {
return CodegenType.CLIENT;
}
@Override
public String escapeReservedWord(String name) {
@@ -75,7 +76,7 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp
@Override
public String toVarName(String name) {
// replace - with _ e.g. created-at => created_at
name = name.replaceAll("-", "_");
name = name.replaceAll("-", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
// if it's all uppper case, do nothing
if (name.matches("^[A-Z_]*$"))

View File

@@ -63,7 +63,9 @@ public class AkkaScalaClientCodegen extends DefaultCodegen implements CodegenCon
* unmarshalling problems and any other RuntimeException will be considered as ApiErrors.
*/
protected boolean onlyOneSuccess = true;
Logger LOGGER = LoggerFactory.getLogger(AkkaScalaClientCodegen.class);
@SuppressWarnings("hiding")
protected Logger LOGGER = LoggerFactory.getLogger(AkkaScalaClientCodegen.class);
public AkkaScalaClientCodegen() {
super();

View File

@@ -7,7 +7,6 @@ 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.MapProperty;
import io.swagger.models.properties.Property;
@@ -151,7 +150,7 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi
@Override
public String toVarName(String name) {
// replace - with _ e.g. created-at => created_at
name = name.replaceAll("-", "_");
name = name.replaceAll("-", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
// if it's all uppper case, do nothing
if (name.matches("^[A-Z_]*$")) {

View File

@@ -23,8 +23,6 @@ import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import org.apache.commons.lang.StringUtils;
public class AsyncScalaClientCodegen extends DefaultCodegen implements CodegenConfig {
protected String invokerPackage = "io.swagger.client";
protected String groupId = "io.swagger";

View File

@@ -22,10 +22,13 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig {
@SuppressWarnings({ "unused", "hiding" })
private static final Logger LOGGER = LoggerFactory.getLogger(CSharpClientCodegen.class);
protected boolean optionalAssemblyInfoFlag = true;
protected boolean optionalProjectFileFlag = false;
protected boolean optionalMethodArgumentFlag = true;
protected boolean useDateTimeOffsetFlag = false;
protected String packageGuid = "{" + java.util.UUID.randomUUID().toString().toUpperCase() + "}";
protected String packageTitle = "Swagger Library";
protected String packageProductName = "SwaggerLibrary";
protected String packageDescription = "A library generated from a Swagger doc";
@@ -119,6 +122,9 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig
CodegenConstants.OPTIONAL_ASSEMBLY_INFO_DESC).defaultValue(Boolean.TRUE.toString()));
cliOptions.add(new CliOption(CodegenConstants.SOURCE_FOLDER, CodegenConstants.SOURCE_FOLDER_DESC).defaultValue(sourceFolder));
cliOptions.add(CliOption.newBoolean(CodegenConstants.USE_DATETIME_OFFSET, CodegenConstants.USE_DATETIME_OFFSET_DESC));
cliOptions.add(CliOption.newBoolean(CodegenConstants.OPTIONAL_PROJECT_FILE,
CodegenConstants.OPTIONAL_PROJECT_FILE_DESC).defaultValue(Boolean.FALSE.toString()));
cliOptions.add(new CliOption(CodegenConstants.OPTIONAL_PROJECT_GUID, CodegenConstants.OPTIONAL_PROJECT_GUID_DESC));
}
@Override
@@ -163,7 +169,19 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig
additionalProperties.put("packageDescription", packageDescription);
additionalProperties.put("packageCompany", packageCompany);
additionalProperties.put("packageCopyright", packageCopyright);
if (additionalProperties.containsKey(CodegenConstants.OPTIONAL_PROJECT_FILE))
{
setOptionalProjectFileFlag(Boolean.valueOf(
additionalProperties.get(CodegenConstants.OPTIONAL_PROJECT_FILE).toString()));
}
if (additionalProperties.containsKey(CodegenConstants.OPTIONAL_PROJECT_GUID))
{
setPackageGuid((String) additionalProperties.get(CodegenConstants.OPTIONAL_PROJECT_GUID));
}
additionalProperties.put("packageGuid", packageGuid);
if (additionalProperties.containsKey(CodegenConstants.OPTIONAL_METHOD_ARGUMENT)) {
setOptionalMethodArgumentFlag(Boolean.valueOf(additionalProperties
.get(CodegenConstants.OPTIONAL_METHOD_ARGUMENT).toString()));
@@ -174,15 +192,28 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig
setOptionalAssemblyInfoFlag(Boolean.valueOf(additionalProperties
.get(CodegenConstants.OPTIONAL_ASSEMBLY_INFO).toString()));
}
String packageFolder = sourceFolder + File.separator + packageName.replace(".", java.io.File.separator);
String clientPackageDir = sourceFolder + File.separator + clientPackage.replace(".", java.io.File.separator);
//Compute the relative path to the bin directory where the external assemblies live
//This is necessary to properly generate the project file
int packageDepth = packageFolder.length() - packageFolder.replace(java.io.File.separator, "").length();
String binRelativePath = "..\\";
for (int i=0; i < packageDepth; i = i+1)
binRelativePath += "..\\";
binRelativePath += "bin\\";
additionalProperties.put("binRelativePath", binRelativePath);
supportingFiles.add(new SupportingFile("Configuration.mustache",
sourceFolder + File.separator + clientPackage.replace(".", java.io.File.separator), "Configuration.cs"));
clientPackageDir, "Configuration.cs"));
supportingFiles.add(new SupportingFile("ApiClient.mustache",
sourceFolder + File.separator + clientPackage.replace(".", java.io.File.separator), "ApiClient.cs"));
clientPackageDir, "ApiClient.cs"));
supportingFiles.add(new SupportingFile("ApiException.mustache",
sourceFolder + File.separator + clientPackage.replace(".", java.io.File.separator), "ApiException.cs"));
clientPackageDir, "ApiException.cs"));
supportingFiles.add(new SupportingFile("ApiResponse.mustache",
sourceFolder + File.separator + clientPackage.replace(".", java.io.File.separator), "ApiResponse.cs"));
clientPackageDir, "ApiResponse.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"));
@@ -191,9 +222,11 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig
supportingFiles.add(new SupportingFile("README.md", "", "README.md"));
if (optionalAssemblyInfoFlag) {
supportingFiles.add(new SupportingFile("AssemblyInfo.mustache", "src" + File.separator + "Properties", "AssemblyInfo.cs"));
supportingFiles.add(new SupportingFile("AssemblyInfo.mustache", packageFolder + File.separator + "Properties", "AssemblyInfo.cs"));
}
if (optionalProjectFileFlag) {
supportingFiles.add(new SupportingFile("Project.mustache", packageFolder, clientPackage + ".csproj"));
}
}
@Override
@@ -229,7 +262,7 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig
@Override
public String toVarName(String name) {
// sanitize name
name = sanitizeName(name);
name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
// if it's all uppper case, do nothing
if (name.matches("^[A-Z_]*$")) {
@@ -338,6 +371,10 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig
this.optionalAssemblyInfoFlag = flag;
}
public void setOptionalProjectFileFlag(boolean flag) {
this.optionalProjectFileFlag = flag;
}
public void setOptionalMethodArgumentFlag(boolean flag) {
this.optionalMethodArgumentFlag = flag;
}
@@ -350,7 +387,10 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig
typeMapping.put("datetime", "DateTime?");
}
public void setPackageGuid(String packageGuid) {
this.packageGuid = packageGuid;
}
public void setPackageName(String packageName) {
this.packageName = packageName;
}

View File

@@ -172,7 +172,7 @@ public class ClojureClientCodegen extends DefaultCodegen implements CodegenConfi
@Override
public String toVarName(String name) {
name = name.replaceAll("[^a-zA-Z0-9_-]+", "");
name = name.replaceAll("[^a-zA-Z0-9_-]+", ""); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
name = dashize(name);
return name;
}
@@ -196,6 +196,7 @@ public class ClojureClientCodegen extends DefaultCodegen implements CodegenConfi
return operations;
}
@SuppressWarnings("static-method")
protected String namespaceToFolder(String ns) {
return ns.replace(".", File.separator).replace("-", "_");
}

View File

@@ -172,7 +172,7 @@ public class CsharpDotNet2ClientCodegen extends DefaultCodegen implements Codege
@Override
public String toVarName(String name) {
// replace - with _ e.g. created-at => created_at
name = name.replaceAll("-", "_");
name = name.replaceAll("-", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
// if it's all uppper case, do nothing
if (name.matches("^[A-Z_]*$")) {

View File

@@ -171,7 +171,7 @@ public class DartClientCodegen extends DefaultCodegen implements CodegenConfig {
@Override
public String toVarName(String name) {
// replace - with _ e.g. created-at => created_at
name = name.replaceAll("-", "_");
name = name.replaceAll("-", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
// if it's all uppper case, do nothing
if (name.matches("^[A-Z_]*$")) {
@@ -221,15 +221,10 @@ public class DartClientCodegen extends DefaultCodegen implements CodegenConfig {
@Override
public String toDefaultValue(Property p) {
if (p instanceof MapProperty) {
MapProperty ap = (MapProperty) p;
String inner = getSwaggerType(ap.getAdditionalProperties());
return "{}";
} else if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
String inner = getSwaggerType(ap.getItems());
return "[]";
}
return super.toDefaultValue(p);
}

View File

@@ -193,14 +193,7 @@ public class FlashClientCodegen extends DefaultCodegen implements CodegenConfig
@Override
public String getTypeDeclaration(Property p) {
if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
return getSwaggerType(p);
} else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
if (p instanceof ArrayProperty || p instanceof MapProperty) {
return getSwaggerType(p);
}
return super.getTypeDeclaration(p);
@@ -256,12 +249,8 @@ public class FlashClientCodegen extends DefaultCodegen implements CodegenConfig
}
return "0";
} else if (p instanceof MapProperty) {
MapProperty ap = (MapProperty) p;
String inner = getSwaggerType(ap.getAdditionalProperties());
return "new Dictionary()";
} else if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
String inner = getSwaggerType(ap.getItems());
return "new Array()";
} else {
return "null";
@@ -271,8 +260,8 @@ public class FlashClientCodegen extends DefaultCodegen implements CodegenConfig
@Override
public String toVarName(String name) {
// replace - with _ e.g. created-at => created_at
name = name.replaceAll("-", "_");
name = name.replaceAll("-", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
// if it's all uppper case, convert to lower case
if (name.matches("^[A-Z_]*$")) {
name = name.toLowerCase();
@@ -323,7 +312,7 @@ public class FlashClientCodegen extends DefaultCodegen implements CodegenConfig
@Override
public String toApiFilename(String name) {
// replace - with _ e.g. created-at => created_at
name = name.replaceAll("-", "_");
name = name.replaceAll("-", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
// e.g. PhoneNumberApi.rb => phone_number_api.rb
return camelize(name) + "Api";
@@ -376,7 +365,4 @@ public class FlashClientCodegen extends DefaultCodegen implements CodegenConfig
public void setSourceFolder(String sourceFolder) {
this.sourceFolder = sourceFolder;
}
}

View File

@@ -167,8 +167,8 @@ public class FlaskConnexionCodegen extends DefaultCodegen implements CodegenConf
*/
@Override
public String getHelp() {
return "Generates a python server library using the connexion project. By default, " +
"it will also generate service classes--which you can disable with the `-Dnoservice` environment variable.";
return "Generates a Python server library using the Connexion project. By default, " +
"it will also generate service classes -- which you can disable with the `-Dnoservice` environment variable.";
}
@Override
@@ -249,7 +249,7 @@ public class FlaskConnexionCodegen extends DefaultCodegen implements CodegenConf
}
@SuppressWarnings("unchecked")
private List<Map<String, Object>> getOperations(Map<String, Object> objs) {
private static List<Map<String, Object>> getOperations(Map<String, Object> objs) {
List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
Map<String, Object> apiInfo = (Map<String, Object>) objs.get("apiInfo");
List<Map<String, Object>> apis = (List<Map<String, Object>>) apiInfo.get("apis");
@@ -259,7 +259,7 @@ public class FlaskConnexionCodegen extends DefaultCodegen implements CodegenConf
return result;
}
private List<Map<String, Object>> sortOperationsByPath(List<CodegenOperation> ops) {
private static List<Map<String, Object>> sortOperationsByPath(List<CodegenOperation> ops) {
Multimap<String, CodegenOperation> opsByPath = ArrayListMultimap.create();
for (CodegenOperation op : ops) {
@@ -304,7 +304,7 @@ public class FlaskConnexionCodegen extends DefaultCodegen implements CodegenConf
@Override
public String toOperationId(String operationId) {
operationId = super.toOperationId(operationId);
operationId = super.toOperationId(operationId); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
// Use the part after the last dot, e.g.
// controllers.defaultController.addPet => addPet
operationId = operationId.replaceAll(".*\\.", "");
@@ -312,4 +312,4 @@ public class FlaskConnexionCodegen extends DefaultCodegen implements CodegenConf
// addPet => add_pet
return underscore(operationId);
}
}
}

View File

@@ -0,0 +1,283 @@
package io.swagger.codegen.languages;
import io.swagger.codegen.*;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
import java.io.File;
import java.util.*;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class GoClientCodegen extends DefaultCodegen implements CodegenConfig {
static Logger LOGGER = LoggerFactory.getLogger(GoClientCodegen.class);
protected String packageName = "swagger";
protected String packageVersion = "1.0.0";
public CodegenType getTag() {
return CodegenType.CLIENT;
}
public String getName() {
return "go";
}
public String getHelp() {
return "Generates a Go client library (beta).";
}
public GoClientCodegen() {
super();
outputFolder = "generated-code/go";
modelTemplateFiles.put("model.mustache", ".go");
apiTemplateFiles.put("api.mustache", ".go");
templateDir = "go";
reservedWords = new HashSet<String> (
Arrays.asList(
"break", "default", "func", "interface", "select",
"case", "defer", "go", "map", "struct",
"chan", "else", "goto", "package", "switch",
"const", "fallthrough", "if", "range", "type",
"continue", "for", "import", "return", "var")
);
defaultIncludes = new HashSet<String>(
Arrays.asList(
"map",
"array")
);
languageSpecificPrimitives = new HashSet<String>(
Arrays.asList(
"string",
"bool",
"uint",
"uint32",
"uint64",
"int",
"int32",
"int64",
"float32",
"float64",
"complex64",
"complex128",
"rune",
"byte")
);
instantiationTypes.clear();
/*instantiationTypes.put("array", "GoArray");
instantiationTypes.put("map", "GoMap");*/
typeMapping.clear();
typeMapping.put("integer", "int32");
typeMapping.put("long", "int64");
typeMapping.put("float", "float32");
typeMapping.put("double", "float64");
typeMapping.put("boolean", "bool");
typeMapping.put("string", "string");
typeMapping.put("Date", "time.Time");
typeMapping.put("DateTime", "time.Time");
typeMapping.put("password", "string");
typeMapping.put("File", "*os.File");
typeMapping.put("file", "*os.File");
// map binary to string as a workaround
// the correct solution is to use []byte
typeMapping.put("binary", "string");
importMapping = new HashMap<String, String>();
importMapping.put("time.Time", "time");
importMapping.put("*os.File", "os");
cliOptions.clear();
cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME, "Go package name (convention: lowercase).")
.defaultValue("swagger"));
cliOptions.add(new CliOption(CodegenConstants.PACKAGE_VERSION, "Go package version.")
.defaultValue("1.0.0"));
}
@Override
public void processOpts() {
//super.processOpts();
if (additionalProperties.containsKey(CodegenConstants.PACKAGE_NAME)) {
setPackageName((String) additionalProperties.get(CodegenConstants.PACKAGE_NAME));
}
else {
setPackageName("swagger");
}
if (additionalProperties.containsKey(CodegenConstants.PACKAGE_VERSION)) {
setPackageVersion((String) additionalProperties.get(CodegenConstants.PACKAGE_VERSION));
}
else {
setPackageVersion("1.0.0");
}
additionalProperties.put(CodegenConstants.PACKAGE_NAME, packageName);
additionalProperties.put(CodegenConstants.PACKAGE_VERSION, packageVersion);
modelPackage = packageName;
apiPackage = packageName;
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
}
@Override
public String escapeReservedWord(String name) {
return "_" + name;
}
@Override
public String apiFileFolder() {
return outputFolder + File.separator + packageName;
}
public String modelFileFolder() {
return outputFolder + File.separator + packageName;
}
@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);
// 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 "[]" + 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;
}
@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);
}
@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) {
// http method verb conversion (e.g. PUT => Put)
operation.httpMethod = camelize(operation.httpMethod.toLowerCase());
}
// remove model imports to avoid error
List<Map<String, String>> imports = (List<Map<String, String>>) objs.get("imports");
if (imports == null)
return objs;
Iterator<Map<String, String>> iterator = imports.iterator();
while (iterator.hasNext()) {
String _import = iterator.next().get("import");
if (_import.startsWith(apiPackage()))
iterator.remove();
}
return objs;
}
@Override
public Map<String, Object> postProcessModels(Map<String, Object> objs) {
// remove model imports to avoid error
List<Map<String, String>> imports = (List<Map<String, String>>) objs.get("imports");
final String prefix = modelPackage();
Iterator<Map<String, String>> iterator = imports.iterator();
while (iterator.hasNext()) {
String _import = iterator.next().get("import");
if (_import.startsWith(prefix))
iterator.remove();
}
return objs;
}
@Override
protected boolean needToImport(String type) {
return !defaultIncludes.contains(type)
&& !languageSpecificPrimitives.contains(type);
}
public void setPackageName(String packageName) {
this.packageName = packageName;
}
public void setPackageVersion(String packageVersion) {
this.packageVersion = packageVersion;
}
}

View File

@@ -5,8 +5,6 @@ import io.swagger.models.Operation;
import io.swagger.models.Path;
import io.swagger.models.Swagger;
import io.swagger.models.properties.*;
import org.apache.commons.lang.StringUtils;
import java.util.*;
import java.io.File;

View File

@@ -17,6 +17,7 @@ import java.io.File;
import java.util.*;
public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
@SuppressWarnings("hiding")
private static final Logger LOGGER = LoggerFactory.getLogger(JavaClientCodegen.class);
public static final String FULL_JAVA_UTIL = "fullJavaUtil";
public static final String DEFAULT_LIBRARY = "<default>";
@@ -322,7 +323,7 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
@Override
public String toVarName(String name) {
// sanitize name
name = sanitizeName(name);
name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
if("_".equals(name)) {
name = "_u";
@@ -353,7 +354,7 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
@Override
public String toModelName(String name) {
name = sanitizeName(name);
name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
// model name cannot use reserved keyword, e.g. return
if (reservedWords.contains(name)) {
@@ -647,7 +648,7 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
}
}
private String getAccept(Operation operation) {
private static String getAccept(Operation operation) {
String accepts = null;
String defaultContentType = "application/json";
if (operation.getProduces() != null && !operation.getProduces().isEmpty()) {
@@ -678,14 +679,14 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
return super.needToImport(type) && type.indexOf(".") < 0;
}
private String findCommonPrefixOfVars(List<String> vars) {
private static String findCommonPrefixOfVars(List<String> vars) {
String prefix = StringUtils.getCommonPrefix(vars.toArray(new String[vars.size()]));
// exclude trailing characters that should be part of a valid variable
// e.g. ["status-on", "status-off"] => "status-" (not "status-o")
return prefix.replaceAll("[a-zA-Z0-9]+\\z", "");
}
private String toEnumVarName(String value) {
private static String toEnumVarName(String value) {
String var = value.replaceAll("\\W+", "_").toUpperCase();
if (var.matches("\\d.*")) {
return "_" + var;
@@ -694,7 +695,7 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
}
}
private CodegenModel reconcileInlineEnums(CodegenModel codegenModel, CodegenModel parentCodegenModel) {
private static CodegenModel reconcileInlineEnums(CodegenModel codegenModel, CodegenModel parentCodegenModel) {
// This generator uses inline classes to define enums, which breaks when
// dealing with models that have subTypes. To clean this up, we will analyze
// the parent and child models, look for enums that match, and remove
@@ -778,8 +779,8 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
this.serializableModel = serializableModel;
}
private String sanitizePackageName(String packageName) {
packageName = packageName.trim();
private static String sanitizePackageName(String packageName) {
packageName = packageName.trim(); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
packageName = packageName.replaceAll("[^a-zA-Z0-9_\\.]", "_");
if(Strings.isNullOrEmpty(packageName)) {
return "invalidPackageName";

View File

@@ -11,7 +11,7 @@ import io.swagger.util.Yaml;
import java.util.*;
public class JavaInflectorServerCodegen extends JavaClientCodegen implements CodegenConfig {
public class JavaInflectorServerCodegen extends JavaClientCodegen {
protected String title = "Swagger Inflector";
public JavaInflectorServerCodegen() {
@@ -175,12 +175,15 @@ public class JavaInflectorServerCodegen extends JavaClientCodegen implements Cod
if (name.length() == 0) {
return "DefaultController";
}
name = name.replaceAll("[^a-zA-Z0-9]+", "_");
name = name.replaceAll("[^a-zA-Z0-9]+", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
return camelize(name)+ "Controller";
}
@Override
public boolean shouldOverwrite(String filename) {
return super.shouldOverwrite(filename);
return super.shouldOverwrite(filename) &&
!filename.endsWith("pom.xml") &&
!filename.endsWith("README.md") &&
!filename.endsWith("inflector.yaml");
}
}

View File

@@ -13,7 +13,6 @@ import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile;
import io.swagger.models.*;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.LongProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
import io.swagger.models.properties.RefProperty;
@@ -32,6 +31,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class JavascriptClientCodegen extends DefaultCodegen implements CodegenConfig {
@SuppressWarnings("hiding")
private static final Logger LOGGER = LoggerFactory.getLogger(JavascriptClientCodegen.class);
private static final String PROJECT_NAME = "projectName";
@@ -228,7 +228,7 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
@Override
public String toVarName(String name) {
// sanitize name
name = sanitizeName(name);
name = sanitizeName(name); // FIXME parameter should not be assigned. Also declare it as "final"
if("_".equals(name)) {
name = "_u";
@@ -259,7 +259,7 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
@Override
public String toModelName(String name) {
name = sanitizeName(name);
name = sanitizeName(name); // FIXME parameter should not be assigned. Also declare it as "final"
// model name cannot use reserved keyword, e.g. return
if (reservedWords.contains(name)) {
@@ -279,7 +279,7 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
@Override
public String toModelImport(String name) {
return name;
return toModelName(name);
}
@Override
@@ -290,8 +290,8 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
@Override
public String getTypeDeclaration(Property p) {
if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
// ArrayProperty ap = (ArrayProperty) p;
// Property inner = ap.getItems();
return getSwaggerType(p); // TODO: + "/* <" + getTypeDeclaration(inner) + "> */";
} else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
@@ -308,43 +308,22 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
return "[]";
} else if (p instanceof MapProperty) {
return "{}";
} else if (p instanceof LongProperty) {
LongProperty dp = (LongProperty) p;
if (dp.getDefault() != null) {
return dp.getDefault().toString()+"l";
}
return "null";
// added for Javascript
} else if (p instanceof RefProperty) {
RefProperty rp = (RefProperty)p;
return "new " +rp.getSimpleRef() + "()";
return "new " + getTypeDeclaration(p) + "()";
}
return super.toDefaultValue(p);
}
@Override
public String toDefaultValueWithParam(String name, Property p) {
if (p instanceof ArrayProperty) {
return " = new Array();";
} else if (p instanceof MapProperty) {
return " = {}";
} else if (p instanceof LongProperty) {
LongProperty dp = (LongProperty) p;
return " = data." + name + ";";
// added for Javascript
} else if (p instanceof RefProperty) {
RefProperty rp = (RefProperty)p;
if (p instanceof RefProperty) {
return ".constructFromObject(data." + name + ");";
}
return super.toDefaultValueWithParam(name, p);
}
@Override
public String getSwaggerType(Property p) {
String swaggerType = super.getSwaggerType(p);
@@ -385,7 +364,7 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
if (allDefinitions != null && codegenModel != null && codegenModel.parent != null && codegenModel.hasEnums) {
final Model parentModel = allDefinitions.get(toModelName(codegenModel.parent));
final CodegenModel parentCodegenModel = super.fromModel(codegenModel.parent, parentModel);
codegenModel = this.reconcileInlineEnums(codegenModel, parentCodegenModel);
codegenModel = JavascriptClientCodegen.reconcileInlineEnums(codegenModel, parentCodegenModel);
}
return codegenModel;
@@ -468,14 +447,14 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
&& !languageSpecificPrimitives.contains(type);
}
private String findCommonPrefixOfVars(List<String> vars) {
private static String findCommonPrefixOfVars(List<String> vars) {
String prefix = StringUtils.getCommonPrefix(vars.toArray(new String[vars.size()]));
// exclude trailing characters that should be part of a valid variable
// e.g. ["status-on", "status-off"] => "status-" (not "status-o")
return prefix.replaceAll("[a-zA-Z0-9]+\\z", "");
}
private String toEnumVarName(String value) {
private static String toEnumVarName(String value) {
String var = value.replaceAll("\\W+", "_").toUpperCase();
if (var.matches("\\d.*")) {
return "_" + var;
@@ -484,7 +463,7 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
}
}
private CodegenModel reconcileInlineEnums(CodegenModel codegenModel, CodegenModel parentCodegenModel) {
private static CodegenModel reconcileInlineEnums(CodegenModel codegenModel, CodegenModel parentCodegenModel) {
// This generator uses inline classes to define enums, which breaks when
// dealing with models that have subTypes. To clean this up, we will analyze
// the parent and child models, look for enums that match, and remove
@@ -532,7 +511,7 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
return codegenModel;
}
private String sanitizePackageName(String packageName) {
private static String sanitizePackageName(String packageName) { // FIXME parameter should not be assigned. Also declare it as "final"
packageName = packageName.trim();
packageName = packageName.replaceAll("[^a-zA-Z0-9_\\.]", "_");
if(Strings.isNullOrEmpty(packageName)) {

View File

@@ -8,7 +8,7 @@ import io.swagger.models.Swagger;
import java.io.File;
import java.util.*;
public class JaxRSServerCodegen extends JavaClientCodegen implements CodegenConfig {
public class JaxRSServerCodegen extends JavaClientCodegen {
protected String title = "Swagger Server";
protected String implFolder = "src/main/java";
@@ -74,11 +74,7 @@ public class JaxRSServerCodegen extends JavaClientCodegen implements CodegenConf
if(additionalProperties.containsKey(CodegenConstants.IMPL_FOLDER)) {
implFolder = (String) additionalProperties.get(CodegenConstants.IMPL_FOLDER);
}
// if("jersey2".equals(getLibrary())) {
// embeddedTemplateDir = templateDir = "JavaJaxRS" + File.separator + "jersey2";
// }
supportingFiles.clear();
supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml"));
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
@@ -157,7 +153,7 @@ public class JaxRSServerCodegen extends JavaClientCodegen implements CodegenConf
}
}
this.additionalProperties.put("serverPort", port);
if(swagger != null && swagger.getPaths() != null) {
if(swagger.getPaths() != null) {
for(String pathname : swagger.getPaths().keySet()) {
Path path = swagger.getPath(pathname);
if(path.getOperations() != null) {
@@ -233,7 +229,7 @@ public class JaxRSServerCodegen extends JavaClientCodegen implements CodegenConf
if (name.length() == 0) {
return "DefaultApi";
}
name = sanitizeName(name);
name = sanitizeName(name);
return camelize(name) + "Api";
}

View File

@@ -212,7 +212,7 @@ public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig
}
@SuppressWarnings("unchecked")
private List<Map<String, Object>> getOperations(Map<String, Object> objs) {
private static List<Map<String, Object>> getOperations(Map<String, Object> objs) {
List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
Map<String, Object> apiInfo = (Map<String, Object>) objs.get("apiInfo");
List<Map<String, Object>> apis = (List<Map<String, Object>>) apiInfo.get("apis");
@@ -222,7 +222,7 @@ public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig
return result;
}
private List<Map<String, Object>> sortOperationsByPath(List<CodegenOperation> ops) {
private static List<Map<String, Object>> sortOperationsByPath(List<CodegenOperation> ops) {
Multimap<String, CodegenOperation> opsByPath = ArrayListMultimap.create();
for (CodegenOperation op : ops) {

View File

@@ -219,12 +219,8 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
@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;
@@ -312,7 +308,7 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
@Override
public String toModelName(String type) {
type = type.replaceAll("[^0-9a-zA-Z_]", "_");
type = type.replaceAll("[^0-9a-zA-Z_]", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
// language build-in classes
if (typeMapping.keySet().contains(type) ||
@@ -372,7 +368,7 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
@Override
public String toVarName(String name) {
// sanitize name
name = sanitizeName(name);
name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
// if it's all upper case, do noting
if (name.matches("^[A-Z_]$")) {
@@ -409,6 +405,7 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
return "_" + name;
}
@SuppressWarnings("static-method")
public String escapeSpecialWord(String name) {
return "var_" + name;
}

View File

@@ -7,7 +7,6 @@ import io.swagger.codegen.SupportingFile;
import io.swagger.codegen.CodegenConstants;
import io.swagger.codegen.CliOption;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.BooleanProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
@@ -185,14 +184,13 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig {
public String toVarName(String name) {
// return the name in underscore style
// PhoneNumber => phone_number
name = underscore(name);
name = underscore(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
// parameter name starting with number won't compile
// need to escape it by appending _ at the beginning
if (name.matches("^\\d.*")) {
name = "_" + name;
}
return name;
}
@@ -223,7 +221,7 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig {
@Override
public String toApiFilename(String name) {
// replace - with _ e.g. created-at => created_at
name = name.replaceAll("-", "_");
name = name.replaceAll("-", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
// e.g. phone_number_api.rb => PhoneNumberApi.rb
return camelize(name) + "Api";

View File

@@ -20,6 +20,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig {
@SuppressWarnings("hiding")
static Logger LOGGER = LoggerFactory.getLogger(PhpClientCodegen.class);
public static final String VARIABLE_NAMING_CONVENTION = "variableNamingConvention";
@@ -119,9 +120,9 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig {
}
public String toPackagePath(String packageName, String basePath) {
packageName = packageName.replace(invokerPackage, "");
packageName = packageName.replace(invokerPackage, ""); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
if (basePath != null && basePath.length() > 0) {
basePath = basePath.replaceAll("[\\\\/]?$", "") + File.separatorChar;
basePath = basePath.replaceAll("[\\\\/]?$", "") + File.separatorChar; // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
}
String regFirstPathSeparator;
@@ -326,7 +327,7 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig {
@Override
public String toVarName(String name) {
// sanitize name
name = sanitizeName(name);
name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
if ("camelCase".equals(variableNamingConvention)) {
// return the name in camelCase style
@@ -356,7 +357,7 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig {
@Override
public String toModelName(String name) {
// Note: backslash ("\\") is allowed for e.g. "\\DateTime"
name = name.replaceAll("[^\\w\\\\]+", "_");
name = name.replaceAll("[^\\w\\\\]+", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
// remove dollar sign
name = name.replaceAll("$", "");

View File

@@ -179,7 +179,7 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig
@Override
public String toVarName(String name) {
// sanitize name
name = sanitizeName(name);
name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
// remove dollar sign
name = name.replaceAll("$", "");
@@ -212,7 +212,7 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig
@Override
public String toModelName(String name) {
name = sanitizeName(name);
name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
// remove dollar sign
name = name.replaceAll("$", "");
@@ -294,6 +294,7 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig
* (PEP 0008) Python packages should also have short, all-lowercase names,
* although the use of underscores is discouraged.
*/
@SuppressWarnings("static-method")
public String generatePackageName(String packageName) {
return underscore(packageName.replaceAll("[^\\w]+", ""));
}

View File

@@ -187,7 +187,6 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig {
supportingFiles.add(new SupportingFile("api_error.mustache", gemFolder, "api_error.rb"));
supportingFiles.add(new SupportingFile("configuration.mustache", gemFolder, "configuration.rb"));
supportingFiles.add(new SupportingFile("version.mustache", gemFolder, "version.rb"));
String modelFolder = gemFolder + File.separator + modelPackage.replace("/", File.separator);
}
@@ -209,6 +208,7 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig {
/**
* Generate Ruby module name from the gem name, e.g. use "SwaggerClient" for "swagger_client".
*/
@SuppressWarnings("static-method")
public String generateModuleName(String gemName) {
return camelize(gemName.replaceAll("[^\\w]+", "_"));
}
@@ -216,6 +216,7 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig {
/**
* Generate Ruby gem name from the module name, e.g. use "swagger_client" for "SwaggerClient".
*/
@SuppressWarnings("static-method")
public String generateGemName(String moduleName) {
return underscore(moduleName.replaceAll("[^\\w]+", ""));
}
@@ -307,7 +308,7 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig {
@Override
public String toVarName(String name) {
// sanitize name
name = sanitizeName(name);
name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
// if it's all uppper case, convert to lower case
if (name.matches("^[A-Z_]*$")) {
@@ -334,7 +335,7 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig {
@Override
public String toModelName(String name) {
name = sanitizeName(name);
name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
// model name cannot use reserved keyword, e.g. return
if (reservedWords.contains(name)) {
@@ -361,7 +362,7 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig {
@Override
public String toApiFilename(String name) {
// replace - with _ e.g. created-at => created_at
name = name.replaceAll("-", "_");
name = name.replaceAll("-", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
// e.g. PhoneNumberApi.rb => phone_number_api.rb
return underscore(name) + "_api";

View File

@@ -165,7 +165,7 @@ public class SilexServerCodegen extends DefaultCodegen implements CodegenConfig
public String toVarName(String name) {
// return the name in underscore style
// PhoneNumber => phone_number
name = underscore(name);
name = underscore(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
// parameter name starting with number won't compile
// need to escape it by appending _ at the beginning

View File

@@ -2,7 +2,6 @@ package io.swagger.codegen.languages;
import com.fasterxml.jackson.core.JsonProcessingException;
import io.swagger.codegen.CliOption;
import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen;
@@ -18,8 +17,6 @@ import java.util.Arrays;
import java.util.HashSet;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
public class SinatraServerCodegen extends DefaultCodegen implements CodegenConfig {
protected String gemName;
protected String moduleName;
@@ -149,7 +146,7 @@ public class SinatraServerCodegen extends DefaultCodegen implements CodegenConfi
@Override
public String toVarName(String name) {
// replace - with _ e.g. created-at => created_at
name = name.replaceAll("-", "_");
name = name.replaceAll("-", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
// if it's all uppper case, convert to lower case
if (name.matches("^[A-Z_]*$")) {
@@ -201,7 +198,7 @@ public class SinatraServerCodegen extends DefaultCodegen implements CodegenConfi
@Override
public String toApiFilename(String name) {
// replace - with _ e.g. created-at => created_at
name = name.replaceAll("-", "_");
name = name.replaceAll("-", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
// e.g. PhoneNumberApi.rb => phone_number_api.rb
return underscore(name) + "_api";

View File

@@ -180,8 +180,7 @@ public class SlimFrameworkServerCodegen extends DefaultCodegen implements Codege
@Override
public String toVarName(String name) {
// sanitize name
name = sanitizeName(name);
name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
if ("camelCase".equals(variableNamingConvention)) {
// return the name in camelCase style

View File

@@ -6,7 +6,7 @@ import io.swagger.models.Operation;
import java.io.File;
import java.util.*;
public class SpringMVCServerCodegen extends JavaClientCodegen implements CodegenConfig {
public class SpringMVCServerCodegen extends JavaClientCodegen {
public static final String CONFIG_PACKAGE = "configPackage";
protected String title = "Petstore Server";
protected String configPackage = "";

View File

@@ -270,6 +270,7 @@ public class SwiftCodegen extends DefaultCodegen implements CodegenConfig {
return codegenProperty;
}
@SuppressWarnings("static-method")
public String toSwiftyEnumName(String value) {
// Prevent from breaking properly cased identifier
if (value.matches("[A-Z][a-z0-9]+[a-zA-Z0-9]*")) {
@@ -289,7 +290,7 @@ public class SwiftCodegen extends DefaultCodegen implements CodegenConfig {
@Override
public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map<String, Model> definitions, Swagger swagger) {
path = normalizePath(path);
path = normalizePath(path); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
List<Parameter> parameters = operation.getParameters();
parameters = Lists.newArrayList(Iterators.filter(parameters.iterator(), new Predicate<Parameter>() {
@Override

View File

@@ -131,12 +131,8 @@ public class TizenClientCodegen extends DefaultCodegen implements CodegenConfig
@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;
@@ -220,12 +216,8 @@ public class TizenClientCodegen extends DefaultCodegen implements CodegenConfig
} else if (p instanceof DecimalProperty) {
return "new Long()";
} else if (p instanceof MapProperty) {
MapProperty ap = (MapProperty) p;
String inner = getSwaggerType(ap.getAdditionalProperties());
return "new HashMap()";
} else if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
String inner = getSwaggerType(ap.getItems());
return "new ArrayList()";
}
// else

View File

@@ -452,34 +452,51 @@ public class ApiClient {
}
}
private ClientResponse getAPIResponse(String path, String method, List<Pair> queryParams, Object body, Map<String, String> headerParams, Map<String, Object> formParams, String accept, String contentType, String[] authNames) throws ApiException {
/**
* Build full URL by concatenating base path, the given sub path and query parameters.
*
* @param path The sub path
* @param queryParams The query parameters
* @return The full URL
*/
private String buildUrl(String path, List<Pair> queryParams) {
final StringBuilder url = new StringBuilder();
url.append(basePath).append(path);
if (body != null && !formParams.isEmpty()){
if (queryParams != null && !queryParams.isEmpty()) {
// support (constant) query string in `path`, e.g. "/posts?draft=1"
String prefix = path.contains("?") ? "&" : "?";
for (Pair param : queryParams) {
if (param.getValue() != null) {
if (prefix != null) {
url.append(prefix);
prefix = null;
} else {
url.append("&");
}
String value = parameterToString(param.getValue());
url.append(escapeString(param.getName())).append("=").append(escapeString(value));
}
}
}
return url.toString();
}
private ClientResponse getAPIResponse(String path, String method, List<Pair> queryParams, Object body, Map<String, String> headerParams, Map<String, Object> formParams, String accept, String contentType, String[] authNames) throws ApiException {
if (body != null && !formParams.isEmpty()) {
throw new ApiException(500, "Cannot have body and form params");
}
updateParamsForAuth(authNames, queryParams, headerParams);
StringBuilder b = new StringBuilder();
b.append("?");
if (queryParams != null){
for (Pair queryParam : queryParams){
if (!queryParam.getName().isEmpty()) {
b.append(escapeString(queryParam.getName()));
b.append("=");
b.append(escapeString(queryParam.getValue()));
b.append("&");
}
}
}
String querystring = b.substring(0, b.length() - 1);
final String url = buildUrl(path, queryParams);
Builder builder;
if (accept == null)
builder = httpClient.resource(basePath + path + querystring).getRequestBuilder();
else
builder = httpClient.resource(basePath + path + querystring).accept(accept);
if (accept == null) {
builder = httpClient.resource(url).getRequestBuilder();
} else {
builder = httpClient.resource(url).accept(accept);
}
for (String key : headerParams.keySet()) {
builder = builder.header(key, headerParams.get(key));

View File

@@ -495,7 +495,9 @@ public class ApiClient {
public <T> T invokeAPI(String path, String method, List<Pair> queryParams, Object body, Map<String, String> headerParams, Map<String, Object> formParams, String accept, String contentType, String[] authNames, GenericType<T> returnType) throws ApiException {
updateParamsForAuth(authNames, queryParams, headerParams);
WebTarget target = httpClient.target(this.basePath).path(path);
// Not using `.target(this.basePath).path(path)` below,
// to support (constant) query string in `path`, e.g. "/posts?draft=1"
WebTarget target = httpClient.target(this.basePath + path);
if (queryParams != null) {
for (Pair queryParam : queryParams) {

View File

@@ -657,8 +657,8 @@ public class ApiClient {
}
/**
* Deserialize response body to Java object, according to the Content-Type
* response header.
* Deserialize response body to Java object, according to the return type and
* the Content-Type response header.
*
* @param response HTTP response
* @param returnType The type of the Java object
@@ -667,12 +667,21 @@ public class ApiClient {
* or the Content-Type of the response is not supported.
*/
public <T> T deserialize(Response response, Type returnType) throws ApiException {
if (response == null || returnType == null)
if (response == null || returnType == null) {
return null;
}
// Handle file downloading.
if (returnType.equals(File.class))
if ("byte[]".equals(returnType.toString())) {
// Handle binary response (byte array).
try {
return (T) response.body().bytes();
} catch (IOException e) {
throw new ApiException(e);
}
} else if (returnType.equals(File.class)) {
// Handle file downloading.
return (T) downloadFileFromResponse(response);
}
String respBody;
try {
@@ -684,8 +693,9 @@ public class ApiClient {
throw new ApiException(e);
}
if (respBody == null || "".equals(respBody))
if (respBody == null || "".equals(respBody)) {
return null;
}
String contentType = response.headers().get("Content-Type");
if (contentType == null) {
@@ -707,20 +717,29 @@ public class ApiClient {
}
/**
* Serialize the given Java object into request body string, according to the
* request Content-Type.
* Serialize the given Java object into request body according to the object's
* class and the request Content-Type.
*
* @param obj The Java object
* @param contentType The request Content-Type
* @return The serialized string
* @return The serialized request body
* @throws ApiException If fail to serialize the given object
*/
public String serialize(Object obj, String contentType) throws ApiException {
if (isJsonMime(contentType)) {
if (obj != null)
return json.serialize(obj);
else
return null;
public RequestBody serialize(Object obj, String contentType) throws ApiException {
if (obj instanceof byte[]) {
// Binary (byte array) body parameter support.
return RequestBody.create(MediaType.parse(contentType), (byte[]) obj);
} else if (obj instanceof File) {
// File body parameter support.
return RequestBody.create(MediaType.parse(contentType), (File) obj);
} else if (isJsonMime(contentType)) {
String content;
if (obj != null) {
content = json.serialize(obj);
} else {
content = null;
}
return RequestBody.create(MediaType.parse(contentType), content);
} else {
throw new ApiException("Content type \"" + contentType + "\" is not supported");
}
@@ -909,7 +928,7 @@ public class ApiClient {
reqBody = RequestBody.create(MediaType.parse(contentType), "");
}
} else {
reqBody = RequestBody.create(MediaType.parse(contentType), serialize(body, contentType));
reqBody = serialize(body, contentType);
}
Request request = null;
@@ -932,20 +951,27 @@ public class ApiClient {
* @return The full URL
*/
public String buildUrl(String path, List<Pair> queryParams) {
StringBuilder query = new StringBuilder();
if (queryParams != null) {
final StringBuilder url = new StringBuilder();
url.append(basePath).append(path);
if (queryParams != null && !queryParams.isEmpty()) {
// support (constant) query string in `path`, e.g. "/posts?draft=1"
String prefix = path.contains("?") ? "&" : "?";
for (Pair param : queryParams) {
if (param.getValue() != null) {
if (query.toString().length() == 0)
query.append("?");
else
query.append("&");
if (prefix != null) {
url.append(prefix);
prefix = null;
} else {
url.append("&");
}
String value = parameterToString(param.getValue());
query.append(escapeString(param.getName())).append("=").append(escapeString(value));
url.append(escapeString(param.getName())).append("=").append(escapeString(value));
}
}
}
return basePath + path + query.toString();
return url.toString();
}
/**

View File

@@ -8,7 +8,6 @@ import {{modelPackage}}.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import io.swagger.annotations.Authorization;
import io.swagger.annotations.AuthorizationScope;
@@ -44,8 +43,8 @@ public class {{classname}} {
}{{/isOAuth}}){{#hasMore}},
{{/hasMore}}{{/authMethods}}
}{{/hasAuthMethods}})
@ApiResponses(value = { {{#responses}}
@ApiResponse(code = {{{code}}}, message = "{{{message}}}"){{#hasMore}},{{/hasMore}}{{/responses}} })
@io.swagger.annotations.ApiResponses(value = { {{#responses}}
@io.swagger.annotations.ApiResponse(code = {{{code}}}, message = "{{{message}}}"){{#hasMore}},{{/hasMore}}{{/responses}} })
@RequestMapping(value = "{{path}}",
{{#hasProduces}}produces = { {{#produces}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }, {{/hasProduces}}
{{#hasConsumes}}consumes = { {{#consumes}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} },{{/hasConsumes}}

View File

@@ -75,31 +75,6 @@
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j-version}</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-core</artifactId>
<version>${jersey-version}</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-json</artifactId>
<version>${jersey-version}</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-servlet</artifactId>
<version>${jersey-version}</version>
</dependency>
<dependency>
<groupId>com.sun.jersey.contribs</groupId>
<artifactId>jersey-multipart</artifactId>
<version>${jersey-version}</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-server</artifactId>
<version>${jersey-version}</version>
</dependency>
<!--Spring dependencies -->
<dependency>
@@ -142,22 +117,14 @@
<version>${servlet-api-version}</version>
</dependency>
</dependencies>
<repositories>
<repository>
<id>jcenter-snapshots</id>
<name>jcenter</name>
<url>http://oss.jfrog.org/artifactory/oss-snapshot-local/</url>
</repository>
</repositories>
<properties>
<swagger-core-version>1.5.4</swagger-core-version>
<swagger-core-version>1.5.6</swagger-core-version>
<jetty-version>9.2.9.v20150224</jetty-version>
<jersey-version>1.13</jersey-version>
<slf4j-version>1.6.3</slf4j-version>
<scala-test-version>1.6.1</scala-test-version>
<junit-version>4.8.1</junit-version>
<servlet-api-version>2.5</servlet-api-version>
<springfox-version>2.0.4-SNAPSHOT</springfox-version>
<spring-version>4.0.9.RELEASE</spring-version>
<springfox-version>2.3.1</springfox-version>
<spring-version>4.1.8.RELEASE</spring-version>
</properties>
</project>

View File

@@ -4,6 +4,7 @@ io.swagger.codegen.languages.CSharpClientCodegen
io.swagger.codegen.languages.DartClientCodegen
io.swagger.codegen.languages.FlashClientCodegen
io.swagger.codegen.languages.FlaskConnexionCodegen
io.swagger.codegen.languages.GoClientCodegen
io.swagger.codegen.languages.JavaClientCodegen
io.swagger.codegen.languages.JavascriptClientCodegen
io.swagger.codegen.languages.JaxRSServerCodegen

View File

@@ -17,9 +17,12 @@ import com.android.volley.VolleyError;
import org.apache.http.HttpEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import java.util.Map;
import java.util.ArrayList;
import java.util.HashMap;
import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
{{#operations}}
public class {{classname}} {
@@ -44,11 +47,93 @@ public class {{classname}} {
{{#operation}}
/**
* {{summary}}
* {{notes}}
* {{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 TimeoutException, ExecutionException, InterruptedException, ApiException {
Object postBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}};
{{#allParams}}{{#required}}
// verify the required parameter '{{paramName}}' is set
if ({{paramName}} == null) {
VolleyError error = new VolleyError("Missing the required parameter '{{paramName}}' when calling {{nickname}}",
new ApiException(400, "Missing the required parameter '{{paramName}}' when calling {{nickname}}"));
}
{{/required}}{{/allParams}}
// create path and map variables
String path = "{{path}}".replaceAll("\\{format\\}","json"){{#pathParams}}.replaceAll("\\{" + "{{baseName}}" + "\\}", apiInvoker.escapeString({{{paramName}}}.toString())){{/pathParams}};
// query params
List<Pair> queryParams = new ArrayList<Pair>();
// header params
Map<String, String> headerParams = new HashMap<String, String>();
// form params
Map<String, String> formParams = new HashMap<String, String>();
{{#queryParams}}
queryParams.addAll(ApiInvoker.parameterToPairs("{{#collectionFormat}}{{{collectionFormat}}}{{/collectionFormat}}", "{{baseName}}", {{paramName}}));
{{/queryParams}}
{{#headerParams}}
headerParams.put("{{baseName}}", ApiInvoker.parameterToString({{paramName}}));
{{/headerParams}}
String[] contentTypes = {
{{#consumes}}"{{mediaType}}"{{#hasMore}},{{/hasMore}}{{/consumes}}
};
String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json";
if (contentType.startsWith("multipart/form-data")) {
// file uploading
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
{{#formParams}}{{#notFile}}
if ({{paramName}} != null) {
builder.addTextBody("{{baseName}}", ApiInvoker.parameterToString({{paramName}}), ApiInvoker.TEXT_PLAIN_UTF8);
}
{{/notFile}}{{#isFile}}
if ({{paramName}} != null) {
builder.addBinaryBody("{{baseName}}", {{paramName}});
}
{{/isFile}}{{/formParams}}
HttpEntity httpEntity = builder.build();
postBody = httpEntity;
} else {
// normal form params
{{#formParams}}{{#notFile}}formParams.put("{{baseName}}", ApiInvoker.parameterToString({{paramName}}));{{/notFile}}
{{/formParams}}
}
String[] authNames = new String[] { {{#authMethods}}"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}} };
try {
String response = apiInvoker.invokeAPI (basePath, path, "{{httpMethod}}", queryParams, postBody, headerParams, formParams, contentType, authNames);
if(response != null){
return {{#returnType}}({{{returnType}}}) ApiInvoker.deserialize(response, "{{returnContainer}}", {{returnBaseType}}.class){{/returnType}};
} else {
return {{#returnType}}null{{/returnType}};
}
} catch (ApiException ex) {
throw ex;
} catch (InterruptedException ex) {
throw ex;
} catch (ExecutionException ex) {
if(ex.getCause() instanceof VolleyError) {
throw new ApiException(((VolleyError) ex.getCause()).networkResponse.statusCode, ((VolleyError) ex.getCause()).getMessage());
}
throw ex;
} catch (TimeoutException ex) {
throw ex;
}
}
/**
* {{summary}}
* {{notes}}
{{#allParams}} * @param {{paramName}} {{description}}{{/allParams}}
*/
public void {{nickname}} ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{^hasMore}}, {{/hasMore}}{{/allParams}}final Response.Listener<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}String{{/returnType}}> responseListener, final Response.ErrorListener errorListener) {
Object postBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}};

View File

@@ -1,10 +1,16 @@
package {{invokerPackage}};
import android.content.Context;
import com.android.volley.Cache;
import com.android.volley.Network;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.Volley;
import com.android.volley.ResponseDelivery;
import com.android.volley.toolbox.BasicNetwork;
import com.android.volley.toolbox.HttpStack;
import com.android.volley.toolbox.HurlStack;
import com.android.volley.toolbox.NoCache;
import com.android.volley.toolbox.RequestFuture;
import com.google.gson.JsonParseException;
import org.apache.http.Consts;
@@ -22,6 +28,9 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import {{invokerPackage}}.auth.Authentication;
import {{invokerPackage}}.auth.ApiKeyAuth;
@@ -36,11 +45,12 @@ public class ApiInvoker {
private static ApiInvoker INSTANCE;
private Map<String, String> defaultHeaderMap = new HashMap<String, String>();
private Context context;
private RequestQueue mRequestQueue;
private Map<String, Authentication> authentications;
private int connectionTimeout;
/** Content type "text/plain" with UTF-8 encoding. */
public static final ContentType TEXT_PLAIN_UTF8 = ContentType.create("text/plain", Consts.UTF_8);
@@ -165,8 +175,16 @@ public class ApiInvoker {
return params;
}
public static void initializeInstance(Context context) {
INSTANCE = new ApiInvoker(context);
public static void initializeInstance() {
initializeInstance(null);
}
public static void initializeInstance(Cache cache) {
initializeInstance(cache, null, 0, null, 30);
}
public static void initializeInstance(Cache cache, Network network, int threadPoolSize, ResponseDelivery delivery, int connectionTimeout) {
INSTANCE = new ApiInvoker(cache, network, threadPoolSize, delivery, connectionTimeout);
setUserAgent("Android-Volley-Swagger");
// Setup authentications (key: authentication name, value: authentication).
@@ -178,17 +196,27 @@ public class ApiInvoker {
{{#isBasic}}
INSTANCE.authentications.put("{{name}}", new HttpBasicAuth());
{{/isBasic}}
{{#isOAuth}}
INSTANCE.authentications.put("{{name}}", new OAuth());
{{/isOAuth}}
{{/authMethods}}
// Prevent the authentications from being modified.
INSTANCE.authentications = Collections.unmodifiableMap(INSTANCE.authentications);
}
private ApiInvoker(Context context) {
this.context = context;
initConnectionManager();
}
public ApiInvoker() {
initConnectionManager();
private ApiInvoker(Cache cache, Network network, int threadPoolSize, ResponseDelivery delivery, int connectionTimeout) {
if(cache == null) cache = new NoCache();
if(network == null) {
HttpStack stack = new HurlStack();
network = new BasicNetwork(stack);
}
if(delivery == null) {
initConnectionRequest(cache, network);
} else {
initConnectionRequest(cache, network, threadPoolSize, delivery);
}
this.connectionTimeout = connectionTimeout;
}
public static ApiInvoker getInstance() {
@@ -304,6 +332,14 @@ public class ApiInvoker {
throw new RuntimeException("No API key authentication configured!");
}
public void setConnectionTimeout(int connectionTimeout){
this.connectionTimeout = connectionTimeout;
}
public int getConnectionTimeout() {
return connectionTimeout;
}
/**
* Update query and header parameters based on authentication settings.
*
@@ -317,7 +353,21 @@ public class ApiInvoker {
}
}
public String invokeAPI(String host, String path, String method, List<Pair> queryParams, Object body, Map<String, String> headerParams, Map<String, String> formParams, String contentType, String[] authNames) throws ApiException, InterruptedException, ExecutionException, TimeoutException {
RequestFuture<String> future = RequestFuture.newFuture();
Request request = createRequest(host, path, method, queryParams, body, headerParams, formParams, contentType, authNames, future, future);
if(request != null) {
mRequestQueue.add(request);
return future.get(connectionTimeout, TimeUnit.SECONDS);
} else return "no data";
}
public void invokeAPI(String host, String path, String method, List<Pair> queryParams, Object body, Map<String, String> headerParams, Map<String, String> formParams, String contentType, String[] authNames, Response.Listener<String> stringRequest, Response.ErrorListener errorListener) throws ApiException {
Request request = createRequest(host, path, method, queryParams, body, headerParams, formParams, contentType, authNames, stringRequest, errorListener);
if (request != null) mRequestQueue.add(request);
}
public Request<String> createRequest(String host, String path, String method, List<Pair> queryParams, Object body, Map<String, String> headerParams, Map<String, String> formParams, String contentType, String[] authNames, Response.Listener<String> stringRequest, Response.ErrorListener errorListener) throws ApiException {
StringBuilder b = new StringBuilder();
b.append("?");
@@ -374,13 +424,13 @@ public class ApiInvoker {
}
formParamStr = formParamBuilder.toString();
}
Request request = null;
if ("GET".equals(method)) {
GetRequest request = new GetRequest(url, headers, null, stringRequest, errorListener);
mRequestQueue.add(request);
request = new GetRequest(url, headers, null, stringRequest, errorListener);
}
else if ("POST".equals(method)) {
PostRequest request = null;
request = null;
if (formParamStr != null) {
request = new PostRequest(url, headers, contentType, new StringEntity(formParamStr, "UTF-8"), stringRequest, errorListener);
} else if (body != null) {
@@ -389,11 +439,12 @@ public class ApiInvoker {
} else {
request = new PostRequest(url, headers, contentType, new StringEntity(serialize(body), "UTF-8"), stringRequest, errorListener);
}
} else {
request = new PostRequest(url, headers, null, null, stringRequest, errorListener);
}
if(request != null) mRequestQueue.add(request);
}
else if ("PUT".equals(method)) {
PutRequest request = null;
request = null;
if (formParamStr != null) {
request = new PutRequest(url, headers, contentType, new StringEntity(formParamStr, "UTF-8"), stringRequest, errorListener);
} else if (body != null) {
@@ -402,11 +453,12 @@ public class ApiInvoker {
} else {
request = new PutRequest(url, headers, contentType, new StringEntity(serialize(body), "UTF-8"), stringRequest, errorListener);
}
} else {
request = new PutRequest(url, headers, null, null, stringRequest, errorListener);
}
if(request != null) mRequestQueue.add(request);
}
else if ("DELETE".equals(method)) {
DeleteRequest request = null;
request = null;
if (formParamStr != null) {
request = new DeleteRequest(url, headers, contentType, new StringEntity(formParamStr, "UTF-8"), stringRequest, errorListener);
} else if (body != null) {
@@ -415,11 +467,12 @@ public class ApiInvoker {
} else {
request = new DeleteRequest(url, headers, contentType, new StringEntity(serialize(body), "UTF-8"), stringRequest, errorListener);
}
} else {
request = new DeleteRequest(url, headers, null, null, stringRequest, errorListener);
}
if(request != null) mRequestQueue.add(request);
}
else if ("PATCH".equals(method)) {
PatchRequest request = null;
request = null;
if (formParamStr != null) {
request = new PatchRequest(url, headers, contentType, new StringEntity(formParamStr, "UTF-8"), stringRequest, errorListener);
} else if (body != null) {
@@ -428,12 +481,24 @@ public class ApiInvoker {
} else {
request = new PatchRequest(url, headers, contentType, new StringEntity(serialize(body), "UTF-8"), stringRequest, errorListener);
}
}
if(request != null) mRequestQueue.add(request);
} else {
request = new PatchRequest(url, headers, null, null, stringRequest, errorListener);
}
}
return request;
}
private void initConnectionManager() {
mRequestQueue = Volley.newRequestQueue(context);
private void initConnectionRequest(Cache cache, Network network) {
mRequestQueue = new RequestQueue(cache, network);
mRequestQueue.start();
}
private void initConnectionRequest(Cache cache, Network network, int threadPoolSize, ResponseDelivery delivery) {
mRequestQueue = new RequestQueue(cache, network, threadPoolSize, delivery);
mRequestQueue.start();
}
public void stopQueue() {
mRequestQueue.stop();
}
}

View File

@@ -44,6 +44,9 @@ public class ApiKeyAuth implements Authentication {
@Override
public void applyToParams(List<Pair> queryParams, Map<String, String> headerParams) {
String value;
if (apiKey == null) {
return;
}
if (apiKeyPrefix != null) {
value = apiKeyPrefix + " " + apiKey;
} else {

View File

@@ -0,0 +1,13 @@
package {{invokerPackage}}.auth;
import {{invokerPackage}}.Pair;
import java.util.Map;
import java.util.List;
public class OAuth implements Authentication {
@Override
public void applyToParams(List<Pair> queryParams, Map<String, String> headerParams) {
// TODO stub
}
}

View File

@@ -49,6 +49,10 @@ android {
}
}
}
testOptions {
unitTests.returnDefaultValues = true
}
}
@@ -58,6 +62,8 @@ ext {
httpclient_version = "4.3.3"
volley_version = "1.0.19"
junit_version = "4.8.1"
robolectric_version = "3.0"
concurrent_unit_version = "0.4.2"
}
dependencies {
@@ -67,6 +73,8 @@ dependencies {
compile "org.apache.httpcomponents:httpmime:$httpclient_version"
compile "com.mcxiaoke.volley:library:${volley_version}@aar"
testCompile "junit:junit:$junit_version"
testCompile "org.robolectric:robolectric:${robolectric_version}"
testCompile "net.jodah:concurrentunit:${concurrentunitVersion}"
}
afterEvaluate {

View File

@@ -0,0 +1,58 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{{packageGuid}}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>{{packageTitle}}</RootNamespace>
<AssemblyName>{{packageTitle}}</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Net.Http.WebRequest" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Runtime.Serialization" />
<Reference Include="System.Xml" />
<Reference Include="Newtonsoft.Json">
<SpecificVersion>False</SpecificVersion>
<HintPath>{{binRelativePath}}Newtonsoft.Json.dll</HintPath>
</Reference>
<Reference Include="RestSharp">
<HintPath>{{binRelativePath}}RestSharp.dll</HintPath>
</Reference>
</ItemGroup>
<ItemGroup>
<Compile Include="Properties\AssemblyInfo.cs"/>
<Compile Include="Api\*.cs"/>
<Compile Include="Client\*.cs"/>
<Compile Include="Model\*.cs"/>
</ItemGroup>
<Import Project="$(MsBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>

View File

@@ -3,25 +3,26 @@
## Overview
This server was generated by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. By using the
[OpenAPI-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 flask server.
is an example of building a swagger-enabled Flask server.
This example uses the [connexion](https://github.com/zalando/connexion) library on top of Flask.
This example uses the [Connexion](https://github.com/zalando/connexion) library on top of Flask.
To run the server, please execute the following:
```
sudo pip3 install -U connexion # install Connexion from PyPI
python3 app.py
```
and open your browser to here:
```
http://localhost:{{serverPort}}/ui
http://localhost:{{serverPort}}{{contextPath}}/ui/
```
Your swagger definition lives here:
Your Swagger definition lives here:
```
http://localhost:{{serverPort}}{{basePathWithoutHost}}/swagger.json
http://localhost:{{serverPort}}{{contextPath}}/swagger.json
```

View File

@@ -3,7 +3,6 @@
import connexion
if __name__ == '__main__':
app = connexion.App(__name__, {{serverPort}},
specification_dir='./swagger/')
app = connexion.App(__name__, specification_dir='./swagger/')
app.add_api('swagger.yaml', arguments={'title': '{{appDescription}}'})
app.run()
app.run(port={{serverPort}})

View File

@@ -0,0 +1,12 @@
# Go API client for {{packageName}}
## Overview
This API client 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-spec) from a remote server, you can easily generate an API client.
## Installation
Put the package under your project folder and add the following in import:
```
"./{{packageName}}"
```

View File

@@ -0,0 +1,83 @@
package {{packageName}}
{{#operations}}
import (
"strings"
"fmt"
"github.com/dghubble/sling"
{{#imports}} "{{import}}"
{{/imports}}
)
type {{classname}} struct {
basePath string
}
func New{{classname}}() *{{classname}}{
return &{{classname}} {
basePath: "{{basePath}}",
}
}
func New{{classname}}WithBasePath(basePath string) *{{classname}}{
return &{{classname}} {
basePath: basePath,
}
}
{{#operation}}
/**
* {{summary}}
* {{notes}}
{{#allParams}} * @param {{paramName}} {{description}}
{{/allParams}} * @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}}
*/
//func (a {{classname}}) {{nickname}} ({{#allParams}}{{paramName}} {{{dataType}}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) ({{#returnType}}{{{returnType}}}, {{/returnType}}error) {
func (a {{classname}}) {{nickname}} ({{#allParams}}{{paramName}} {{{dataType}}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) ({{#returnType}}{{{returnType}}}, {{/returnType}}error) {
_sling := sling.New().{{httpMethod}}(a.basePath)
// create path and map variables
path := "{{basePathWithoutHost}}{{path}}"
{{#pathParams}} path = strings.Replace(path, "{" + "{{baseName}}" + "}", fmt.Sprintf("%v", {{paramName}}), -1)
{{/pathParams}}
_sling = _sling.Path(path)
{{#hasQueryParams}} type QueryParams struct {
{{#queryParams}}{{paramName}} {{dataType}} `url:"{{baseName}},omitempty"`
{{/queryParams}}
}
_sling = _sling.QueryStruct(&QueryParams{ {{#queryParams}}{{paramName}}: {{paramName}}{{#hasMore}},{{/hasMore}}{{/queryParams}} })
{{/hasQueryParams}}
// accept header
accepts := []string { {{#produces}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }
for key := range accepts {
_sling = _sling.Set("Accept", accepts[key])
break // only use the first Accept
}
{{#hasHeaderParams}}{{#headerParams}} // header params "{{baseName}}"
_sling = _sling.Set("{{baseName}}", {{paramName}})
{{/headerParams}}{{/hasHeaderParams}}
{{#hasFormParams}} type FormParams struct {
{{#formParams}} {{paramName}} {{dataType}} `url:"{{baseName}},omitempty"`
{{/formParams}}
}
_sling = _sling.BodyForm(&FormParams{ {{#formParams}}{{paramName}}: {{paramName}}{{#hasMore}},{{/hasMore}}{{/formParams}} })
{{/hasFormParams}}
{{#hasBodyParam}}{{#bodyParams}}// body params
_sling = _sling.BodyJSON({{paramName}})
{{/bodyParams}}{{/hasBodyParam}}
{{#returnType}} response := new({{returnType}})
_, err := _sling.ReceiveSuccess(response)
//fmt.Println("{{operationId}} response: ", response, resp, err)
return *response, err
{{/returnType}}{{^returnType}}
_, err := _sling.ReceiveSuccess(nil)
//fmt.Println("{{operationId}} response: void, ", resp, err)
return err
{{/returnType}}
}
{{/operation}}
{{/operations}}

View File

@@ -0,0 +1,15 @@
package {{packageName}}
{{#models}}
import (
{{#imports}} "{{import}}"
{{/imports}}
)
{{#model}}
type {{classname}} struct {
{{#vars}}{{name}} {{{datatype}}} `json:"{{baseName}},omitempty"`
{{/vars}}
}
{{/model}}
{{/models}}

View File

@@ -153,7 +153,7 @@ class ObjectSerializer
*/
public function toFormValue($value)
{
if ($value instanceof SplFileObject) {
if ($value instanceof \SplFileObject) {
return $value->getRealPath();
} else {
return $this->toString($value);

View File

@@ -22,6 +22,7 @@ public abstract class AbstractOptionsTest {
this.optionsProvider = optionsProvider;
}
@SuppressWarnings("unused")
@Test
public void checkOptionsProcessing() {
getCodegenConfig().additionalProperties().putAll(optionsProvider.createOptions());
@@ -49,7 +50,7 @@ public abstract class AbstractOptionsTest {
}
}
private Function<CliOption, String> getCliOptionTransformer() {
private static Function<CliOption, String> getCliOptionTransformer() {
return new Function<CliOption, String>() {
@Override
public String apply(CliOption option) {

View File

@@ -7,6 +7,7 @@ import org.testng.annotations.Test;
import java.util.List;
@SuppressWarnings("static-method")
public class ClientAuthInputTest {
@Test(description = "read a file upload param from a 2.0 spec")

View File

@@ -11,6 +11,7 @@ import java.util.Set;
import static org.testng.Assert.assertEquals;
@SuppressWarnings("static-method")
public class CodegenConfigLoaderTest {
@DataProvider(name = "codegenConfig")

View File

@@ -189,7 +189,7 @@ public class CodegenTest {
}
private Swagger parseAndPrepareSwagger(String path) {
private static Swagger parseAndPrepareSwagger(String path) {
Swagger swagger = new SwaggerParser().read(path);
// resolve inline models
new InlineModelResolver().flatten(swagger);

View File

@@ -200,13 +200,13 @@ public class DefaultGeneratorTest {
}
}
private void changeContent(File file) throws IOException {
private static void changeContent(File file) throws IOException {
Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), UTF_8));
out.write(TEST_SKIP_OVERWRITE);
out.close();
}
private CodegenOperation findCodegenOperationByOperationId(Map<String, List<CodegenOperation>> paths, String operationId) {
private static CodegenOperation findCodegenOperationByOperationId(Map<String, List<CodegenOperation>> paths, String operationId) {
for (List<CodegenOperation> ops : paths.values()) {
for (CodegenOperation co : ops) {
if (operationId.equals(co.operationId)) {

View File

@@ -18,6 +18,7 @@ import java.util.List;
import java.util.Map;
import java.util.Set;
@SuppressWarnings("static-method")
public class ExampleGeneratorTest {
@Test(description = "check handling of recursive models")

View File

@@ -12,6 +12,7 @@ import java.util.Map;
import static org.testng.AssertJUnit.*;
@SuppressWarnings("static-method")
public class InlineModelResolverTest {
@Test
public void resolveInlineModelTest() throws Exception {

View File

@@ -5,6 +5,7 @@ import io.swagger.parser.SwaggerParser;
import org.testng.annotations.Test;
@SuppressWarnings("static-method")
public class SwaggerMigratorTest {
@Test(description = "read a 1.2 spec")

View File

@@ -22,6 +22,7 @@ public class AkkaScalaClientOptionsTest extends AbstractOptionsTest {
return clientCodegen;
}
@SuppressWarnings("unused")
@Override
protected void setExpectations() {
new Expectations(clientCodegen) {{

View File

@@ -22,6 +22,7 @@ public class AndroidClientOptionsTest extends AbstractOptionsTest {
return clientCodegen;
}
@SuppressWarnings("unused")
@Override
protected void setExpectations() {
new Expectations(clientCodegen) {{

View File

@@ -22,6 +22,7 @@ public class AsyncScalaClientOptionsTest extends AbstractOptionsTest {
return clientCodegen;
}
@SuppressWarnings("unused")
@Override
protected void setExpectations() {
new Expectations(clientCodegen) {{

View File

@@ -25,6 +25,7 @@ import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;
@SuppressWarnings("static-method")
public class CodegenConfiguratorTest {
@Mocked
@@ -45,6 +46,7 @@ public class CodegenConfiguratorTest {
@Tested
CodegenConfigurator configurator;
@SuppressWarnings("unused")
@Test
public void testVerbose() throws Exception {
@@ -75,6 +77,7 @@ public class CodegenConfiguratorTest {
assertValueInMap(clientOptInput.getConfig().additionalProperties(), CodegenConstants.TEMPLATE_DIR, toAbsolutePathDir(templateDir));
}
@SuppressWarnings("unused")
@Test
public void testSystemProperties() throws Exception {
@@ -286,6 +289,7 @@ public class CodegenConfiguratorTest {
assertValueInMap(configurator.getDynamicProperties(), CodegenConstants.LOCAL_VARIABLE_PREFIX, "_");
}
@SuppressWarnings("unused")
private ClientOptInput setupAndRunGenericTest(CodegenConfigurator configurator) {
final String spec = "swagger.yaml";
@@ -315,10 +319,11 @@ public class CodegenConfiguratorTest {
return result;
}
private String toAbsolutePathDir(String outputDir) {
private static String toAbsolutePathDir(String outputDir) {
return Paths.get(outputDir).toAbsolutePath().toAbsolutePath().toString();
}
@SuppressWarnings("unused")
private void setupStandardExpectations(final String spec, final String languageName, final String auth, final CodegenConfig config) {
new StrictExpectations() {{
@@ -339,7 +344,7 @@ public class CodegenConfiguratorTest {
}};
}
private void assertValueInMap(Map map, String propertyKey, String expectedPropertyValue) {
private static void assertValueInMap(Map<?, ?> map, String propertyKey, String expectedPropertyValue) {
assertTrue(map.containsKey(propertyKey));
assertEquals(map.get(propertyKey), expectedPropertyValue);
}

View File

@@ -22,6 +22,7 @@ public class CSharpClientOptionsTest extends AbstractOptionsTest {
return clientCodegen;
}
@SuppressWarnings("unused")
@Override
protected void setExpectations() {
new Expectations(clientCodegen) {{
@@ -37,6 +38,10 @@ public class CSharpClientOptionsTest extends AbstractOptionsTest {
times = 1;
clientCodegen.useDateTimeOffset(true);
times = 1;
clientCodegen.setOptionalProjectFileFlag(true);
times = 1;
clientCodegen.setPackageGuid(CSharpClientOptionsProvider.PACKAGE_GUID_VALUE);
times = 1;
}};
}
}

View File

@@ -22,6 +22,7 @@ public class CsharpDotNet2ClientOptionsTest extends AbstractOptionsTest {
return clientCodegen;
}
@SuppressWarnings("unused")
@Override
protected void setExpectations() {
new Expectations(clientCodegen) {{

View File

@@ -22,6 +22,7 @@ public class DartClientOptionsTest extends AbstractOptionsTest {
return clientCodegen;
}
@SuppressWarnings("unused")
@Override
protected void setExpectations() {
new Expectations(clientCodegen) {{

View File

@@ -8,8 +8,6 @@ import io.swagger.codegen.options.FlashClienOptionsProvider;
import mockit.Expectations;
import mockit.Tested;
import java.util.Map;
public class FlashClienOptionsTest extends AbstractOptionsTest {
@Tested
@@ -24,6 +22,7 @@ public class FlashClienOptionsTest extends AbstractOptionsTest {
return clientCodegen;
}
@SuppressWarnings("unused")
@Override
protected void setExpectations() {
new Expectations(clientCodegen) {{

View File

@@ -21,6 +21,7 @@ public class JavaInflectorServerOptionsTest extends JavaClientOptionsTest {
return clientCodegen;
}
@SuppressWarnings("unused")
@Override
protected void setExpectations() {
new Expectations(clientCodegen) {{

View File

@@ -27,6 +27,7 @@ public class JavaClientOptionsTest extends AbstractOptionsTest {
return clientCodegen;
}
@SuppressWarnings("unused")
@Override
protected void setExpectations() {
new Expectations(clientCodegen) {{

View File

@@ -15,6 +15,7 @@ import org.testng.annotations.Test;
public class JavaInheritanceTest {
@SuppressWarnings("static-method")
@Test(description = "convert a composed model")
public void javaInheritanceTest() {
final Model model = new ComposedModel().parent(new RefModel("Base"))

View File

@@ -18,6 +18,7 @@ import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
@SuppressWarnings("static-method")
public class JavaModelEnumTest {
@Test(description = "convert a java model with an enum")

View File

@@ -24,6 +24,7 @@ import org.testng.annotations.Test;
import java.util.List;
@SuppressWarnings("static-method")
public class JavaModelTest {
@Test(description = "convert a simple java model")

View File

@@ -31,7 +31,7 @@ public class AllowableValuesTest {
}
@DataProvider(name = PROVIDER_NAME)
private Object[][] resource() {
private static Object[][] resource() {
final CodegenParameter param1 = new CodegenParameter();
final CodegenParameter param2 = new CodegenParameter() {{
allowableValues = ImmutableMap.<String, Object>of("values", ImmutableList.of("item1", "item2", "item3"));

View File

@@ -22,6 +22,7 @@ public class JaxRSServerOptionsTest extends JavaClientOptionsTest {
return clientCodegen;
}
@SuppressWarnings("unused")
@Override
protected void setExpectations() {
new Expectations(clientCodegen) {{

View File

@@ -1,6 +1,7 @@
package io.swagger.codegen.jaxrs;
import io.swagger.codegen.CodegenModel;
import io.swagger.codegen.languages.JaxRSServerCodegen;
import io.swagger.models.Model;
import io.swagger.models.ModelImpl;
@@ -12,7 +13,9 @@ import org.testng.annotations.Test;
import static org.testng.Assert.assertEquals;
@SuppressWarnings("static-method")
public class JaxrsJava8ModelTest {
@Test(description = "convert a simple java model with java8 types")
public void simpleModelTest() {
final Model model = new ModelImpl()

View File

@@ -12,7 +12,9 @@ import org.testng.annotations.Test;
import static org.testng.Assert.assertEquals;
@SuppressWarnings("static-method")
public class JaxrsJodaModelTest {
@Test(description = "convert a simple java model with Joda types")
public void simpleModelTest() {
final Model model = new ModelImpl()

View File

@@ -13,6 +13,7 @@ import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
@SuppressWarnings("static-method")
public class BooleanOptionsTest {
private static final String OPTIONS_PROVIDER = "Codegen";

View File

@@ -22,6 +22,7 @@ public class NodeJSServerOptionsTest extends AbstractOptionsTest {
return clientCodegen;
}
@SuppressWarnings("unused")
@Override
protected void setExpectations() {
new Expectations(clientCodegen) {{

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