Merge remote-tracking branch 'upstream/master'

Conflicts:
	modules/swagger-codegen-maven-plugin/src/main/java/io/swagger/codegen/plugin/CodeGenMojo.java
This commit is contained in:
evigeant
2016-01-28 09:18:24 -05:00
142 changed files with 5810 additions and 540 deletions

1
.gitignore vendored
View File

@@ -48,6 +48,7 @@ atlassian-ide-plugin.xml
packages/
.pub
.packages
.vagrant/
samples/client/petstore/php/SwaggerClient-php/composer.lock
samples/client/petstore/php/SwaggerClient-php/vendor/

View File

@@ -23,7 +23,7 @@ Check out [Swagger-Spec](https://github.com/OAI/OpenAPI-Specification) for addit
- [Building](#building)
- [Docker](#docker)
- [Build and run](#build-and-run-using-docker)
- [Build a Node.js server stub](#build-a-nodejs-server-stub)
- [Run docker in Vagrant](#run-docker-in-vagrant)
- [Public Docker image](#public-docker-image)
- [Homebrew](#homebrew)
- Generators
@@ -104,19 +104,21 @@ mvn package
```
git clone https://github.com/swagger-api/swagger-codegen
cd swagger-codegen
./run-in-docker.sh mvn package
```
#### Build a Node.js server stub
#### Run Docker in Vagrant
Prerequisite: install [Vagrant](https://www.vagrantup.com/downloads.html) and [VirtualBox](https://www.virtualbox.org/wiki/Downloads).
```
./run-in-docker.sh generate \
-i http://petstore.swagger.io/v2/swagger.json \
-l nodejs \
-o samples/server/petstore/nodejs
git clone http://github.com/swagger-api/swagger-codegen.git
cd swagger-codegen
vagrant up
vagrant ssh
cd /vagrant
sudo ./run-in-docker.sh mvn package
```
#### Public Docker image
@@ -408,7 +410,7 @@ Your config file for Java can look like
```json
{
"groupId":"com.my.company",
"artifactId":"MyClent",
"artifactId":"MyClient",
"artifactVersion":"1.2.0",
"library":"feign"
}
@@ -534,13 +536,22 @@ java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \
-o samples/server/petstore/scalatra
```
### Java JAX-RS
### Java JAX-RS (Jersey v1.18)
```
java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \
-i http://petstore.swagger.io/v2/swagger.json \
-l jaxrs \
-o samples/server/petstore/jaxrs
-o samples/server/petstore/jaxrs-jersey
```
### Java JAX-RS (Apache CXF 3)
```
java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \
-i http://petstore.swagger.io/v2/swagger.json \
-l jaxrs-cxf \
-o samples/server/petstore/jaxrs-cxf
```
### Java Spring MVC

34
Vagrantfile vendored Normal file
View File

@@ -0,0 +1,34 @@
# -*- mode: ruby -*-
# vi: set ft=ruby :
# Vagrantfile API/syntax version. Don't touch unless you know what you're doing!
VAGRANTFILE_API_VERSION = "2"
Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
config.vm.box = "ubuntu/trusty64"
config.vm.provider "virtualbox" do |v|
v.name = "swagger-codegen"
v.memory = 2048
v.cpus = 2
end
config.vm.box_check_update = true
#SSH
config.ssh.forward_agent = true
config.ssh.shell = "bash -c 'BASH_ENV=/etc/profile exec bash'"
#Provision
config.vm.provision "shell", inline: <<-SHELL
sudo apt-key adv --keyserver hkp://pgp.mit.edu:80 --recv-keys 58118E89F3A912897C070ADBF76221572C52609D
sudo sh -c 'echo "deb https://apt.dockerproject.org/repo ubuntu-trusty main" > /etc/apt/sources.list.d/docker.list'
sudo apt-cache policy docker-engine
sudo apt-get update
sudo apt-get upgrade -y
sudo apt-get install -y docker-engine
SHELL
end

View File

@@ -0,0 +1,4 @@
{
"library": "retrofit2",
"artifactId": "swagger-petstore-retrofit2-rx"
}

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 -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l java -c bin/java-petstore-retrofit2rx.json -o samples/client/petstore/java/retrofit2rx -DuseRxJava=true"
java $JAVA_OPTS -jar $executable $ags

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/JavaJaxRS -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l jaxrs-cxf -o samples/server/petstore/jaxrs-cxf"
java $JAVA_OPTS -jar $executable $ags

View File

@@ -5,7 +5,7 @@ import io.airlift.airline.Option;
import io.swagger.codegen.ClientOptInput;
import io.swagger.codegen.CodegenConstants;
import io.swagger.codegen.DefaultGenerator;
import io.swagger.codegen.cmd.utils.OptionUtils;
import io.swagger.codegen.utils.OptionUtils;
import io.swagger.codegen.config.CodegenConfigurator;
import org.apache.commons.lang3.tuple.Pair;
import org.slf4j.Logger;

View File

@@ -33,7 +33,7 @@ import static com.google.common.base.Joiner.on;
"specify, and includes default templates to include.")
public class Meta implements Runnable {
private static final Logger LOG = LoggerFactory.getLogger(Meta.class);
private static final Logger LOGGER = LoggerFactory.getLogger(Meta.class);
private static final String TEMPLATE_DIR_CLASSPATH = "codegen";
private static final String MUSTACHE_EXTENSION = ".mustache";
@@ -53,7 +53,7 @@ public class Meta implements Runnable {
@Override
public void run() {
final File targetDir = new File(outputFolder);
LOG.info("writing to folder [{}]", targetDir.getAbsolutePath());
LOGGER.info("writing to folder [{}]", targetDir.getAbsolutePath());
String mainClass = CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, name) + "Generator";
@@ -108,13 +108,13 @@ public class Meta implements Runnable {
String formatted = template;
if (support.templateFile.endsWith(MUSTACHE_EXTENSION)) {
LOG.info("writing file to {}", outputFile.getAbsolutePath());
LOGGER.info("writing file to {}", outputFile.getAbsolutePath());
formatted = Mustache.compiler().withLoader(loader(generator))
.defaultValue("")
.compile(template)
.execute(data);
} else {
LOG.info("copying file to {}", outputFile.getAbsolutePath());
LOGGER.info("copying file to {}", outputFile.getAbsolutePath());
}
FileUtils.writeStringToFile(outputFile, formatted);

View File

@@ -1,5 +1,6 @@
package io.swagger.codegen.cmd.utils;
import io.swagger.codegen.utils.OptionUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.junit.Test;

View File

@@ -19,8 +19,10 @@ package io.swagger.codegen.plugin;
import config.Config;
import config.ConfigParser;
import io.swagger.codegen.*;
import io.swagger.codegen.utils.OptionUtils;
import io.swagger.models.Swagger;
import io.swagger.parser.SwaggerParser;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.LifecyclePhase;
@@ -31,6 +33,7 @@ import org.apache.maven.project.MavenProject;
import java.io.File;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
@@ -161,6 +164,20 @@ public class CodeGenMojo extends AbstractMojo {
}
if (configOptions != null) {
if(configOptions.containsKey("import-mappings")) {
Map<String, String> mappings = createMapFromKeyValuePairs(configOptions.remove("import-mappings").toString());
config.importMapping().putAll(mappings);
}
if(configOptions.containsKey("type-mappings")) {
Map<String, String> mappings = createMapFromKeyValuePairs(configOptions.remove("type-mappings").toString());
config.typeMapping().putAll(mappings);
}
if(configOptions.containsKey("instantiation-types")) {
Map<String, String> mappings = createMapFromKeyValuePairs(configOptions.remove("instantiation-types").toString());
config.instantiationTypes().putAll(mappings);
}
addAdditionalProperties(config, definedOptions, configOptions);
}
@@ -207,4 +224,16 @@ public class CodeGenMojo extends AbstractMojo {
}
}
}
private static Map<String, String> createMapFromKeyValuePairs(String commaSeparatedKVPairs) {
final List<Pair<String, String>> pairs = OptionUtils.parseCommaSeparatedTuples(commaSeparatedKVPairs);
Map<String, String> result = new HashMap<String, String>();
for (Pair<String, String> pair : pairs) {
result.put(pair.getLeft(), pair.getRight());
}
return result;
}
}

View File

@@ -7,11 +7,16 @@ import java.io.File;
import java.util.Iterator;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ConfigParser {
private static final Logger LOGGER = LoggerFactory.getLogger(ConfigParser.class);
public static Config read(String location) {
System.out.println("reading config from " + location);
LOGGER.info("reading config from " + location);
ObjectMapper mapper = new ObjectMapper();
@@ -27,11 +32,11 @@ public class ConfigParser {
if (optionNode.getValue().isValueNode()) {
config.setOption(optionNode.getKey(), optionNode.getValue().asText());
} else {
System.out.println("omitting non-value node " + optionNode.getKey());
LOGGER.warn("omitting non-value node " + optionNode.getKey());
}
}
} catch (Exception e) {
System.out.println(e.getMessage());
LOGGER.error(e.getMessage());
return null;
}

View File

@@ -10,13 +10,18 @@ import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.util.Scanner;
import java.util.regex.Pattern;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public abstract class AbstractGenerator {
private static final Logger LOGGER = LoggerFactory.getLogger(AbstractGenerator.class);
@SuppressWarnings("static-method")
public File writeToFile(String filename, String contents) throws IOException {
System.out.println("writing file " + filename);
LOGGER.info("writing file " + filename);
File output = new File(filename);
if (output.getParent() != null && !new File(output.getParent()).exists()) {
@@ -37,10 +42,10 @@ public abstract class AbstractGenerator {
if (reader == null) {
throw new RuntimeException("no file found");
}
java.util.Scanner s = new java.util.Scanner(reader).useDelimiter("\\A");
Scanner s = new Scanner(reader).useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
} catch (Exception e) {
e.printStackTrace();
LOGGER.error(e.getMessage());
}
throw new RuntimeException("can't load template " + name);
}
@@ -53,7 +58,7 @@ public abstract class AbstractGenerator {
}
return new InputStreamReader(is);
} catch (Exception e) {
e.printStackTrace();
LOGGER.error(e.getMessage());
}
throw new RuntimeException("can't load template " + name);
}

View File

@@ -1,15 +1,5 @@
package io.swagger.codegen;
import config.Config;
import config.ConfigParser;
import io.swagger.models.Swagger;
import io.swagger.parser.SwaggerParser;
import org.apache.commons.cli.BasicParser;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
@@ -17,12 +7,28 @@ import java.util.List;
import java.util.Map;
import java.util.ServiceLoader;
import org.apache.commons.cli.BasicParser;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import config.Config;
import config.ConfigParser;
import io.swagger.models.Swagger;
import io.swagger.parser.SwaggerParser;
/**
* @deprecated use instead {@link io.swagger.codegen.DefaultGenerator}
* or cli interface from https://github.com/swagger-api/swagger-codegen/pull/547
*/
@Deprecated
public class Codegen extends DefaultGenerator {
private static final Logger LOGGER = LoggerFactory.getLogger(Codegen.class);
static Map<String, CodegenConfig> configs = new HashMap<String, CodegenConfig>();
static String configString;
static String debugInfoOptions = "\nThe following additional debug options are available for all codegen targets:" +
@@ -111,7 +117,7 @@ public class Codegen extends DefaultGenerator {
.swagger(swagger);
new Codegen().opts(clientOptInput).generate();
} catch (Exception e) {
e.printStackTrace();
LOGGER.error(e.getMessage(), e);
}
}
@@ -136,9 +142,9 @@ public class Codegen extends DefaultGenerator {
} else {
// see if it's a class
try {
System.out.println("loading class " + name);
LOGGER.debug("loading class " + name);
Class<?> customClass = Class.forName(name);
System.out.println("loaded");
LOGGER.debug("loaded");
return (CodegenConfig) customClass.newInstance();
} catch (Exception e) {
throw new RuntimeException("can't load class " + name);

View File

@@ -74,4 +74,9 @@ public class CodegenConstants {
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";
public static final String MODEL_PROPERTY_NAMING = "modelPropertyNaming";
public static final String MODEL_PROPERTY_NAMING_DESC = "Naming convention for the property: 'camelCase', 'PascalCase', 'snake_case' and 'original', which keeps the original name";
public static enum MODEL_PROPERTY_NAMING_TYPE {camelCase, PascalCase, snake_case, original}
}

View File

@@ -689,7 +689,7 @@ public class DefaultCodegen {
} catch (Exception e) {
LOGGER.warn("Error obtaining the datatype from RefProperty:" + p + ". Datatype default to Object");
datatype = "Object";
e.printStackTrace();
LOGGER.error(e.getMessage(), e);
}
} else {
if (p != null) {
@@ -1090,7 +1090,7 @@ public class DefaultCodegen {
ArrayProperty ap = (ArrayProperty) p;
CodegenProperty cp = fromProperty(property.name, ap.getItems());
if (cp == null) {
LOGGER.warn("skipping invalid property " + Json.pretty(p));
LOGGER.warn("skipping invalid property " + Json.pretty(p));
} else {
property.baseType = getSwaggerType(p);
if (!languageSpecificPrimitives.contains(cp.baseType)) {

View File

@@ -240,7 +240,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
}
}
if (System.getProperty("debugModels") != null) {
System.out.println("############ Model info ############");
LOGGER.info("############ Model info ############");
Json.prettyPrint(allModels);
}
@@ -340,7 +340,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
}
}
if (System.getProperty("debugOperations") != null) {
System.out.println("############ Operation info ############");
LOGGER.info("############ Operation info ############");
Json.prettyPrint(allOperations);
}
@@ -379,7 +379,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
config.postProcessSupportingFileData(bundle);
if (System.getProperty("debugSupportingFiles") != null) {
System.out.println("############ Supporting file info ############");
LOGGER.info("############ Supporting file info ############");
Json.prettyPrint(bundle);
}
@@ -439,10 +439,12 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
File outputFile = new File(outputFilename);
OutputStream out = new FileOutputStream(outputFile, false);
if (in != null) {
System.out.println("writing file " + outputFile);
LOGGER.info("writing file " + outputFile);
IOUtils.copy(in, out);
} else {
System.out.println("can't open " + templateFile + " for input"); // FIXME: use LOGGER instead of standart output
if (in == null) {
LOGGER.error("can't open " + templateFile + " for input");
}
}
files.add(outputFile);
}
@@ -550,7 +552,8 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
public void processOperation(String resourcePath, String httpMethod, Operation operation, Map<String, List<CodegenOperation>> operations, Path path) {
if (operation != null) {
if (System.getProperty("debugOperations") != null) {
LOGGER.debug("processOperation: resourcePath= " + resourcePath + "\t;" + httpMethod + " " + operation + "\n");
LOGGER.info("processOperation: resourcePath= " + resourcePath + "\t;" + httpMethod + " " + operation
+ "\n");
}
List<String> tags = operation.getTags();
if (tags == null) {

View File

@@ -8,8 +8,11 @@ import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.HashMap;
@@ -24,6 +27,9 @@ import java.util.ServiceLoader;
*/
@Deprecated
public class MetaGenerator extends AbstractGenerator {
private static final Logger LOGGER = LoggerFactory.getLogger(MetaGenerator.class);
static Map<String, CodegenConfig> configs = new HashMap<String, CodegenConfig>();
static String configString;
@@ -99,7 +105,7 @@ public class MetaGenerator extends AbstractGenerator {
usage(options);
return;
}
System.out.println("writing to folder " + outputFolder);
LOGGER.info("writing to folder " + outputFolder);
File outputFolderLocation = new File(outputFolder);
if (!outputFolderLocation.exists()) {
outputFolderLocation.mkdirs();
@@ -163,11 +169,11 @@ public class MetaGenerator extends AbstractGenerator {
} else {
String template = readTemplate(templateDir + File.separator + support.templateFile);
FileUtils.writeStringToFile(new File(outputFilename), template);
System.out.println("copying file to " + outputFilename);
LOGGER.info("copying file to " + outputFilename);
files.add(new File(outputFilename));
}
} catch (java.io.IOException e) {
e.printStackTrace();
} catch (IOException e) {
LOGGER.error(e.getMessage(), e);
}
}
}

View File

@@ -7,9 +7,16 @@ import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import config.ConfigParser;
import static org.apache.commons.lang3.StringUtils.isNotEmpty;
public class AuthParser {
private static final Logger LOGGER = LoggerFactory.getLogger(AuthParser.class);
public static List<AuthorizationValue> parse(String urlEncodedAuthStr) {
List<AuthorizationValue> auths = new ArrayList<AuthorizationValue>();
@@ -38,7 +45,7 @@ public class AuthParser {
.append(URLEncoder.encode(v.getValue(), "UTF-8"));
} catch (Exception e) {
// continue
e.printStackTrace();
LOGGER.error(e.getMessage(), e);
}
}
return b.toString();

View File

@@ -36,7 +36,7 @@ import static org.apache.commons.lang3.StringUtils.isNotEmpty;
*/
public class CodegenConfigurator {
public static final Logger LOG = LoggerFactory.getLogger(CodegenConfigurator.class);
public static final Logger LOGGER = LoggerFactory.getLogger(CodegenConfigurator.class);
private String lang;
private String inputSpec;
@@ -349,7 +349,7 @@ public class CodegenConfigurator {
if (!verbose) {
return;
}
LOG.info("\nVERBOSE MODE: ON. Additional debug options are injected" +
LOGGER.info("\nVERBOSE MODE: ON. Additional debug options are injected" +
"\n - [debugSwagger] prints the swagger specification as interpreted by the codegen" +
"\n - [debugModels] prints models passed to the template engine" +
"\n - [debugOperations] prints operations passed to the template engine" +
@@ -392,7 +392,7 @@ public class CodegenConfigurator {
try {
return Json.mapper().readValue(new File(configFile), CodegenConfigurator.class);
} catch (IOException e) {
LOG.error("Unable to deserialize config file: " + configFile, e);
LOGGER.error("Unable to deserialize config file: " + configFile, e);
}
}
return null;

View File

@@ -0,0 +1,183 @@
package io.swagger.codegen.languages;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import io.swagger.codegen.CodegenOperation;
import io.swagger.codegen.CodegenResponse;
import io.swagger.codegen.CodegenType;
import io.swagger.models.Operation;
import io.swagger.models.Path;
import io.swagger.models.Swagger;
public abstract class AbstractJavaJAXRSServerCodegen extends JavaClientCodegen
{
/**
* Name of the sub-directory in "src/main/resource" where to find the
* Mustache template for the JAX-RS Codegen.
*/
protected static final String JAXRS_TEMPLATE_DIRECTORY_NAME = "JavaJaxRS";
protected String implFolder = "src/main/java";
protected String title = "Swagger Server";
public AbstractJavaJAXRSServerCodegen()
{
super();
}
// ================
// ABSTRACT METHODS
// ================
@Override
public abstract String getHelp();
@Override
public abstract String getName();
// ===============
// COMMONS METHODS
// ===============
@Override
public CodegenType getTag()
{
return CodegenType.SERVER;
}
@Override
public void preprocessSwagger(Swagger swagger)
{
if ( "/".equals(swagger.getBasePath()) ) {
swagger.setBasePath("");
}
String host = swagger.getHost();
String port = "8080"; // Default value for a JEE Server
if ( host != null ) {
String[] parts = host.split(":");
if ( parts.length > 1 ) {
port = parts[1];
}
}
this.additionalProperties.put("serverPort", port);
if ( swagger.getPaths() != null ) {
for ( String pathname : swagger.getPaths().keySet() ) {
Path path = swagger.getPath(pathname);
if ( path.getOperations() != null ) {
for ( Operation operation : path.getOperations() ) {
if ( operation.getTags() != null ) {
List<Map<String, String>> tags = new ArrayList<Map<String, String>>();
for ( String tag : operation.getTags() ) {
Map<String, String> value = new HashMap<String, String>();
value.put("tag", tag);
value.put("hasMore", "true");
tags.add(value);
}
if ( tags.size() > 0 ) {
tags.get(tags.size() - 1).remove("hasMore");
}
if ( operation.getTags().size() > 0 ) {
String tag = operation.getTags().get(0);
operation.setTags(Arrays.asList(tag));
}
operation.setVendorExtension("x-tags", tags);
}
}
}
}
}
}
@Override
public Map<String, Object> postProcessOperations(Map<String, Object> objs)
{
@SuppressWarnings("unchecked")
Map<String, Object> operations = (Map<String, Object>) objs.get("operations");
if ( operations != null ) {
@SuppressWarnings("unchecked")
List<CodegenOperation> ops = (List<CodegenOperation>) operations.get("operation");
for ( CodegenOperation operation : ops ) {
List<CodegenResponse> responses = operation.responses;
if ( responses != null ) {
for ( CodegenResponse resp : responses ) {
if ( "0".equals(resp.code) ) {
resp.code = "200";
}
}
}
if ( operation.returnType == null ) {
operation.returnType = "void";
} else if ( operation.returnType.startsWith("List") ) {
String rt = operation.returnType;
int end = rt.lastIndexOf(">");
if ( end > 0 ) {
operation.returnType = rt.substring("List<".length(), end).trim();
operation.returnContainer = "List";
}
} else if ( operation.returnType.startsWith("Map") ) {
String rt = operation.returnType;
int end = rt.lastIndexOf(">");
if ( end > 0 ) {
operation.returnType = rt.substring("Map<".length(), end).split(",")[1].trim();
operation.returnContainer = "Map";
}
} else if ( operation.returnType.startsWith("Set") ) {
String rt = operation.returnType;
int end = rt.lastIndexOf(">");
if ( end > 0 ) {
operation.returnType = rt.substring("Set<".length(), end).trim();
operation.returnContainer = "Set";
}
}
}
}
return objs;
}
@Override
public String toApiName(final String name)
{
String computed = name;
if ( computed.length() == 0 ) {
return "DefaultApi";
}
computed = sanitizeName(computed);
return camelize(computed) + "Api";
}
@Override
public String apiFilename(String templateName, String tag)
{
String result = super.apiFilename(templateName, tag);
if ( templateName.endsWith("Impl.mustache") ) {
int ix = result.lastIndexOf('/');
result = result.substring(0, ix) + "/impl" + result.substring(ix, result.length() - 5) + "ServiceImpl.java";
result = result.replace(apiFileFolder(), implFileFolder(implFolder));
} else if ( templateName.endsWith("Factory.mustache") ) {
int ix = result.lastIndexOf('/');
result = result.substring(0, ix) + "/factories" + result.substring(ix, result.length() - 5) + "ServiceFactory.java";
result = result.replace(apiFileFolder(), implFileFolder(implFolder));
} else if ( templateName.endsWith("Service.mustache") ) {
int ix = result.lastIndexOf('.');
result = result.substring(0, ix) + "Service.java";
}
return result;
}
private String implFileFolder(String output)
{
return outputFolder + "/" + output + "/" + apiPackage().replace('.', '/');
}
@Override
public boolean shouldOverwrite(String filename)
{
return super.shouldOverwrite(filename) && !filename.endsWith("ServiceImpl.java") && !filename.endsWith("ServiceFactory.java");
}
}

View File

@@ -10,6 +10,8 @@ import org.apache.commons.lang.StringUtils;
public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen implements CodegenConfig {
protected String modelPropertyNaming= "camelCase";
public AbstractTypeScriptClientCodegen() {
super();
supportsInheritance = true;
@@ -50,8 +52,21 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp
typeMapping.put("DateTime", "Date");
//TODO binary should be mapped to byte array
// mapped to String as a workaround
typeMapping.put("binary", "string");
typeMapping.put("binary", "string");
cliOptions.add(new CliOption(CodegenConstants.MODEL_PROPERTY_NAMING, CodegenConstants.MODEL_PROPERTY_NAMING_DESC).defaultValue("camelCase"));
}
@Override
public void processOpts() {
super.processOpts();
if (additionalProperties.containsKey(CodegenConstants.MODEL_PROPERTY_NAMING)) {
setModelPropertyNaming((String) additionalProperties.get(CodegenConstants.MODEL_PROPERTY_NAMING));
}
}
@Override
public CodegenType getTag() {
@@ -74,7 +89,7 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp
}
@Override
public String toVarName(String name) {
public String toParamName(String name) {
// replace - with _ e.g. created-at => created_at
name = name.replaceAll("-", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
@@ -94,9 +109,9 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp
}
@Override
public String toParamName(String name) {
public String toVarName(String name) {
// should be the same as variable name
return toVarName(name);
return getNameUsingModelPropertyNaming(name);
}
@Override
@@ -146,19 +161,47 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp
return type;
}
@Override
public String toOperationId(String operationId) {
// throw exception if method name is empty
if (StringUtils.isEmpty(operationId)) {
throw new RuntimeException("Empty method name (operationId) not allowed");
}
// method name cannot use reserved keyword, e.g. return
// append _ at the beginning, e.g. _return
if (reservedWords.contains(operationId)) {
return escapeReservedWord(camelize(sanitizeName(operationId), true));
}
return camelize(sanitizeName(operationId), true);
@Override
public String toOperationId(String operationId) {
// throw exception if method name is empty
if (StringUtils.isEmpty(operationId)) {
throw new RuntimeException("Empty method name (operationId) not allowed");
}
// method name cannot use reserved keyword, e.g. return
// append _ at the beginning, e.g. _return
if (reservedWords.contains(operationId)) {
return escapeReservedWord(camelize(sanitizeName(operationId), true));
}
return camelize(sanitizeName(operationId), true);
}
public void setModelPropertyNaming(String naming) {
if ("original".equals(naming) || "camelCase".equals(naming) ||
"PascalCase".equals(naming) || "snake_case".equals(naming)) {
this.modelPropertyNaming = naming;
} else {
throw new IllegalArgumentException("Invalid model property naming '" +
naming + "'. Must be 'original', 'camelCase', " +
"'PascalCase' or 'snake_case'");
}
}
public String getModelPropertyNaming() {
return this.modelPropertyNaming;
}
public String getNameUsingModelPropertyNaming(String name) {
switch (CodegenConstants.MODEL_PROPERTY_NAMING_TYPE.valueOf(getModelPropertyNaming())) {
case original: return name;
case camelCase: return camelize(name, true);
case PascalCase: return camelize(name);
case snake_case: return underscore(name);
default: throw new IllegalArgumentException("Invalid model property naming '" +
name + "'. Must be 'original', 'camelCase', " +
"'PascalCase' or 'snake_case'");
}
}
}

View File

@@ -4,6 +4,8 @@ import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Multimap;
import config.ConfigParser;
import io.swagger.codegen.*;
import io.swagger.models.HttpMethod;
import io.swagger.models.Operation;
@@ -14,7 +16,13 @@ import io.swagger.util.Yaml;
import java.io.File;
import java.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class FlaskConnexionCodegen extends DefaultCodegen implements CodegenConfig {
private static final Logger LOGGER = LoggerFactory.getLogger(FlaskConnexionCodegen.class);
public static final String CONTROLLER_PACKAGE = "controllerPackage";
public static final String DEFAULT_CONTROLLER = "defaultController";
@@ -289,7 +297,7 @@ public class FlaskConnexionCodegen extends DefaultCodegen implements CodegenConf
try {
objs.put("swagger-yaml", Yaml.mapper().writeValueAsString(swagger));
} catch (JsonProcessingException e) {
e.printStackTrace();
LOGGER.error(e.getMessage(), e);
}
}
for (Map<String, Object> operations : getOperations(objs)) {

View File

@@ -0,0 +1,73 @@
package io.swagger.codegen.languages;
import java.io.File;
import java.util.List;
import java.util.Map;
import io.swagger.codegen.CliOption;
import io.swagger.codegen.CodegenConstants;
import io.swagger.codegen.CodegenOperation;
import io.swagger.models.Operation;
public class JavaCXFServerCodegen extends AbstractJavaJAXRSServerCodegen
{
public JavaCXFServerCodegen()
{
super();
sourceFolder = "src/gen/java";
invokerPackage = "io.swagger.api";
artifactId = "swagger-jaxrs-server";
outputFolder = "generated-code/JavaJaxRS-CXF";
modelTemplateFiles.put("model.mustache", ".java");
apiTemplateFiles.put("api.mustache", ".java");
apiPackage = "io.swagger.api";
modelPackage = "io.swagger.model";
additionalProperties.put("title", title);
super.embeddedTemplateDir = templateDir = JAXRS_TEMPLATE_DIRECTORY_NAME + File.separator + "cxf";
for ( int i = 0; i < cliOptions.size(); i++ ) {
if ( CodegenConstants.LIBRARY.equals(cliOptions.get(i).getOpt()) ) {
cliOptions.remove(i);
break;
}
}
cliOptions.add(new CliOption(CodegenConstants.IMPL_FOLDER, CodegenConstants.IMPL_FOLDER_DESC));
}
@Override
public void processOpts()
{
super.processOpts();
sourceFolder = "gen" + File.separator + "java";
modelTemplateFiles.clear();
modelTemplateFiles.put("entityModel.mustache", ".java");
supportingFiles.clear();
}
@Override
public String getName()
{
return "jaxrs-cxf";
}
@Override
public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, Map<String, List<CodegenOperation>> operations) {
super.addOperationToGroup(tag, resourcePath, operation, co, operations);
co.subresourceOperation = !co.path.isEmpty();
}
@Override
public String getHelp()
{
return "Generates a Java JAXRS Server application based on Apache CXF framework.";
}
}

View File

@@ -1,20 +1,45 @@
package io.swagger.codegen.languages;
import com.google.common.base.Strings;
import io.swagger.codegen.*;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import io.swagger.codegen.CliOption;
import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenConstants;
import io.swagger.codegen.CodegenModel;
import io.swagger.codegen.CodegenOperation;
import io.swagger.codegen.CodegenParameter;
import io.swagger.codegen.CodegenProperty;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile;
import io.swagger.models.Model;
import io.swagger.models.Operation;
import io.swagger.models.Path;
import io.swagger.models.Swagger;
import io.swagger.models.parameters.FormParameter;
import io.swagger.models.parameters.Parameter;
import io.swagger.models.properties.*;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.util.*;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.BooleanProperty;
import io.swagger.models.properties.DoubleProperty;
import io.swagger.models.properties.FloatProperty;
import io.swagger.models.properties.IntegerProperty;
import io.swagger.models.properties.LongProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
import io.swagger.models.properties.StringProperty;
public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
@SuppressWarnings("hiding")
@@ -22,6 +47,10 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
public static final String FULL_JAVA_UTIL = "fullJavaUtil";
public static final String DEFAULT_LIBRARY = "<default>";
public static final String DATE_LIBRARY = "dateLibrary";
public static final String USE_RX_JAVA = "useRxJava";
public static final String RETROFIT_1 = "retrofit";
public static final String RETROFIT_2 = "retrofit2";
protected String dateLibrary = "default";
protected String invokerPackage = "io.swagger.client";
@@ -35,6 +64,7 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
protected String javaUtilPrefix = "";
protected Boolean serializableModel = false;
protected boolean serializeBigDecimalAsString = false;
protected boolean useRxJava = false;
public JavaClientCodegen() {
super();
@@ -88,13 +118,15 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
cliOptions.add(CliOption.newBoolean(CodegenConstants.SERIALIZE_BIG_DECIMAL_AS_STRING, CodegenConstants
.SERIALIZE_BIG_DECIMAL_AS_STRING_DESC));
cliOptions.add(CliOption.newBoolean(FULL_JAVA_UTIL, "whether to use fully qualified name for classes under java.util"));
cliOptions.add(CliOption.newBoolean(USE_RX_JAVA, "Whether to use the RxJava adapter with the retrofit2 library."));
supportedLibraries.put(DEFAULT_LIBRARY, "HTTP client: Jersey client 1.18. JSON processing: Jackson 2.4.2");
supportedLibraries.put("feign", "HTTP client: Netflix Feign 8.1.1");
supportedLibraries.put("jersey2", "HTTP client: Jersey client 2.6");
supportedLibraries.put("okhttp-gson", "HTTP client: OkHttp 2.4.0. JSON processing: Gson 2.3.1");
supportedLibraries.put("retrofit", "HTTP client: OkHttp 2.4.0. JSON processing: Gson 2.3.1 (Retrofit 1.9.0)");
supportedLibraries.put("retrofit2", "HTTP client: OkHttp 2.5.0. JSON processing: Gson 2.4 (Retrofit 2.0.0-beta2)");
supportedLibraries.put(RETROFIT_1, "HTTP client: OkHttp 2.4.0. JSON processing: Gson 2.3.1 (Retrofit 1.9.0)");
supportedLibraries.put(RETROFIT_2, "HTTP client: OkHttp 2.5.0. JSON processing: Gson 2.4 (Retrofit 2.0.0-beta2). Enable the RxJava adapter using '-DuseRxJava=true'.");
CliOption library = new CliOption(CodegenConstants.LIBRARY, "library template (sub-template) to use");
library.setDefault(DEFAULT_LIBRARY);
library.setEnum(supportedLibraries);
@@ -183,6 +215,10 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
if (additionalProperties.containsKey(FULL_JAVA_UTIL)) {
this.setFullJavaUtil(Boolean.valueOf(additionalProperties.get(FULL_JAVA_UTIL).toString()));
}
if (additionalProperties.containsKey(USE_RX_JAVA)) {
this.setUseRxJava(Boolean.valueOf(additionalProperties.get(USE_RX_JAVA).toString()));
}
if (fullJavaUtil) {
javaUtilPrefix = "java.util.";
}
@@ -240,7 +276,7 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
supportingFiles.add(new SupportingFile("auth/OAuth.mustache", authFolder, "OAuth.java"));
supportingFiles.add(new SupportingFile("auth/OAuthFlow.mustache", authFolder, "OAuthFlow.java"));
if (!("feign".equals(getLibrary()) || "retrofit".equals(getLibrary()) || "retrofit2".equals(getLibrary()))) {
if (!("feign".equals(getLibrary()) || usesAnyRetrofitLibrary())) {
supportingFiles.add(new SupportingFile("apiException.mustache", invokerFolder, "ApiException.java"));
supportingFiles.add(new SupportingFile("Configuration.mustache", invokerFolder, "Configuration.java"));
supportingFiles.add(new SupportingFile("Pair.mustache", invokerFolder, "Pair.java"));
@@ -257,7 +293,7 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
supportingFiles.add(new SupportingFile("ProgressResponseBody.mustache", invokerFolder, "ProgressResponseBody.java"));
// "build.sbt" is for development with SBT
supportingFiles.add(new SupportingFile("build.sbt.mustache", "", "build.sbt"));
} else if ("retrofit".equals(getLibrary()) || "retrofit2".equals(getLibrary())) {
} else if (usesAnyRetrofitLibrary()) {
supportingFiles.add(new SupportingFile("auth/OAuthOkHttpClient.mustache", authFolder, "OAuthOkHttpClient.java"));
supportingFiles.add(new SupportingFile("CollectionFormats.mustache", invokerFolder, "CollectionFormats.java"));
} else if("jersey2".equals(getLibrary())) {
@@ -285,6 +321,14 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
}
}
private boolean usesAnyRetrofitLibrary() {
return getLibrary() != null && getLibrary().contains(RETROFIT_1);
}
private boolean usesRetrofit2Library() {
return getLibrary() != null && getLibrary().contains(RETROFIT_2);
}
private void sanitizeConfig() {
// Sanitize any config options here. We also have to update the additionalProperties because
// the whole additionalProperties object is injected into the main object passed to the mustache layer
@@ -493,7 +537,7 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
if (allDefinitions != null && codegenModel != null && codegenModel.parentSchema != null && codegenModel.hasEnums) {
final Model parentModel = allDefinitions.get(codegenModel.parentSchema);
final CodegenModel parentCodegenModel = super.fromModel(codegenModel.parent, parentModel);
codegenModel = this.reconcileInlineEnums(codegenModel, parentCodegenModel);
codegenModel = JavaClientCodegen.reconcileInlineEnums(codegenModel, parentCodegenModel);
}
return codegenModel;
@@ -598,7 +642,7 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
@Override
public Map<String, Object> postProcessOperations(Map<String, Object> objs) {
if("retrofit".equals(getLibrary()) || "retrofit2".equals(getLibrary())) {
if(usesAnyRetrofitLibrary()) {
Map<String, Object> operations = (Map<String, Object>) objs.get("operations");
if (operations != null) {
List<CodegenOperation> ops = (List<CodegenOperation>) operations.get("operation");
@@ -614,7 +658,7 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
if (operation.returnType == null) {
operation.returnType = "Void";
}
if ("retrofit2".equals(getLibrary()) && StringUtils.isNotEmpty(operation.path) && operation.path.startsWith("/"))
if (usesRetrofit2Library() && StringUtils.isNotEmpty(operation.path) && operation.path.startsWith("/"))
operation.path = operation.path.substring(1);
}
}
@@ -792,6 +836,10 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
this.fullJavaUtil = fullJavaUtil;
}
public void setUseRxJava(boolean useRxJava) {
this.useRxJava = useRxJava;
}
public void setDateLibrary(String library) {
this.dateLibrary = library;
}

View File

@@ -11,7 +11,13 @@ import io.swagger.util.Yaml;
import java.util.*;
public class JavaInflectorServerCodegen extends JavaClientCodegen {
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class JavaInflectorServerCodegen extends JavaClientCodegen implements CodegenConfig {
private static final Logger LOGGER = LoggerFactory.getLogger(JavaInflectorServerCodegen.class);
protected String title = "Swagger Inflector";
public JavaInflectorServerCodegen() {
@@ -164,7 +170,7 @@ public class JavaInflectorServerCodegen extends JavaClientCodegen {
try {
objs.put("swagger-yaml", Yaml.mapper().writeValueAsString(swagger));
} catch (JsonProcessingException e) {
e.printStackTrace();
LOGGER.error(e.getMessage(), e);
}
}
return super.postProcessSupportingFileData(objs);

View File

@@ -0,0 +1,124 @@
package io.swagger.codegen.languages;
import io.swagger.codegen.*;
import io.swagger.models.Operation;
import java.io.File;
import java.util.*;
public class JavaJerseyServerCodegen extends AbstractJavaJAXRSServerCodegen
{
public JavaJerseyServerCodegen()
{
super();
sourceFolder = "src/gen/java";
invokerPackage = "io.swagger.api";
artifactId = "swagger-jaxrs-server";
outputFolder = "generated-code/JavaJaxRS-Jersey";
modelTemplateFiles.put("model.mustache", ".java");
apiTemplateFiles.put("api.mustache", ".java");
apiTemplateFiles.put("apiService.mustache", ".java");
apiTemplateFiles.put("apiServiceImpl.mustache", ".java");
apiTemplateFiles.put("apiServiceFactory.mustache", ".java");
apiPackage = "io.swagger.api";
modelPackage = "io.swagger.model";
additionalProperties.put("title", title);
embeddedTemplateDir = templateDir = JAXRS_TEMPLATE_DIRECTORY_NAME + File.separator + "jersey1_18";
for ( int i = 0; i < cliOptions.size(); i++ ) {
if ( CodegenConstants.LIBRARY.equals(cliOptions.get(i).getOpt()) ) {
cliOptions.remove(i);
break;
}
}
CliOption library = new CliOption(CodegenConstants.LIBRARY, "library template (sub-template) to use");
library.setDefault(DEFAULT_LIBRARY);
Map<String, String> supportedLibraries = new LinkedHashMap<String, String>();
supportedLibraries.put(DEFAULT_LIBRARY, "Jersey core 1.18.1");
library.setEnum(supportedLibraries);
cliOptions.add(library);
cliOptions.add(new CliOption(CodegenConstants.IMPL_FOLDER, CodegenConstants.IMPL_FOLDER_DESC));
}
@Override
public String getName()
{
return "jaxrs"; // TODO should be renamed as "jaxrs-jersey"
}
@Override
public String getHelp()
{
return "Generates a Java JAXRS Server application based on Jersey framework.";
}
@Override
public void processOpts()
{
super.processOpts();
if ( additionalProperties.containsKey(CodegenConstants.IMPL_FOLDER) ) {
implFolder = (String) additionalProperties.get(CodegenConstants.IMPL_FOLDER);
}
supportingFiles.clear();
supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml"));
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
supportingFiles.add(new SupportingFile("ApiException.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "ApiException.java"));
supportingFiles.add(new SupportingFile("ApiOriginFilter.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "ApiOriginFilter.java"));
supportingFiles.add(new SupportingFile("ApiResponseMessage.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "ApiResponseMessage.java"));
supportingFiles.add(new SupportingFile("NotFoundException.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "NotFoundException.java"));
supportingFiles.add(new SupportingFile("web.mustache", ("src/main/webapp/WEB-INF"), "web.xml"));
supportingFiles.add(new SupportingFile("StringUtil.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "StringUtil.java"));
if ( additionalProperties.containsKey("dateLibrary") ) {
setDateLibrary(additionalProperties.get("dateLibrary").toString());
additionalProperties.put(dateLibrary, "true");
}
if ( "joda".equals(dateLibrary) ) {
supportingFiles.add(new SupportingFile("JodaDateTimeProvider.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "JodaDateTimeProvider.java"));
supportingFiles.add(new SupportingFile("JodaLocalDateProvider.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "JodaLocalDateProvider.java"));
} else if ( "java8".equals(dateLibrary) ) {
supportingFiles.add(new SupportingFile("LocalDateTimeProvider.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "LocalDateTimeProvider.java"));
supportingFiles.add(new SupportingFile("LocalDateProvider.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "LocalDateProvider.java"));
}
}
@Override
public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, Map<String, List<CodegenOperation>> operations) {
String basePath = resourcePath;
if (basePath.startsWith("/")) {
basePath = basePath.substring(1);
}
int pos = basePath.indexOf("/");
if (pos > 0) {
basePath = basePath.substring(0, pos);
}
if (basePath == "") {
basePath = "default";
} else {
if (co.path.startsWith("/" + basePath)) {
co.path = co.path.substring(("/" + basePath).length());
}
co.subresourceOperation = !co.path.isEmpty();
}
List<CodegenOperation> opList = operations.get(basePath);
if (opList == null) {
opList = new ArrayList<CodegenOperation>();
operations.put(basePath, opList);
}
opList.add(co);
co.baseName = basePath;
}
}

View File

@@ -419,25 +419,6 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
@Override
public Map<String, Object> postProcessOperations(Map<String, Object> objs) {
if("retrofit".equals(getLibrary())) {
Map<String, Object> operations = (Map<String, Object>) objs.get("operations");
if (operations != null) {
List<CodegenOperation> ops = (List<CodegenOperation>) operations.get("operation");
for (CodegenOperation operation : ops) {
if (operation.hasConsumes == Boolean.TRUE) {
Map<String, String> firstType = operation.consumes.get(0);
if (firstType != null) {
if ("multipart/form-data".equals(firstType.get("mediaType"))) {
operation.isMultipart = Boolean.TRUE;
}
}
}
if (operation.returnType == null) {
operation.returnType = "Void";
}
}
}
}
return objs;
}

View File

@@ -1,267 +0,0 @@
package io.swagger.codegen.languages;
import io.swagger.codegen.*;
import io.swagger.models.Operation;
import io.swagger.models.Path;
import io.swagger.models.Swagger;
import java.io.File;
import java.util.*;
public class JaxRSServerCodegen extends JavaClientCodegen {
protected String title = "Swagger Server";
protected String implFolder = "src/main/java";
public JaxRSServerCodegen() {
super();
sourceFolder = "src/gen/java";
invokerPackage = "io.swagger.api";
artifactId = "swagger-jaxrs-server";
outputFolder = "generated-code/javaJaxRS";
modelTemplateFiles.put("model.mustache", ".java");
apiTemplateFiles.put("api.mustache", ".java");
apiTemplateFiles.put("apiService.mustache", ".java");
apiTemplateFiles.put("apiServiceImpl.mustache", ".java");
apiTemplateFiles.put("apiServiceFactory.mustache", ".java");
apiPackage = "io.swagger.api";
modelPackage = "io.swagger.model";
additionalProperties.put("title", title);
embeddedTemplateDir = templateDir = "JavaJaxRS" + File.separator + "jersey1_18";
for(int i = 0; i < cliOptions.size(); i++) {
if(CodegenConstants.LIBRARY.equals(cliOptions.get(i).getOpt())) {
cliOptions.remove(i);
break;
}
}
CliOption library = new CliOption(CodegenConstants.LIBRARY, "library template (sub-template) to use");
library.setDefault(DEFAULT_LIBRARY);
Map<String, String> supportedLibraries = new LinkedHashMap<String, String>();
supportedLibraries.put(DEFAULT_LIBRARY, "Jersey core 1.18.1");
// supportedLibraries.put("jersey2", "Jersey2 core library 2.x");
library.setEnum(supportedLibraries);
cliOptions.add(library);
cliOptions.add(new CliOption(CodegenConstants.IMPL_FOLDER, CodegenConstants.IMPL_FOLDER_DESC));
}
@Override
public CodegenType getTag() {
return CodegenType.SERVER;
}
@Override
public String getName() {
return "jaxrs";
}
@Override
public String getHelp() {
return "Generates a Java JAXRS Server application.";
}
@Override
public void processOpts() {
super.processOpts();
if(additionalProperties.containsKey(CodegenConstants.IMPL_FOLDER)) {
implFolder = (String) additionalProperties.get(CodegenConstants.IMPL_FOLDER);
}
supportingFiles.clear();
supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml"));
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
supportingFiles.add(new SupportingFile("ApiException.mustache",
(sourceFolder + '/' + apiPackage).replace(".", "/"), "ApiException.java"));
supportingFiles.add(new SupportingFile("ApiOriginFilter.mustache",
(sourceFolder + '/' + apiPackage).replace(".", "/"), "ApiOriginFilter.java"));
supportingFiles.add(new SupportingFile("ApiResponseMessage.mustache",
(sourceFolder + '/' + apiPackage).replace(".", "/"), "ApiResponseMessage.java"));
supportingFiles.add(new SupportingFile("NotFoundException.mustache",
(sourceFolder + '/' + apiPackage).replace(".", "/"), "NotFoundException.java"));
supportingFiles.add(new SupportingFile("web.mustache",
("src/main/webapp/WEB-INF"), "web.xml"));
supportingFiles.add(new SupportingFile("StringUtil.mustache",
(sourceFolder + '/' + apiPackage).replace(".", "/"), "StringUtil.java"));
if (additionalProperties.containsKey("dateLibrary")) {
setDateLibrary(additionalProperties.get("dateLibrary").toString());
additionalProperties.put(dateLibrary, "true");
}
if("joda".equals(dateLibrary)) {
supportingFiles.add(new SupportingFile("JodaDateTimeProvider.mustache",
(sourceFolder + '/' + apiPackage).replace(".", "/"), "JodaDateTimeProvider.java"));
supportingFiles.add(new SupportingFile("JodaLocalDateProvider.mustache",
(sourceFolder + '/' + apiPackage).replace(".", "/"), "JodaLocalDateProvider.java"));
}
else if ("java8".equals(dateLibrary)) {
supportingFiles.add(new SupportingFile("LocalDateTimeProvider.mustache",
(sourceFolder + '/' + apiPackage).replace(".", "/"), "LocalDateTimeProvider.java"));
supportingFiles.add(new SupportingFile("LocalDateProvider.mustache",
(sourceFolder + '/' + apiPackage).replace(".", "/"), "LocalDateProvider.java"));
}
}
@Override
public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, Map<String, List<CodegenOperation>> operations) {
String basePath = resourcePath;
if (basePath.startsWith("/")) {
basePath = basePath.substring(1);
}
int pos = basePath.indexOf("/");
if (pos > 0) {
basePath = basePath.substring(0, pos);
}
if (basePath == "") {
basePath = "default";
} else {
if (co.path.startsWith("/" + basePath)) {
co.path = co.path.substring(("/" + basePath).length());
}
co.subresourceOperation = !co.path.isEmpty();
}
List<CodegenOperation> opList = operations.get(basePath);
if (opList == null) {
opList = new ArrayList<CodegenOperation>();
operations.put(basePath, opList);
}
opList.add(co);
co.baseName = basePath;
}
@Override
public void preprocessSwagger(Swagger swagger) {
if("/".equals(swagger.getBasePath())) {
swagger.setBasePath("");
}
String host = swagger.getHost();
String port = "8080";
if(host != null) {
String[] parts = host.split(":");
if(parts.length > 1) {
port = parts[1];
}
}
this.additionalProperties.put("serverPort", port);
if(swagger.getPaths() != null) {
for(String pathname : swagger.getPaths().keySet()) {
Path path = swagger.getPath(pathname);
if(path.getOperations() != null) {
for(Operation operation : path.getOperations()) {
if(operation.getTags() != null) {
List<Map<String, String>> tags = new ArrayList<Map<String, String>>();
for(String tag : operation.getTags()) {
Map<String, String> value = new HashMap<String, String>();
value.put("tag", tag);
value.put("hasMore", "true");
tags.add(value);
}
if(tags.size() > 0) {
tags.get(tags.size() - 1).remove("hasMore");
}
if(operation.getTags().size() > 0) {
String tag = operation.getTags().get(0);
operation.setTags(Arrays.asList(tag));
}
operation.setVendorExtension("x-tags", tags);
}
}
}
}
}
}
@Override
public Map<String, Object> postProcessOperations(Map<String, Object> objs) {
Map<String, Object> operations = (Map<String, Object>) objs.get("operations");
if (operations != null) {
List<CodegenOperation> ops = (List<CodegenOperation>) operations.get("operation");
for (CodegenOperation operation : ops) {
List<CodegenResponse> responses = operation.responses;
if (responses != null) {
for (CodegenResponse resp : responses) {
if ("0".equals(resp.code)) {
resp.code = "200";
}
}
}
if (operation.returnType == null) {
operation.returnType = "Void";
} else if (operation.returnType.startsWith("List")) {
String rt = operation.returnType;
int end = rt.lastIndexOf(">");
if (end > 0) {
operation.returnType = rt.substring("List<".length(), end).trim();
operation.returnContainer = "List";
}
} else if (operation.returnType.startsWith("Map")) {
String rt = operation.returnType;
int end = rt.lastIndexOf(">");
if (end > 0) {
operation.returnType = rt.substring("Map<".length(), end).split(",")[1].trim();
operation.returnContainer = "Map";
}
} else if (operation.returnType.startsWith("Set")) {
String rt = operation.returnType;
int end = rt.lastIndexOf(">");
if (end > 0) {
operation.returnType = rt.substring("Set<".length(), end).trim();
operation.returnContainer = "Set";
}
}
}
}
return objs;
}
@Override
public String toApiName(String name) {
if (name.length() == 0) {
return "DefaultApi";
}
name = sanitizeName(name);
return camelize(name) + "Api";
}
@Override
public String apiFilename(String templateName, String tag) {
String result = super.apiFilename(templateName, tag);
if (templateName.endsWith("Impl.mustache")) {
int ix = result.lastIndexOf('/');
result = result.substring(0, ix) + "/impl" + result.substring(ix, result.length() - 5) + "ServiceImpl.java";
result = result.replace(apiFileFolder(), implFileFolder(implFolder));
} else if (templateName.endsWith("Factory.mustache")) {
int ix = result.lastIndexOf('/');
result = result.substring(0, ix) + "/factories" + result.substring(ix, result.length() - 5) + "ServiceFactory.java";
result = result.replace(apiFileFolder(), implFileFolder(implFolder));
} else if (templateName.endsWith("Service.mustache")) {
int ix = result.lastIndexOf('.');
result = result.substring(0, ix) + "Service.java";
}
return result;
}
private String implFileFolder(String output) {
return outputFolder + "/" + output + "/" + apiPackage().replace('.', '/');
}
@Override
public boolean shouldOverwrite(String filename) {
return super.shouldOverwrite(filename) && !filename.endsWith("ServiceImpl.java") && !filename.endsWith("ServiceFactory.java");
}
}

View File

@@ -20,7 +20,13 @@ import java.math.BigDecimal;
import java.util.*;
import java.util.Map.Entry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig {
private static final Logger LOGGER = LoggerFactory.getLogger(NodeJSServerCodegen.class);
protected String apiVersion = "1.0.0";
protected int serverPort = 8080;
protected String projectName = "swagger-server";
@@ -284,7 +290,7 @@ public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig
});
objs.put("swagger-yaml", Yaml.mapper().registerModule(module).writeValueAsString(swagger));
} catch (JsonProcessingException e) {
e.printStackTrace();
LOGGER.error(e.getMessage(), e);
}
}
for (Map<String, Object> operations : getOperations(objs)) {

View File

@@ -29,6 +29,7 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig {
protected String gemName;
protected String moduleName;
protected String gemVersion = "1.0.0";
protected String specFolder = "spec";
protected String libFolder = "lib";
protected String gemLicense = "Apache-2.0";
protected String gemHomepage = "http://swagger.io";
@@ -47,6 +48,9 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig {
apiTemplateFiles.put("api.mustache", ".rb");
embeddedTemplateDir = templateDir = "ruby";
modelTestTemplateFiles.put("model_test.mustache", ".rb");
apiTestTemplateFiles.put("api_test.mustache", ".rb");
typeMapping.clear();
languageSpecificPrimitives.clear();
@@ -235,6 +239,16 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig {
return outputFolder + File.separator + libFolder + File.separator + gemName + File.separator + modelPackage.replace("/", File.separator);
}
@Override
public String apiTestFileFolder() {
return outputFolder + File.separator + specFolder + File.separator + apiPackage.replace("/", File.separator);
}
@Override
public String modelTestFileFolder() {
return outputFolder + File.separator + specFolder + File.separator + modelPackage.replace("/", File.separator);
}
@Override
public String getTypeDeclaration(Property p) {
if (p instanceof ArrayProperty) {
@@ -367,6 +381,16 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig {
return underscore(name) + "_api";
}
@Override
public String toApiTestFilename(String name) {
return toApiName(name) + "_spec";
}
@Override
public String toModelTestFilename(String name) {
return toModelName(name) + "_spec";
}
@Override
public String toApiName(String name) {
if (name.length() == 0) {

View File

@@ -17,7 +17,14 @@ import java.util.Arrays;
import java.util.HashSet;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SinatraServerCodegen extends DefaultCodegen implements CodegenConfig {
private static final Logger LOGGER = LoggerFactory.getLogger(SinatraServerCodegen.class);
protected String gemName;
protected String moduleName;
protected String gemVersion = "1.0.0";
@@ -230,7 +237,7 @@ public class SinatraServerCodegen extends DefaultCodegen implements CodegenConfi
try {
objs.put("swagger-yaml", Yaml.mapper().writeValueAsString(swagger));
} catch (JsonProcessingException e) {
e.printStackTrace();
LOGGER.error(e.getMessage(), e);
}
}
return super.postProcessSupportingFileData(objs);

View File

@@ -1,16 +1,22 @@
package io.swagger.codegen.languages;
import java.io.File;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile;
import io.swagger.models.Swagger;
import io.swagger.util.Json;
import org.apache.commons.io.FileUtils;
import java.io.File;
public class SwaggerGenerator extends DefaultCodegen implements CodegenConfig {
private static final Logger LOGGER = LoggerFactory.getLogger(SwaggerGenerator.class);
public SwaggerGenerator() {
super();
embeddedTemplateDir = templateDir = "swagger";
@@ -41,9 +47,9 @@ public class SwaggerGenerator extends DefaultCodegen implements CodegenConfig {
try {
String outputFile = outputFolder + File.separator + "swagger.json";
FileUtils.writeStringToFile(new File(outputFile), swaggerString);
System.out.println("wrote file to " + outputFile);
LOGGER.debug("wrote file to " + outputFile);
} catch (Exception e) {
e.printStackTrace();
LOGGER.error(e.getMessage(), e);
}
}
}

View File

@@ -1,16 +1,22 @@
package io.swagger.codegen.languages;
import java.io.File;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile;
import io.swagger.models.Swagger;
import io.swagger.util.Yaml;
import org.apache.commons.io.FileUtils;
import java.io.File;
public class SwaggerYamlGenerator extends DefaultCodegen implements CodegenConfig {
private static final Logger LOGGER = LoggerFactory.getLogger(SwaggerYamlGenerator.class);
public SwaggerYamlGenerator() {
super();
embeddedTemplateDir = templateDir = "swagger";
@@ -40,9 +46,9 @@ public class SwaggerYamlGenerator extends DefaultCodegen implements CodegenConfi
String swaggerString = Yaml.mapper().writeValueAsString(swagger);
String outputFile = outputFolder + File.separator + "swagger.yaml";
FileUtils.writeStringToFile(new File(outputFile), swaggerString);
System.out.println("wrote file to " + outputFile);
LOGGER.debug("wrote file to " + outputFile);
} catch (Exception e) {
e.printStackTrace();
LOGGER.error(e.getMessage(), e);
}
}
}

View File

@@ -1,4 +1,4 @@
package io.swagger.codegen.cmd.utils;
package io.swagger.codegen.utils;
import org.apache.commons.lang3.tuple.Pair;

View File

@@ -13,6 +13,7 @@ import org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuil
import retrofit.Converter;
import retrofit.Retrofit;
import retrofit.GsonConverterFactory;
{{#useRxJava}}import retrofit.RxJavaCallAdapterFactory;{{/useRxJava}}
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
@@ -22,6 +23,7 @@ import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.ResponseBody;
import {{invokerPackage}}.auth.HttpBasicAuth;
import {{invokerPackage}}.auth.ApiKeyAuth;
import {{invokerPackage}}.auth.OAuth;
@@ -117,6 +119,7 @@ public class ApiClient {
.Builder()
.baseUrl(baseUrl)
.client(okClient)
{{#useRxJava}}.addCallAdapterFactory(RxJavaCallAdapterFactory.create()){{/useRxJava}}
.addConverterFactory(GsonCustomConverterFactory.create(gson));
}

View File

@@ -2,8 +2,10 @@ package {{package}};
import {{invokerPackage}}.CollectionFormats.*;
import retrofit.Call;
{{#useRxJava}}import rx.Observable;{{/useRxJava}}
{{^useRxJava}}import retrofit.Call;{{/useRxJava}}
import retrofit.http.*;
import com.squareup.okhttp.RequestBody;
{{#imports}}import {{import}};
@@ -25,7 +27,7 @@ public interface {{classname}} {
{{#formParams}}{{#-first}}
{{#isMultipart}}@Multipart{{/isMultipart}}{{^isMultipart}}@FormUrlEncoded{{/isMultipart}}{{/-first}}{{/formParams}}
@{{httpMethod}}("{{path}}")
Call<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Object{{/returnType}}> {{operationId}}({{^allParams}});{{/allParams}}
{{#useRxJava}}Observable{{/useRxJava}}{{^useRxJava}}Call{{/useRxJava}}<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Object{{/returnType}}> {{operationId}}({{^allParams}});{{/allParams}}
{{#allParams}}{{>libraries/retrofit2/queryParams}}{{>libraries/retrofit2/pathParams}}{{>libraries/retrofit2/headerParams}}{{>libraries/retrofit2/bodyParams}}{{>libraries/retrofit2/formParams}}{{#hasMore}}, {{/hasMore}}{{^hasMore}}
);{{/hasMore}}{{/allParams}}

View File

@@ -20,7 +20,7 @@ if(hasProperty('target') && target == 'android') {
apply plugin: 'com.android.library'
apply plugin: 'com.github.dcendents.android-maven'
android {
compileSdkVersion 22
buildToolsVersion '22.0.0'
@@ -32,7 +32,7 @@ if(hasProperty('target') && target == 'android') {
sourceCompatibility JavaVersion.VERSION_1_7
targetCompatibility JavaVersion.VERSION_1_7
}
// Rename the aar correctly
libraryVariants.all { variant ->
variant.outputs.each { output ->
@@ -44,7 +44,7 @@ if(hasProperty('target') && target == 'android') {
}
}
}
afterEvaluate {
android.libraryVariants.all { variant ->
def task = project.tasks.create "jar${variant.name.capitalize()}", Jar
@@ -56,12 +56,12 @@ if(hasProperty('target') && target == 'android') {
artifacts.add('archives', task);
}
}
task sourcesJar(type: Jar) {
from android.sourceSets.main.java.srcDirs
classifier = 'sources'
}
artifacts {
archives sourcesJar
}
@@ -70,16 +70,16 @@ if(hasProperty('target') && target == 'android') {
apply plugin: 'java'
apply plugin: 'maven'
sourceCompatibility = JavaVersion.VERSION_1_7
targetCompatibility = JavaVersion.VERSION_1_7
sourceCompatibility = JavaVersion.VERSION_1_7
targetCompatibility = JavaVersion.VERSION_1_7
install {
repositories.mavenInstaller {
pom.artifactId = '{{artifactId}}'
}
}
task execute(type:JavaExec) {
main = System.getProperty('mainClass')
classpath = sourceSets.main.runtimeClasspath
@@ -93,14 +93,26 @@ ext {
gson_version = "2.4"
swagger_annotations_version = "1.5.0"
junit_version = "4.12"
{{#useRxJava}}
rx_java_version = "1.0.15"
{{/useRxJava}}
{{^useRxJava}}{{/useRxJava}}
}
dependencies {
compile "com.squareup.okhttp:okhttp:$okhttp_version"
compile "com.squareup.retrofit:retrofit:$retrofit_version"
compile "com.google.code.gson:gson:$gson_version"
compile "com.squareup.retrofit:converter-gson:$retrofit_version"
{{#useRxJava}}
compile "com.squareup.retrofit:adapter-rxjava:$retrofit_version"
compile "io.reactivex:rxjava:$rx_java_version"
{{/useRxJava}}
{{^useRxJava}}{{/useRxJava}}
compile "com.google.code.gson:gson:$gson_version"
compile "io.swagger:swagger-annotations:$swagger_annotations_version"
compile "org.apache.oltu.oauth2:org.apache.oltu.oauth2.client:$oltu_version"
testCompile "junit:junit:$junit_version"
}

View File

@@ -100,8 +100,9 @@
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
<source>
1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
@@ -137,6 +138,18 @@
<artifactId>okhttp</artifactId>
<version>${okhttp-version}</version>
</dependency>
{{#useRxJava}}
<dependency>
<groupId>io.reactivex</groupId>
<artifactId>rxjava</artifactId>
<version>${rxjava-version}</version>
</dependency>
<dependency>
<groupId>com.squareup.retrofit</groupId>
<artifactId>adapter-rxjava</artifactId>
<version>${retrofit-version}</version>
</dependency>
{{/useRxJava}}
<!-- test dependencies -->
<dependency>
@@ -149,6 +162,7 @@
<properties>
<swagger-annotations-version>1.5.0</swagger-annotations-version>
<retrofit-version>2.0.0-beta2</retrofit-version>
{{#useRxJava}}<rxjava-version>1.0.15</rxjava-version>{{/useRxJava}}
<okhttp-version>2.5.0</okhttp-version>
<gson-version>2.4</gson-version>
<oltu-version>1.0.0</oltu-version>

View File

@@ -0,0 +1 @@
{{#allowableValues}}allowableValues="{{#values}}{{{.}}}{{^-last}}, {{/-last}}{{/values}}{{^values}}range=[{{#min}}{{.}}{{/min}}{{^min}}-infinity{{/min}}, {{#max}}{{.}}{{/max}}{{^max}}infinity{{/max}}]{{/values}}"{{/allowableValues}}

View File

@@ -0,0 +1,22 @@
package {{package}};
{{#imports}}import {{import}};
{{/imports}}
import javax.ws.rs.*;
import javax.ws.rs.core.Response;
@Path("{{contextPath}}")
public interface {{classname}} {
{{#operations}}
{{#operation}}
@{{httpMethod}}
{{#subresourceOperation}}@Path("{{path}}"){{/subresourceOperation}}
{{#hasConsumes}}@Consumes({ {{#consumes}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} }){{/hasConsumes}}
{{#hasProduces}}@Produces({ {{#produces}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }){{/hasProduces}}
public Response {{nickname}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}},
{{/hasMore}}{{/allParams}});
{{/operation}}
}
{{/operations}}

View File

@@ -0,0 +1 @@
{{#isBodyParam}}{{{dataType}}} {{paramName}}{{/isBodyParam}}

View File

@@ -0,0 +1,51 @@
package {{package}};
{{#imports}}import {{import}};
{{/imports}}
import javax.xml.bind.annotation.XmlRootElement;
{{#models}}
{{#model}}{{#description}}
/**
* {{description}}
**/{{/description}}
@XmlRootElement(name="{{classname}}")
public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {
{{#vars}}
{{#isEnum}}
public enum {{datatypeWithEnum}} {
{{#allowableValues}}{{#values}} {{.}}, {{/values}}{{/allowableValues}}
};
private {{{datatypeWithEnum}}} {{name}} = {{{defaultValue}}};{{/isEnum}}{{^isEnum}}
private {{{datatype}}} {{name}} = {{{defaultValue}}};{{/isEnum}}{{/vars}}
{{#vars}}
/**{{#description}}
* {{{description}}}{{/description}}{{#minimum}}
* minimum: {{minimum}}{{/minimum}}{{#maximum}}
* maximum: {{maximum}}{{/maximum}}
**/
@JsonProperty("{{name}}")
public {{{datatypeWithEnum}}} {{getter}}() {
return {{name}};
}
public void {{setter}}({{{datatypeWithEnum}}} {{name}}) {
this.{{name}} = {{name}};
}
{{/vars}}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class {{classname}} {\n");
{{#parent}}sb.append(" " + super.toString()).append("\n");{{/parent}}
{{#vars}}sb.append(" {{name}}: ").append({{name}}).append("\n");
{{/vars}}sb.append("}\n");
return sb.toString();
}
}
{{/model}}
{{/models}}

View File

@@ -0,0 +1,3 @@
public enum {{classname}} {
{{#allowableValues}}{{.}}{{^-last}}, {{/-last}}{{/allowableValues}}
}

View File

@@ -0,0 +1,2 @@
{{#isFormParam}}{{#notFile}}@Multipart(value = "{{paramName}}"{{^required}}, required = false{{/required}}) {{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}} @Multipart(value = "{{paramName}}"{{^required}}, required = false{{/required}}) InputStream {{paramName}}InputStream,
@Multipart(value = "{{paramName}}" {{^required}}, required = false{{/required}}) Attachment {{paramName}}Detail{{/isFile}}{{/isFormParam}}

View File

@@ -0,0 +1 @@
@javax.annotation.Generated(value = "{{generatorClass}}", date = "{{generatedDate}}")

View File

@@ -0,0 +1 @@
{{#isHeaderParam}}@HeaderParam("{{baseName}}") {{{dataType}}} {{paramName}}{{/isHeaderParam}}

View File

@@ -0,0 +1,15 @@
package {{package}};
{{#imports}}import{{import}};
{{/imports}}
{{#serializableModel}}import java.io.Serializable;{{/serializableModel}}
{{#models}}
{{#model}}{{#description}}
/**
* {{description}}
**/{{/description}}
{{#isEnum}}{{>enumOuterClass}}{{/isEnum}}
{{^isEnum}}{{>pojo}}{{/isEnum}}
{{/model}}
{{/models}}

View File

@@ -0,0 +1 @@
{{#isPathParam}}@PathParam("{{baseName}}") {{{dataType}}} {{paramName}}{{/isPathParam}}

View File

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

View File

@@ -0,0 +1 @@
{{#isQueryParam}}@QueryParam("{{baseName}}") {{{dataType}}} {{paramName}}{{/isQueryParam}}

View File

@@ -16,7 +16,15 @@
'use strict';
var ApiClient = function ApiClient() {
/**
* The base path to put in front of every API call's (relative) path.
*/
this.basePath = '{{basePath}}'.replace(/\/+$/, '');
/**
* The default HTTP headers to be included for all API calls.
*/
this.defaultHeaders = {};
};
ApiClient.prototype.paramToString = function paramToString(param) {
@@ -76,6 +84,26 @@
return mimes[0];
};
/**
* Check if the given parameter value is like file content.
*/
ApiClient.prototype.isFileParam = function isFileParam(param) {
// Buffer or fs.ReadStream in Node.js
if (typeof module === 'object' && module.exports &&
(param instanceof Buffer || param instanceof require('fs').ReadStream)) {
return true;
}
// Blob in browser
if (typeof Blob === 'function' && param instanceof Blob) {
return true;
}
// File in browser (it seems File object is also instance of Blob, but keep this for safe)
if (typeof File === 'function' && param instanceof File) {
return true;
}
return false;
};
/**
* Normalize parameters values:
* remove nils,
@@ -87,7 +115,7 @@
for (var key in params) {
if (params.hasOwnProperty(key) && params[key] != null) {
var value = params[key];
if (value instanceof Blob || Array.isArray(value)) {
if (this.isFileParam(value) || Array.isArray(value)) {
newParams[key] = value;
} else {
newParams[key] = this.paramToString(value);
@@ -107,10 +135,14 @@
request.query(this.normalizeParams(queryParams));
// set header parameters
request.set(this.normalizeParams(headerParams));
request.set(this.defaultHeaders).set(this.normalizeParams(headerParams));
var contentType = this.jsonPreferredMime(contentTypes) || 'application/json';
request.type(contentType);
var contentType = this.jsonPreferredMime(contentTypes);
if (contentType) {
request.type(contentType);
} else if (!request.header['Content-Type']) {
request.type('application/json');
}
if (contentType === 'application/x-www-form-urlencoded') {
request.send(this.normalizeParams(formParams));
@@ -118,7 +150,7 @@
var _formParams = this.normalizeParams(formParams);
for (var key in _formParams) {
if (_formParams.hasOwnProperty(key)) {
if (_formParams[key] instanceof Blob) {
if (this.isFileParam(_formParams[key])) {
// file field
request.attach(key, _formParams[key]);
} else {

View File

@@ -8,7 +8,7 @@
"test": "./node_modules/mocha/bin/mocha --recursive"
},
"dependencies": {
"superagent": "^1.6.1"
"superagent": "1.7.1"
},
"devDependencies": {
"mocha": "~2.3.4",

View File

@@ -6,9 +6,10 @@ 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
io.swagger.codegen.languages.JavaJerseyServerCodegen
io.swagger.codegen.languages.JavaCXFServerCodegen
io.swagger.codegen.languages.JavaInflectorServerCodegen
io.swagger.codegen.languages.JavascriptClientCodegen
io.swagger.codegen.languages.JMeterCodegen
io.swagger.codegen.languages.NodeJSServerCodegen
io.swagger.codegen.languages.ObjcClientCodegen

View File

@@ -18,7 +18,7 @@ namespace {{package}} {
* {{{description}}}
*/
{{/description}}
{{name}}{{^required}}?{{/required}}: {{#isEnum}}{{classname}}.{{{datatypeWithEnum}}}{{/isEnum}}{{^isEnum}}{{{datatype}}}{{/isEnum}};
"{{name}}"{{^required}}?{{/required}}: {{#isEnum}}{{classname}}.{{{datatypeWithEnum}}}{{/isEnum}}{{^isEnum}}{{{datatype}}}{{/isEnum}};
{{/vars}}
}

View File

@@ -22,7 +22,7 @@ export class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}{
* {{{description}}}
*/
{{/description}}
{{name}}: {{#isEnum}}{{classname}}.{{{datatypeWithEnum}}}{{/isEnum}}{{^isEnum}}{{{datatype}}}{{/isEnum}};
"{{name}}": {{#isEnum}}{{classname}}.{{{datatypeWithEnum}}}{{/isEnum}}{{^isEnum}}{{{datatype}}}{{/isEnum}};
{{/vars}}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,43 @@
require 'spec_helper'
require 'json'
# Unit tests for {{moduleName}}::{{classname}}
# Automatically generated by swagger-codegen (github.com/swagger-api/swagger-codegen)
# Please update as you see appropriate
{{#operations}}describe '{{classname}}' do
before do
# run before each test
@instance = {{moduleName}}::{{classname}}.new
end
after do
# run after each test
end
describe 'test an instance of {{classname}}' do
it 'should create an instact of {{classname}}' do
@instance.should be_a({{moduleName}}::{{classname}})
end
end
{{#operation}}
# unit tests for {{operationId}}
# {{summary}}
# {{notes}}
{{#allParams}}{{#required}} # @param {{paramName}} {{description}}
{{/required}}{{/allParams}} # @param [Hash] opts the optional parameters
{{#allParams}}{{^required}} # @option opts [{{{dataType}}}] :{{paramName}} {{description}}
{{/required}}{{/allParams}} # @return [{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}nil{{/returnType}}]
describe '{{operationId}} test' do
it "should work" do
# assertion here
# should be_a()
# should be_nil
# should ==
# should_not ==
end
end
{{/operation}}
end
{{/operations}}

View File

@@ -0,0 +1,36 @@
require 'spec_helper'
require 'json'
require 'date'
# Unit tests for {{moduleName}}::{{classname}}
# Automatically generated by swagger-codegen (github.com/swagger-api/swagger-codegen)
# Please update as you see appropriate
{{#models}}{{#model}}describe '{{classname}}' do
before do
# run before each test
@instance = {{moduleName}}::{{classname}}.new
end
after do
# run after each test
end
describe 'test an instance of {{classname}}' do
it 'should create an instact of {{classname}}' do
@instance.should be_a({{moduleName}}::{{classname}})
end
end
{{#vars}}
describe 'test attribute "{{{name}}}"' do
it 'should work' do
# assertion here
# should be_a()
# should be_nil
# should ==
# should_not ==
end
end
{{/vars}}
end
{{/model}}{{/models}}

View File

@@ -0,0 +1,99 @@
package io.swagger.codegen.csharp;
import io.swagger.codegen.CodegenModel;
import io.swagger.codegen.CodegenProperty;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.languages.CSharpClientCodegen;
import io.swagger.models.Model;
import io.swagger.models.ModelImpl;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.LongProperty;
import io.swagger.models.properties.StringProperty;
import org.testng.Assert;
import org.testng.annotations.Test;
@SuppressWarnings("static-method")
public class CSharpModelTest {
@Test(description = "convert a model with array property to default List<T>")
public void arrayPropertyTest() {
final Model model = getArrayTestModel();
final DefaultCodegen codegen = new CSharpClientCodegen();
final CodegenModel generated = codegen.fromModel("sample", model);
Assert.assertEquals(generated.name, "sample");
Assert.assertEquals(generated.classname, "Sample");
Assert.assertEquals(generated.description, "a sample model");
Assert.assertEquals(generated.vars.size(), 2);
final CodegenProperty property = generated.vars.get(1);
Assert.assertEquals(property.baseName, "examples");
Assert.assertEquals(property.getter, "getExamples");
Assert.assertEquals(property.setter, "setExamples");
Assert.assertEquals(property.datatype, "List<string>");
Assert.assertEquals(property.name, "Examples");
Assert.assertEquals(property.defaultValue, null);
Assert.assertEquals(property.baseType, "List");
Assert.assertEquals(property.containerType, "array");
Assert.assertNull(property.required);
Assert.assertTrue(property.isContainer);
}
@Test(description = "convert a model with array property to Collection<T>")
public void arrayPropertyCollectionOptionTest() {
final Model model = getArrayTestModel();
final CSharpClientCodegen codegen = new CSharpClientCodegen();
codegen.setUseCollection(true);
final CodegenModel generated = codegen.fromModel("sample", model);
Assert.assertEquals(generated.name, "sample");
Assert.assertEquals(generated.vars.size(), 2);
final CodegenProperty property = generated.vars.get(1);
Assert.assertEquals(property.baseName, "examples");
Assert.assertEquals(property.name, "Examples");
Assert.assertEquals(property.defaultValue, null);
Assert.assertEquals(property.datatype, "Collection<string>");
Assert.assertEquals(property.baseType, "Collection");
Assert.assertEquals(property.containerType, "array");
Assert.assertNull(property.required);
Assert.assertTrue(property.isContainer);
}
@Test(description = "convert a model with array property to Collection<T>")
public void arrayPropertyICollectionOptionTest() {
final Model model = getArrayTestModel();
final CSharpClientCodegen codegen = new CSharpClientCodegen();
codegen.setUseCollection(true);
codegen.setReturnICollection(true);
final CodegenModel generated = codegen.fromModel("sample", model);
Assert.assertEquals(generated.name, "sample");
Assert.assertEquals(generated.vars.size(), 2);
final CodegenProperty property = generated.vars.get(1);
Assert.assertEquals(property.baseName, "examples");
Assert.assertEquals(property.name, "Examples");
Assert.assertEquals(property.datatype, "Collection<string>",
"returnICollection option should not modify property datatype");
Assert.assertEquals(property.defaultValue, null);
Assert.assertEquals(property.baseType, "Collection",
"returnICollection option should not modify property baseType");
Assert.assertEquals(property.containerType, "array");
Assert.assertNull(property.required);
Assert.assertTrue(property.isContainer);
}
private Model getArrayTestModel() {
return new ModelImpl()
.description("a sample model")
.property("id", new LongProperty())
.property("examples", new ArrayProperty().items(new StringProperty()))
.required("id");
}
}

View File

@@ -45,7 +45,7 @@ public class JavaInflectorServerOptionsTest extends JavaClientOptionsTest {
times = 1;
clientCodegen.setSerializableModel(Boolean.valueOf(JavaInflectorServerOptionsProvider.SERIALIZABLE_MODEL_VALUE));
times = 1;
clientCodegen.setLibrary(JavaInflectorServerOptionsProvider.LIBRARY_VALUE);
clientCodegen.setLibrary(JavaInflectorServerOptionsProvider.DEFAULT_LIBRARY_VALUE);
times = 1;
clientCodegen.setFullJavaUtil(Boolean.valueOf(JavaInflectorServerOptionsProvider.FULL_JAVA_UTIL_VALUE));
times = 1;

View File

@@ -51,7 +51,7 @@ public class JavaClientOptionsTest extends AbstractOptionsTest {
times = 1;
clientCodegen.setSerializableModel(Boolean.valueOf(JavaOptionsProvider.SERIALIZABLE_MODEL_VALUE));
times = 1;
clientCodegen.setLibrary(JavaOptionsProvider.LIBRARY_VALUE);
clientCodegen.setLibrary(JavaOptionsProvider.DEFAULT_LIBRARY_VALUE);
times = 1;
clientCodegen.setFullJavaUtil(Boolean.valueOf(JavaOptionsProvider.FULL_JAVA_UTIL_VALUE));
times = 1;

View File

@@ -2,7 +2,7 @@ package io.swagger.codegen.jaxrs;
import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.java.JavaClientOptionsTest;
import io.swagger.codegen.languages.JaxRSServerCodegen;
import io.swagger.codegen.languages.JavaJerseyServerCodegen;
import io.swagger.codegen.options.JaxRSServerOptionsProvider;
import mockit.Expectations;
@@ -11,7 +11,7 @@ import mockit.Tested;
public class JaxRSServerOptionsTest extends JavaClientOptionsTest {
@Tested
private JaxRSServerCodegen clientCodegen;
private JavaJerseyServerCodegen clientCodegen;
public JaxRSServerOptionsTest() {
super(new JaxRSServerOptionsProvider());
@@ -46,7 +46,7 @@ public class JaxRSServerOptionsTest extends JavaClientOptionsTest {
times = 1;
clientCodegen.setSerializableModel(Boolean.valueOf(JaxRSServerOptionsProvider.SERIALIZABLE_MODEL_VALUE));
times = 1;
clientCodegen.setLibrary(JaxRSServerOptionsProvider.LIBRARY_VALUE);
clientCodegen.setLibrary(JaxRSServerOptionsProvider.DEFAULT_LIBRARY_VALUE);
times = 1;
clientCodegen.setFullJavaUtil(Boolean.valueOf(JaxRSServerOptionsProvider.FULL_JAVA_UTIL_VALUE));
times = 1;

View File

@@ -2,7 +2,7 @@ package io.swagger.codegen.jaxrs;
import io.swagger.codegen.CodegenModel;
import io.swagger.codegen.languages.JaxRSServerCodegen;
import io.swagger.codegen.languages.JavaJerseyServerCodegen;
import io.swagger.models.Model;
import io.swagger.models.ModelImpl;
import io.swagger.models.properties.DateProperty;
@@ -26,7 +26,7 @@ public class JaxrsJava8ModelTest {
.required("id")
.required("name");
final JaxRSServerCodegen codegen = new JaxRSServerCodegen();
final JavaJerseyServerCodegen codegen = new JavaJerseyServerCodegen();
codegen.setDateLibrary("java8");
codegen.processOpts();
final CodegenModel cm = codegen.fromModel("sample", model);

View File

@@ -1,7 +1,7 @@
package io.swagger.codegen.jaxrs;
import io.swagger.codegen.CodegenModel;
import io.swagger.codegen.languages.JaxRSServerCodegen;
import io.swagger.codegen.languages.JavaJerseyServerCodegen;
import io.swagger.models.Model;
import io.swagger.models.ModelImpl;
import io.swagger.models.properties.DateProperty;
@@ -25,7 +25,7 @@ public class JaxrsJodaModelTest {
.required("id")
.required("name");
final JaxRSServerCodegen codegen = new JaxRSServerCodegen();
final JavaJerseyServerCodegen codegen = new JavaJerseyServerCodegen();
codegen.setDateLibrary("joda");
codegen.processOpts();
final CodegenModel cm = codegen.fromModel("sample", model);

View File

@@ -1,5 +1,6 @@
package io.swagger.codegen.options;
import io.swagger.codegen.Codegen;
import io.swagger.codegen.CodegenConstants;
import io.swagger.codegen.languages.JavaClientCodegen;
@@ -17,15 +18,19 @@ public class JavaOptionsProvider implements OptionsProvider {
public static final String ARTIFACT_VERSION_VALUE = "1.0.0-SNAPSHOT";
public static final String SOURCE_FOLDER_VALUE = "src/main/java/test";
public static final String LOCAL_PREFIX_VALUE = "tst";
public static final String LIBRARY_VALUE = "jersey2";
public static final String DEFAULT_LIBRARY_VALUE = "jersey2";
public static final String SERIALIZABLE_MODEL_VALUE = "false";
public static final String FULL_JAVA_UTIL_VALUE = "true";
public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true";
@Override
public Map<String, String> createOptions() {
ImmutableMap.Builder<String, String> builder = new ImmutableMap.Builder<String, String>();
return builder.put(CodegenConstants.MODEL_PACKAGE, MODEL_PACKAGE_VALUE)
private ImmutableMap<String, String> options;
/**
* Create an options provider with the default options.
*/
public JavaOptionsProvider() {
options = new ImmutableMap.Builder<String, String>()
.put(CodegenConstants.MODEL_PACKAGE, MODEL_PACKAGE_VALUE)
.put(CodegenConstants.API_PACKAGE, API_PACKAGE_VALUE)
.put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE)
.put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE)
@@ -37,12 +42,28 @@ public class JavaOptionsProvider implements OptionsProvider {
.put(CodegenConstants.LOCAL_VARIABLE_PREFIX, LOCAL_PREFIX_VALUE)
.put(CodegenConstants.SERIALIZABLE_MODEL, SERIALIZABLE_MODEL_VALUE)
.put(JavaClientCodegen.FULL_JAVA_UTIL, FULL_JAVA_UTIL_VALUE)
.put(CodegenConstants.LIBRARY, LIBRARY_VALUE)
.put(CodegenConstants.LIBRARY, DEFAULT_LIBRARY_VALUE)
.put(CodegenConstants.SERIALIZE_BIG_DECIMAL_AS_STRING, "true")
.put(JavaClientCodegen.USE_RX_JAVA, "false")
.put(JavaClientCodegen.DATE_LIBRARY, "joda")
.build();
}
/**
* Use the default options, but override the ones found in additionalOptions.
*/
public JavaOptionsProvider(Map<String, String> additionalOptions) {
options = new ImmutableMap.Builder<String, String>()
.putAll(options)
.putAll(additionalOptions)
.build();
}
@Override
public Map<String, String> createOptions() {
return options;
}
@Override
public boolean isServer() {
return false;

View File

@@ -25,7 +25,9 @@ public class JaxRSServerOptionsProvider extends JavaOptionsProvider {
ImmutableMap.Builder<String, String> builder = new ImmutableMap.Builder<String, String>();
builder.putAll(options)
.put(CodegenConstants.IMPL_FOLDER, IMPL_FOLDER_VALUE);
.put(CodegenConstants.IMPL_FOLDER, IMPL_FOLDER_VALUE)
//.put(JavaJaxRSJersey1ServerCodegen.DATE_LIBRARY, "joda") //java.lang.IllegalArgumentException: Multiple entries with same key: dateLibrary=joda and dateLibrary=joda
;
return builder.build();
}

View File

@@ -9,6 +9,7 @@ import java.util.Map;
public class TypeScriptAngularClientOptionsProvider implements OptionsProvider {
public static final String SORT_PARAMS_VALUE = "false";
public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true";
public static final String MODEL_PROPERTY_NAMING_VALUE = "camelCase";
@Override
public String getLanguage() {
@@ -20,6 +21,7 @@ public class TypeScriptAngularClientOptionsProvider implements OptionsProvider {
ImmutableMap.Builder<String, String> builder = new ImmutableMap.Builder<String, String>();
return builder.put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE)
.put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE)
.put(CodegenConstants.MODEL_PROPERTY_NAMING, MODEL_PROPERTY_NAMING_VALUE)
.build();
}

View File

@@ -9,6 +9,7 @@ import java.util.Map;
public class TypeScriptNodeClientOptionsProvider implements OptionsProvider {
public static final String SORT_PARAMS_VALUE = "false";
public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true";
public static final String MODEL_PROPERTY_NAMING_VALUE = "camelCase";
@Override
public String getLanguage() {
@@ -20,6 +21,7 @@ public class TypeScriptNodeClientOptionsProvider implements OptionsProvider {
ImmutableMap.Builder<String, String> builder = new ImmutableMap.Builder<String, String>();
return builder.put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE)
.put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE)
.put(CodegenConstants.MODEL_PROPERTY_NAMING, MODEL_PROPERTY_NAMING_VALUE)
.build();
}

View File

@@ -28,6 +28,8 @@ public class TypeScriptAngularClientOptionsTest extends AbstractOptionsTest {
new Expectations(clientCodegen) {{
clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(TypeScriptAngularClientOptionsProvider.SORT_PARAMS_VALUE));
times = 1;
clientCodegen.setModelPropertyNaming(TypeScriptAngularClientOptionsProvider.MODEL_PROPERTY_NAMING_VALUE);
times = 1;
}};
}
}

View File

@@ -28,6 +28,8 @@ public class TypeScriptNodeClientOptionsTest extends AbstractOptionsTest {
new Expectations(clientCodegen) {{
clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(TypeScriptNodeClientOptionsProvider.SORT_PARAMS_VALUE));
times = 1;
clientCodegen.setModelPropertyNaming(TypeScriptNodeClientOptionsProvider.MODEL_PROPERTY_NAMING_VALUE);
times = 1;
}};
}
}

View File

@@ -122,7 +122,7 @@ public class Generator {
List<File> files = new Codegen().opts(clientOptInput).generate();
if (files.size() > 0) {
List<File> filesToAdd = new ArrayList<File>();
System.out.println("adding to " + outputFolder);
LOGGER.debug("adding to " + outputFolder);
filesToAdd.add(new File(outputFolder));
ZipUtil zip = new ZipUtil();
zip.compressFiles(filesToAdd, outputFilename);

View File

@@ -1,64 +1,31 @@
package io.swagger.generator.online;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotEquals;
import io.swagger.codegen.CliOption;
import io.swagger.codegen.CodegenConfigLoader;
import io.swagger.codegen.options.AkkaScalaClientOptionsProvider;
import io.swagger.codegen.options.AndroidClientOptionsProvider;
import io.swagger.codegen.options.AsyncScalaClientOptionsProvider;
import io.swagger.codegen.options.CSharpClientOptionsProvider;
import io.swagger.codegen.options.CsharpDotNet2ClientOptionsProvider;
import io.swagger.codegen.options.DartClientOptionsProvider;
import io.swagger.codegen.options.FlashClienOptionsProvider;
import io.swagger.codegen.options.JavaInflectorServerOptionsProvider;
import io.swagger.codegen.options.JavaOptionsProvider;
import io.swagger.codegen.options.JaxRSServerOptionsProvider;
import io.swagger.codegen.options.NodeJSServerOptionsProvider;
import io.swagger.codegen.options.ObjcClientOptionsProvider;
import io.swagger.codegen.options.OptionsProvider;
import io.swagger.codegen.options.PerlClientOptionsProvider;
import io.swagger.codegen.options.PhpClientOptionsProvider;
import io.swagger.codegen.options.PythonClientOptionsProvider;
import io.swagger.codegen.options.Qt5CPPOptionsProvider;
import io.swagger.codegen.options.RubyClientOptionsProvider;
import io.swagger.codegen.options.ScalaClientOptionsProvider;
import io.swagger.codegen.options.ScalatraServerOptionsProvider;
import io.swagger.codegen.options.SilexServerOptionsProvider;
import io.swagger.codegen.options.SinatraServerOptionsProvider;
import io.swagger.codegen.options.SlimFrameworkServerOptionsProvider;
import io.swagger.codegen.options.SpringMVCServerOptionsProvider;
import io.swagger.codegen.options.StaticDocOptionsProvider;
import io.swagger.codegen.options.StaticHtmlOptionsProvider;
import io.swagger.codegen.options.SwaggerOptionsProvider;
import io.swagger.codegen.options.SwaggerYamlOptionsProvider;
import io.swagger.codegen.options.SwiftOptionsProvider;
import io.swagger.codegen.options.TizenClientOptionsProvider;
import io.swagger.codegen.options.TypeScriptAngularClientOptionsProvider;
import io.swagger.codegen.options.TypeScriptNodeClientOptionsProvider;
import io.swagger.generator.exception.ApiException;
import io.swagger.generator.model.GeneratorInput;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import io.swagger.codegen.CliOption;
import io.swagger.codegen.CodegenConfigLoader;
import io.swagger.codegen.CodegenConstants;
import io.swagger.codegen.languages.JavaClientCodegen;
import io.swagger.codegen.options.*;
import io.swagger.generator.exception.ApiException;
import io.swagger.generator.model.GeneratorInput;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import javax.annotation.Nullable;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.*;
import javax.annotation.Nullable;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotEquals;
public class OnlineGeneratorOptionsTest {
private static final String OPTIONS_PROVIDER = "optionsProvider";
@@ -69,7 +36,16 @@ public class OnlineGeneratorOptionsTest {
{new AsyncScalaClientOptionsProvider()}, {new CSharpClientOptionsProvider()},
{new CsharpDotNet2ClientOptionsProvider()}, {new DartClientOptionsProvider()},
{new FlashClienOptionsProvider()}, {new JavaInflectorServerOptionsProvider()},
{new JavaOptionsProvider()}, {new JaxRSServerOptionsProvider()},
{
new JavaOptionsProvider(),
new JavaOptionsProvider(ImmutableMap.of(CodegenConstants.LIBRARY, JavaClientCodegen.RETROFIT_2)
),
new JavaOptionsProvider(ImmutableMap.of(
CodegenConstants.LIBRARY, JavaClientCodegen.RETROFIT_2,
JavaClientCodegen.USE_RX_JAVA, "true")
)
},
{new JaxRSServerOptionsProvider()},
{new NodeJSServerOptionsProvider()}, {new ObjcClientOptionsProvider()},
{new PerlClientOptionsProvider()}, {new PhpClientOptionsProvider()},
{new PythonClientOptionsProvider()}, {new Qt5CPPOptionsProvider()},

13
pom.xml
View File

@@ -342,6 +342,18 @@
<module>samples/client/petstore/java/retrofit2</module>
</modules>
</profile>
<profile>
<id>java-client-retrofit2-rx</id>
<activation>
<property>
<name>env</name>
<value>java</value>
</property>
</activation>
<modules>
<module>samples/client/petstore/java/retrofit2rx</module>
</modules>
</profile>
<profile>
<id>java-client-feign</id>
<activation>
@@ -443,6 +455,7 @@
<module>samples/client/petstore/java/okhttp-gson</module>
<module>samples/client/petstore/java/retrofit</module>
<module>samples/client/petstore/java/retrofit2</module>
<module>samples/client/petstore/java/retrofit2rx</module>
<module>samples/client/petstore/javascript</module>
<module>samples/client/petstore/scala</module>
<module>samples/server/petstore/spring-mvc</module>

View File

@@ -1,2 +0,0 @@
// <autogenerated />
[assembly: global::System.Runtime.Versioning.TargetFrameworkAttribute(".NETFramework,Version=v4.5", FrameworkDisplayName = "")]

View File

@@ -0,0 +1,43 @@
# swagger-petstore-retrofit2-rx
## Requirements
Building the API client library requires [Maven](https://maven.apache.org/) to be installed.
## Installation & Usage
To install the API client library to your local Maven repository, simply execute:
```shell
mvn install
```
To deploy it to a remote Maven repository instead, configure the settings of the repository and execute:
```shell
mvn deploy
```
Refer to the [official documentation](https://maven.apache.org/plugins/maven-deploy-plugin/usage.html) for more information.
After the client libarary is installed/deployed, you can use it in your Maven project by adding the following to your *pom.xml*:
```xml
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-petstore-retrofit2-rx</artifactId>
<version>1.0.0</version>
<scope>compile</scope>
</dependency>
```
## Recommendation
It's recommended to create an instance of `ApiClient` per thread in a multithreaded environment to avoid any potential issue.
## Author
apiteam@swagger.io

View File

@@ -0,0 +1,114 @@
group = 'io.swagger'
version = '1.0.0'
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:1.2.2'
classpath 'com.github.dcendents:android-maven-plugin:1.2'
}
}
repositories {
jcenter()
}
if(hasProperty('target') && target == 'android') {
apply plugin: 'com.android.library'
apply plugin: 'com.github.dcendents.android-maven'
android {
compileSdkVersion 22
buildToolsVersion '22.0.0'
defaultConfig {
minSdkVersion 14
targetSdkVersion 22
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_7
targetCompatibility JavaVersion.VERSION_1_7
}
// Rename the aar correctly
libraryVariants.all { variant ->
variant.outputs.each { output ->
def outputFile = output.outputFile
if (outputFile != null && outputFile.name.endsWith('.aar')) {
def fileName = "${project.name}-${variant.baseName}-${version}.aar"
output.outputFile = new File(outputFile.parent, fileName)
}
}
}
}
afterEvaluate {
android.libraryVariants.all { variant ->
def task = project.tasks.create "jar${variant.name.capitalize()}", Jar
task.description = "Create jar artifact for ${variant.name}"
task.dependsOn variant.javaCompile
task.from variant.javaCompile.destinationDir
task.destinationDir = project.file("${project.buildDir}/outputs/jar")
task.archiveName = "${project.name}-${variant.baseName}-${version}.jar"
artifacts.add('archives', task);
}
}
task sourcesJar(type: Jar) {
from android.sourceSets.main.java.srcDirs
classifier = 'sources'
}
artifacts {
archives sourcesJar
}
} else {
apply plugin: 'java'
apply plugin: 'maven'
sourceCompatibility = JavaVersion.VERSION_1_7
targetCompatibility = JavaVersion.VERSION_1_7
install {
repositories.mavenInstaller {
pom.artifactId = 'swagger-petstore-retrofit2-rx'
}
}
task execute(type:JavaExec) {
main = System.getProperty('mainClass')
classpath = sourceSets.main.runtimeClasspath
}
}
ext {
okhttp_version = "2.5.0"
oltu_version = "1.0.0"
retrofit_version = "2.0.0-beta2"
gson_version = "2.4"
swagger_annotations_version = "1.5.0"
junit_version = "4.12"
rx_java_version = "1.0.15"
}
dependencies {
compile "com.squareup.okhttp:okhttp:$okhttp_version"
compile "com.squareup.retrofit:retrofit:$retrofit_version"
compile "com.squareup.retrofit:converter-gson:$retrofit_version"
compile "com.squareup.retrofit:adapter-rxjava:$retrofit_version"
compile "io.reactivex:rxjava:$rx_java_version"
compile "com.google.code.gson:gson:$gson_version"
compile "io.swagger:swagger-annotations:$swagger_annotations_version"
compile "org.apache.oltu.oauth2:org.apache.oltu.oauth2.client:$oltu_version"
testCompile "junit:junit:$junit_version"
}

View File

@@ -0,0 +1,2 @@
# Uncomment to build for Android
#target = android

View File

@@ -0,0 +1 @@
Hello world!

View File

@@ -0,0 +1,173 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>io.swagger</groupId>
<artifactId>swagger-petstore-retrofit2-rx</artifactId>
<packaging>jar</packaging>
<name>swagger-petstore-retrofit2-rx</name>
<version>1.0.0</version>
<scm>
<connection>scm:git:git@github.com:swagger-api/swagger-mustache.git</connection>
<developerConnection>scm:git:git@github.com:swagger-api/swagger-codegen.git</developerConnection>
<url>https://github.com/swagger-api/swagger-codegen</url>
</scm>
<prerequisites>
<maven>2.2.0</maven>
</prerequisites>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.12</version>
<configuration>
<systemProperties>
<property>
<name>loggerPath</name>
<value>conf/log4j.properties</value>
</property>
</systemProperties>
<argLine>-Xms512m -Xmx1500m</argLine>
<parallel>methods</parallel>
<forkMode>pertest</forkMode>
</configuration>
</plugin>
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/lib</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
<!-- attach test jar -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.2</version>
<executions>
<execution>
<goals>
<goal>jar</goal>
<goal>test-jar</goal>
</goals>
</execution>
</executions>
<configuration>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<executions>
<execution>
<id>add_sources</id>
<phase>generate-sources</phase>
<goals>
<goal>add-source</goal>
</goals>
<configuration>
<sources>
<source>src/main/java</source>
</sources>
</configuration>
</execution>
<execution>
<id>add_test_sources</id>
<phase>generate-test-sources</phase>
<goals>
<goal>add-test-source</goal>
</goals>
<configuration>
<sources>
<source>src/test/java</source>
</sources>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>
1.7
</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-annotations</artifactId>
<version>${swagger-annotations-version}</version>
</dependency>
<dependency>
<groupId>com.squareup.retrofit</groupId>
<artifactId>retrofit</artifactId>
<version>${retrofit-version}</version>
</dependency>
<dependency>
<groupId>com.squareup.retrofit</groupId>
<artifactId>converter-gson</artifactId>
<version>${retrofit-version}</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>${gson-version}</version>
</dependency>
<dependency>
<groupId>org.apache.oltu.oauth2</groupId>
<artifactId>org.apache.oltu.oauth2.client</artifactId>
<version>${oltu-version}</version>
</dependency>
<dependency>
<groupId>com.squareup.okhttp</groupId>
<artifactId>okhttp</artifactId>
<version>${okhttp-version}</version>
</dependency>
<dependency>
<groupId>io.reactivex</groupId>
<artifactId>rxjava</artifactId>
<version>${rxjava-version}</version>
</dependency>
<dependency>
<groupId>com.squareup.retrofit</groupId>
<artifactId>adapter-rxjava</artifactId>
<version>${retrofit-version}</version>
</dependency>
<!-- test dependencies -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit-version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<swagger-annotations-version>1.5.0</swagger-annotations-version>
<retrofit-version>2.0.0-beta2</retrofit-version>
<rxjava-version>1.0.15</rxjava-version>
<okhttp-version>2.5.0</okhttp-version>
<gson-version>2.4</gson-version>
<oltu-version>1.0.0</oltu-version>
<maven-plugin-version>1.0.0</maven-plugin-version>
<junit-version>4.12</junit-version>
</properties>
</project>

View File

@@ -0,0 +1 @@
rootProject.name = "swagger-petstore-retrofit2-rx"

View File

@@ -0,0 +1,3 @@
<manifest package="io.swagger.client" xmlns:android="http://schemas.android.com/apk/res/android">
<application />
</manifest>

View File

@@ -0,0 +1,345 @@
package io.swagger.client;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;
import org.apache.oltu.oauth2.client.request.OAuthClientRequest.AuthenticationRequestBuilder;
import org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder;
import retrofit.Converter;
import retrofit.Retrofit;
import retrofit.GsonConverterFactory;
import retrofit.RxJavaCallAdapterFactory;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonParseException;
import com.squareup.okhttp.Interceptor;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.ResponseBody;
import io.swagger.client.auth.HttpBasicAuth;
import io.swagger.client.auth.ApiKeyAuth;
import io.swagger.client.auth.OAuth;
import io.swagger.client.auth.OAuth.AccessTokenListener;
import io.swagger.client.auth.OAuthFlow;
public class ApiClient {
private Map<String, Interceptor> apiAuthorizations;
private OkHttpClient okClient;
private Retrofit.Builder adapterBuilder;
public ApiClient() {
apiAuthorizations = new LinkedHashMap<String, Interceptor>();
createDefaultAdapter();
}
public ApiClient(String[] authNames) {
this();
for(String authName : authNames) {
Interceptor auth;
if (authName == "petstore_auth") {
auth = new OAuth(OAuthFlow.implicit, "http://petstore.swagger.io/api/oauth/dialog", "", "write:pets, read:pets");
} else if (authName == "api_key") {
auth = new ApiKeyAuth("header", "api_key");
} else {
throw new RuntimeException("auth name \"" + authName + "\" not found in available auth names");
}
addAuthorization(authName, auth);
}
}
/**
* Basic constructor for single auth name
* @param authName
*/
public ApiClient(String authName) {
this(new String[]{authName});
}
/**
* Helper constructor for single api key
* @param authName
* @param apiKey
*/
public ApiClient(String authName, String apiKey) {
this(authName);
this.setApiKey(apiKey);
}
/**
* Helper constructor for single basic auth or password oauth2
* @param authName
* @param username
* @param password
*/
public ApiClient(String authName, String username, String password) {
this(authName);
this.setCredentials(username, password);
}
/**
* Helper constructor for single password oauth2
* @param authName
* @param clientId
* @param secret
* @param username
* @param password
*/
public ApiClient(String authName, String clientId, String secret, String username, String password) {
this(authName);
this.getTokenEndPoint()
.setClientId(clientId)
.setClientSecret(secret)
.setUsername(username)
.setPassword(password);
}
public void createDefaultAdapter() {
Gson gson = new GsonBuilder()
.setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ")
.create();
okClient = new OkHttpClient();
String baseUrl = "http://petstore.swagger.io/v2";
if(!baseUrl.endsWith("/"))
baseUrl = baseUrl + "/";
adapterBuilder = new Retrofit
.Builder()
.baseUrl(baseUrl)
.client(okClient)
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.addConverterFactory(GsonCustomConverterFactory.create(gson));
}
public <S> S createService(Class<S> serviceClass) {
return adapterBuilder.build().create(serviceClass);
}
/**
* Helper method to configure the first api key found
* @param apiKey
*/
private void setApiKey(String apiKey) {
for(Interceptor apiAuthorization : apiAuthorizations.values()) {
if (apiAuthorization instanceof ApiKeyAuth) {
ApiKeyAuth keyAuth = (ApiKeyAuth) apiAuthorization;
keyAuth.setApiKey(apiKey);
return;
}
}
}
/**
* Helper method to configure the username/password for basic auth or password oauth
* @param username
* @param password
*/
private void setCredentials(String username, String password) {
for(Interceptor apiAuthorization : apiAuthorizations.values()) {
if (apiAuthorization instanceof HttpBasicAuth) {
HttpBasicAuth basicAuth = (HttpBasicAuth) apiAuthorization;
basicAuth.setCredentials(username, password);
return;
}
if (apiAuthorization instanceof OAuth) {
OAuth oauth = (OAuth) apiAuthorization;
oauth.getTokenRequestBuilder().setUsername(username).setPassword(password);
return;
}
}
}
/**
* Helper method to configure the token endpoint of the first oauth found in the apiAuthorizations (there should be only one)
* @return
*/
public TokenRequestBuilder getTokenEndPoint() {
for(Interceptor apiAuthorization : apiAuthorizations.values()) {
if (apiAuthorization instanceof OAuth) {
OAuth oauth = (OAuth) apiAuthorization;
return oauth.getTokenRequestBuilder();
}
}
return null;
}
/**
* Helper method to configure authorization endpoint of the first oauth found in the apiAuthorizations (there should be only one)
* @return
*/
public AuthenticationRequestBuilder getAuthorizationEndPoint() {
for(Interceptor apiAuthorization : apiAuthorizations.values()) {
if (apiAuthorization instanceof OAuth) {
OAuth oauth = (OAuth) apiAuthorization;
return oauth.getAuthenticationRequestBuilder();
}
}
return null;
}
/**
* Helper method to pre-set the oauth access token of the first oauth found in the apiAuthorizations (there should be only one)
* @param accessToken
*/
public void setAccessToken(String accessToken) {
for(Interceptor apiAuthorization : apiAuthorizations.values()) {
if (apiAuthorization instanceof OAuth) {
OAuth oauth = (OAuth) apiAuthorization;
oauth.setAccessToken(accessToken);
return;
}
}
}
/**
* Helper method to configure the oauth accessCode/implicit flow parameters
* @param clientId
* @param clientSecret
* @param redirectURI
*/
public void configureAuthorizationFlow(String clientId, String clientSecret, String redirectURI) {
for(Interceptor apiAuthorization : apiAuthorizations.values()) {
if (apiAuthorization instanceof OAuth) {
OAuth oauth = (OAuth) apiAuthorization;
oauth.getTokenRequestBuilder()
.setClientId(clientId)
.setClientSecret(clientSecret)
.setRedirectURI(redirectURI);
oauth.getAuthenticationRequestBuilder()
.setClientId(clientId)
.setRedirectURI(redirectURI);
return;
}
}
}
/**
* Configures a listener which is notified when a new access token is received.
* @param accessTokenListener
*/
public void registerAccessTokenListener(AccessTokenListener accessTokenListener) {
for(Interceptor apiAuthorization : apiAuthorizations.values()) {
if (apiAuthorization instanceof OAuth) {
OAuth oauth = (OAuth) apiAuthorization;
oauth.registerAccessTokenListener(accessTokenListener);
return;
}
}
}
/**
* Adds an authorization to be used by the client
* @param authName
* @param authorization
*/
public void addAuthorization(String authName, Interceptor authorization) {
if (apiAuthorizations.containsKey(authName)) {
throw new RuntimeException("auth name \"" + authName + "\" already in api authorizations");
}
apiAuthorizations.put(authName, authorization);
okClient.interceptors().add(authorization);
}
public Map<String, Interceptor> getApiAuthorizations() {
return apiAuthorizations;
}
public void setApiAuthorizations(Map<String, Interceptor> apiAuthorizations) {
this.apiAuthorizations = apiAuthorizations;
}
public Retrofit.Builder getAdapterBuilder() {
return adapterBuilder;
}
public void setAdapterBuilder(Retrofit.Builder adapterBuilder) {
this.adapterBuilder = adapterBuilder;
}
public OkHttpClient getOkClient() {
return okClient;
}
public void addAuthsToOkClient(OkHttpClient okClient) {
for(Interceptor apiAuthorization : apiAuthorizations.values()) {
okClient.interceptors().add(apiAuthorization);
}
}
/**
* Clones the okClient given in parameter, adds the auth interceptors and uses it to configure the Retrofit
* @param okClient
*/
public void configureFromOkclient(OkHttpClient okClient) {
OkHttpClient clone = okClient.clone();
addAuthsToOkClient(clone);
adapterBuilder.client(clone);
}
}
/**
* This wrapper is to take care of this case:
* when the deserialization fails due to JsonParseException and the
* expected type is String, then just return the body string.
*/
class GsonResponseBodyConverterToString<T> implements Converter<ResponseBody, T> {
private final Gson gson;
private final Type type;
GsonResponseBodyConverterToString(Gson gson, Type type) {
this.gson = gson;
this.type = type;
}
@Override public T convert(ResponseBody value) throws IOException {
String returned = value.string();
try {
return gson.fromJson(returned, type);
}
catch (JsonParseException e) {
return (T) returned;
}
}
}
class GsonCustomConverterFactory extends Converter.Factory
{
public static GsonCustomConverterFactory create(Gson gson) {
return new GsonCustomConverterFactory(gson);
}
private final Gson gson;
private final GsonConverterFactory gsonConverterFactory;
private GsonCustomConverterFactory(Gson gson) {
if (gson == null) throw new NullPointerException("gson == null");
this.gson = gson;
this.gsonConverterFactory = GsonConverterFactory.create(gson);
}
@Override
public Converter<ResponseBody, ?> fromResponseBody(Type type, Annotation[] annotations) {
if(type.equals(String.class))
return new GsonResponseBodyConverterToString<Object>(gson, type);
else
return gsonConverterFactory.fromResponseBody(type, annotations);
}
@Override
public Converter<?, RequestBody> toRequestBody(Type type, Annotation[] annotations) {
return gsonConverterFactory.toRequestBody(type, annotations);
}
}

View File

@@ -0,0 +1,95 @@
package io.swagger.client;
import java.util.Arrays;
import java.util.List;
public class CollectionFormats {
public static class CSVParams {
protected List<String> params;
public CSVParams() {
}
public CSVParams(List<String> params) {
this.params = params;
}
public CSVParams(String... params) {
this.params = Arrays.asList(params);
}
public List<String> getParams() {
return params;
}
public void setParams(List<String> params) {
this.params = params;
}
@Override
public String toString() {
return StringUtil.join(params.toArray(new String[0]), ",");
}
}
public static class SSVParams extends CSVParams {
public SSVParams() {
}
public SSVParams(List<String> params) {
super(params);
}
public SSVParams(String... params) {
super(params);
}
@Override
public String toString() {
return StringUtil.join(params.toArray(new String[0]), " ");
}
}
public static class TSVParams extends CSVParams {
public TSVParams() {
}
public TSVParams(List<String> params) {
super(params);
}
public TSVParams(String... params) {
super(params);
}
@Override
public String toString() {
return StringUtil.join( params.toArray(new String[0]), "\t");
}
}
public static class PIPESParams extends CSVParams {
public PIPESParams() {
}
public PIPESParams(List<String> params) {
super(params);
}
public PIPESParams(String... params) {
super(params);
}
@Override
public String toString() {
return StringUtil.join(params.toArray(new String[0]), "|");
}
}
}

View File

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

View File

@@ -0,0 +1,155 @@
package io.swagger.client.api;
import io.swagger.client.CollectionFormats.*;
import rx.Observable;
import retrofit.http.*;
import com.squareup.okhttp.RequestBody;
import io.swagger.client.model.Pet;
import java.io.File;
import java.util.*;
public interface PetApi {
/**
* Update an existing pet
*
* @param body Pet object that needs to be added to the store
* @return Call<Void>
*/
@PUT("pet")
Observable<Void> updatePet(
@Body Pet body
);
/**
* Add a new pet to the store
*
* @param body Pet object that needs to be added to the store
* @return Call<Void>
*/
@POST("pet")
Observable<Void> addPet(
@Body Pet body
);
/**
* Finds Pets by status
* Multiple status values can be provided with comma seperated strings
* @param status Status values that need to be considered for filter
* @return Call<List<Pet>>
*/
@GET("pet/findByStatus")
Observable<List<Pet>> findPetsByStatus(
@Query("status") List<String> status
);
/**
* Finds Pets by tags
* Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.
* @param tags Tags to filter by
* @return Call<List<Pet>>
*/
@GET("pet/findByTags")
Observable<List<Pet>> findPetsByTags(
@Query("tags") List<String> tags
);
/**
* Find pet by ID
* Returns a pet when ID &lt; 10. ID &gt; 10 or nonintegers will simulate API error conditions
* @param petId ID of pet that needs to be fetched
* @return Call<Pet>
*/
@GET("pet/{petId}")
Observable<Pet> getPetById(
@Path("petId") Long petId
);
/**
* Updates a pet in the store with form data
*
* @param petId ID of pet that needs to be updated
* @param name Updated name of the pet
* @param status Updated status of the pet
* @return Call<Void>
*/
@FormUrlEncoded
@POST("pet/{petId}")
Observable<Void> updatePetWithForm(
@Path("petId") String petId, @Field("name") String name, @Field("status") String status
);
/**
* Deletes a pet
*
* @param petId Pet id to delete
* @param apiKey
* @return Call<Void>
*/
@DELETE("pet/{petId}")
Observable<Void> deletePet(
@Path("petId") Long petId, @Header("api_key") String apiKey
);
/**
* uploads an image
*
* @param petId ID of pet to update
* @param additionalMetadata Additional data to pass to server
* @param file file to upload
* @return Call<Void>
*/
@Multipart
@POST("pet/{petId}/uploadImage")
Observable<Void> uploadFile(
@Path("petId") Long petId, @Part("additionalMetadata") String additionalMetadata, @Part("file\"; filename=\"file\"") RequestBody file
);
/**
* Fake endpoint to test byte array return by &#39;Find pet by ID&#39;
* Returns a pet when ID &lt; 10. ID &gt; 10 or nonintegers will simulate API error conditions
* @param petId ID of pet that needs to be fetched
* @return Call<byte[]>
*/
@GET("pet/{petId}?testing_byte_array=true")
Observable<byte[]> getPetByIdWithByteArray(
@Path("petId") Long petId
);
/**
* Fake endpoint to test byte array in body parameter for adding a new pet to the store
*
* @param body Pet object in the form of byte array
* @return Call<Void>
*/
@POST("pet?testing_byte_array=true")
Observable<Void> addPetUsingByteArray(
@Body byte[] body
);
}

View File

@@ -0,0 +1,68 @@
package io.swagger.client.api;
import io.swagger.client.CollectionFormats.*;
import rx.Observable;
import retrofit.http.*;
import com.squareup.okhttp.RequestBody;
import java.util.Map;
import io.swagger.client.model.Order;
import java.util.*;
public interface StoreApi {
/**
* Returns pet inventories by status
* Returns a map of status codes to quantities
* @return Call<Map<String, Integer>>
*/
@GET("store/inventory")
Observable<Map<String, Integer>> getInventory();
/**
* Place an order for a pet
*
* @param body order placed for purchasing the pet
* @return Call<Order>
*/
@POST("store/order")
Observable<Order> placeOrder(
@Body Order body
);
/**
* Find purchase order by ID
* For valid response try integer IDs with value &lt;= 5 or &gt; 10. Other values will generated exceptions
* @param orderId ID of pet that needs to be fetched
* @return Call<Order>
*/
@GET("store/order/{orderId}")
Observable<Order> getOrderById(
@Path("orderId") String orderId
);
/**
* Delete purchase order by ID
* For valid response try integer IDs with value &lt; 1000. Anything above 1000 or nonintegers will generate API errors
* @param orderId ID of the order that needs to be deleted
* @return Call<Void>
*/
@DELETE("store/order/{orderId}")
Observable<Void> deleteOrder(
@Path("orderId") String orderId
);
}

View File

@@ -0,0 +1,122 @@
package io.swagger.client.api;
import io.swagger.client.CollectionFormats.*;
import rx.Observable;
import retrofit.http.*;
import com.squareup.okhttp.RequestBody;
import io.swagger.client.model.User;
import java.util.*;
import java.util.*;
public interface UserApi {
/**
* Create user
* This can only be done by the logged in user.
* @param body Created user object
* @return Call<Void>
*/
@POST("user")
Observable<Void> createUser(
@Body User body
);
/**
* Creates list of users with given input array
*
* @param body List of user object
* @return Call<Void>
*/
@POST("user/createWithArray")
Observable<Void> createUsersWithArrayInput(
@Body List<User> body
);
/**
* Creates list of users with given input array
*
* @param body List of user object
* @return Call<Void>
*/
@POST("user/createWithList")
Observable<Void> createUsersWithListInput(
@Body List<User> body
);
/**
* Logs user into the system
*
* @param username The user name for login
* @param password The password for login in clear text
* @return Call<String>
*/
@GET("user/login")
Observable<String> loginUser(
@Query("username") String username, @Query("password") String password
);
/**
* Logs out current logged in user session
*
* @return Call<Void>
*/
@GET("user/logout")
Observable<Void> logoutUser();
/**
* Get user by user name
*
* @param username The name that needs to be fetched. Use user1 for testing.
* @return Call<User>
*/
@GET("user/{username}")
Observable<User> getUserByName(
@Path("username") String username
);
/**
* Updated user
* This can only be done by the logged in user.
* @param username name that need to be deleted
* @param body Updated user object
* @return Call<Void>
*/
@PUT("user/{username}")
Observable<Void> updateUser(
@Path("username") String username, @Body User body
);
/**
* Delete user
* This can only be done by the logged in user.
* @param username The name that needs to be deleted
* @return Call<Void>
*/
@DELETE("user/{username}")
Observable<Void> deleteUser(
@Path("username") String username
);
}

View File

@@ -0,0 +1,68 @@
package io.swagger.client.auth;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import com.squareup.okhttp.Interceptor;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
public class ApiKeyAuth implements Interceptor {
private final String location;
private final String paramName;
private String apiKey;
public ApiKeyAuth(String location, String paramName) {
this.location = location;
this.paramName = paramName;
}
public String getLocation() {
return location;
}
public String getParamName() {
return paramName;
}
public String getApiKey() {
return apiKey;
}
public void setApiKey(String apiKey) {
this.apiKey = apiKey;
}
@Override
public Response intercept(Chain chain) throws IOException {
String paramValue;
Request request = chain.request();
if (location == "query") {
String newQuery = request.uri().getQuery();
paramValue = paramName + "=" + apiKey;
if (newQuery == null) {
newQuery = paramValue;
} else {
newQuery += "&" + paramValue;
}
URI newUri;
try {
newUri = new URI(request.uri().getScheme(), request.uri().getAuthority(),
request.uri().getPath(), newQuery, request.uri().getFragment());
} catch (URISyntaxException e) {
throw new IOException(e);
}
request = request.newBuilder().url(newUri.toURL()).build();
} else if (location == "header") {
request = request.newBuilder()
.addHeader(paramName, apiKey)
.build();
}
return chain.proceed(request);
}
}

View File

@@ -0,0 +1,49 @@
package io.swagger.client.auth;
import java.io.IOException;
import com.squareup.okhttp.Credentials;
import com.squareup.okhttp.Interceptor;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
public class HttpBasicAuth implements Interceptor {
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public void setCredentials(String username, String password) {
this.username = username;
this.password = password;
}
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
// If the request already have an authorization (eg. Basic auth), do nothing
if (request.header("Authorization") == null) {
String credentials = Credentials.basic(username, password);
request = request.newBuilder()
.addHeader("Authorization", credentials)
.build();
}
return chain.proceed(request);
}
}

View File

@@ -0,0 +1,161 @@
package io.swagger.client.auth;
import static java.net.HttpURLConnection.HTTP_UNAUTHORIZED;
import java.io.IOException;
import java.util.Map;
import org.apache.oltu.oauth2.client.OAuthClient;
import org.apache.oltu.oauth2.client.request.OAuthBearerClientRequest;
import org.apache.oltu.oauth2.client.request.OAuthClientRequest;
import org.apache.oltu.oauth2.client.request.OAuthClientRequest.AuthenticationRequestBuilder;
import org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder;
import org.apache.oltu.oauth2.client.response.OAuthJSONAccessTokenResponse;
import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import org.apache.oltu.oauth2.common.message.types.GrantType;
import org.apache.oltu.oauth2.common.token.BasicOAuthToken;
import com.squareup.okhttp.Interceptor;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Request.Builder;
import com.squareup.okhttp.Response;
public class OAuth implements Interceptor {
public interface AccessTokenListener {
public void notify(BasicOAuthToken token);
}
private volatile String accessToken;
private OAuthClient oauthClient;
private TokenRequestBuilder tokenRequestBuilder;
private AuthenticationRequestBuilder authenticationRequestBuilder;
private AccessTokenListener accessTokenListener;
public OAuth( OkHttpClient client, TokenRequestBuilder requestBuilder ) {
this.oauthClient = new OAuthClient(new OAuthOkHttpClient(client));
this.tokenRequestBuilder = requestBuilder;
}
public OAuth(TokenRequestBuilder requestBuilder ) {
this(new OkHttpClient(), requestBuilder);
}
public OAuth(OAuthFlow flow, String authorizationUrl, String tokenUrl, String scopes) {
this(OAuthClientRequest.tokenLocation(tokenUrl).setScope(scopes));
setFlow(flow);
authenticationRequestBuilder = OAuthClientRequest.authorizationLocation(authorizationUrl);
}
public void setFlow(OAuthFlow flow) {
switch(flow) {
case accessCode:
case implicit:
tokenRequestBuilder.setGrantType(GrantType.AUTHORIZATION_CODE);
break;
case password:
tokenRequestBuilder.setGrantType(GrantType.PASSWORD);
break;
case application:
tokenRequestBuilder.setGrantType(GrantType.CLIENT_CREDENTIALS);
break;
default:
break;
}
}
@Override
public Response intercept(Chain chain)
throws IOException {
Request request = chain.request();
// If the request already have an authorization (eg. Basic auth), do nothing
if (request.header("Authorization") != null) {
return chain.proceed(request);
}
// If first time, get the token
OAuthClientRequest oAuthRequest;
if (getAccessToken() == null) {
updateAccessToken(null);
}
// Build the request
Builder rb = request.newBuilder();
String requestAccessToken = new String(getAccessToken());
try {
oAuthRequest = new OAuthBearerClientRequest(request.urlString())
.setAccessToken(requestAccessToken)
.buildHeaderMessage();
} catch (OAuthSystemException e) {
throw new IOException(e);
}
for ( Map.Entry<String, String> header : oAuthRequest.getHeaders().entrySet() ) {
rb.addHeader(header.getKey(), header.getValue());
}
rb.url( oAuthRequest.getLocationUri());
//Execute the request
Response response = chain.proceed(rb.build());
// 401 most likely indicates that access token has expired.
// Time to refresh and resend the request
if ( response.code() == HTTP_UNAUTHORIZED ) {
updateAccessToken(requestAccessToken);
return intercept( chain );
}
return response;
}
public synchronized void updateAccessToken(String requestAccessToken) throws IOException {
if (getAccessToken() == null || getAccessToken().equals(requestAccessToken)) {
try {
OAuthJSONAccessTokenResponse accessTokenResponse = oauthClient.accessToken(this.tokenRequestBuilder.buildBodyMessage());
setAccessToken(accessTokenResponse.getAccessToken());
if (accessTokenListener != null) {
accessTokenListener.notify((BasicOAuthToken) accessTokenResponse.getOAuthToken());
}
} catch (OAuthSystemException e) {
throw new IOException(e);
} catch (OAuthProblemException e) {
throw new IOException(e);
}
}
}
public void registerAccessTokenListener(AccessTokenListener accessTokenListener) {
this.accessTokenListener = accessTokenListener;
}
public synchronized String getAccessToken() {
return accessToken;
}
public synchronized void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
public TokenRequestBuilder getTokenRequestBuilder() {
return tokenRequestBuilder;
}
public void setTokenRequestBuilder(TokenRequestBuilder tokenRequestBuilder) {
this.tokenRequestBuilder = tokenRequestBuilder;
}
public AuthenticationRequestBuilder getAuthenticationRequestBuilder() {
return authenticationRequestBuilder;
}
public void setAuthenticationRequestBuilder(AuthenticationRequestBuilder authenticationRequestBuilder) {
this.authenticationRequestBuilder = authenticationRequestBuilder;
}
}

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