Merge branch 'master' into java-imports

Conflicts:
	modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaClientCodegen.java
This commit is contained in:
xhh
2016-01-29 11:16:14 +08:00
356 changed files with 11850 additions and 3863 deletions

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,12 +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;
public abstract class AbstractGenerator {
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()) {
@@ -36,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);
}
@@ -48,14 +54,11 @@ public abstract class AbstractGenerator {
try {
InputStream is = this.getClass().getClassLoader().getResourceAsStream(getCPResourcePath(name));
if (is == null) {
is = new FileInputStream(new File(name));
}
if (is == null) {
throw new RuntimeException("no file found");
is = new FileInputStream(new File(name)); // May throw but never return a null value
}
return new InputStreamReader(is);
} catch (Exception e) {
e.printStackTrace();
LOGGER.error(e.getMessage());
}
throw new RuntimeException("can't load template " + name);
}
@@ -96,6 +99,7 @@ public abstract class AbstractGenerator {
return this.getClass().getClassLoader().getResource(getCPResourcePath(name)) != null;
}
@SuppressWarnings("static-method")
public String getCPResourcePath(String name) {
if (!"/".equals(File.separator)) {
return name.replaceAll(Pattern.quote(File.separator), "/");

View File

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

View File

@@ -1,29 +1,34 @@
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.Arrays;
import java.util.HashMap;
import java.util.Iterator;
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:" +
@@ -32,10 +37,9 @@ public class Codegen extends DefaultGenerator {
"\n -DdebugOperations prints operations passed to the template engine" +
"\n -DdebugSupportingFiles prints additional data passed to the template engine";
@SuppressWarnings("deprecation")
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
Options options = new Options();
options.addOption("h", "help", false, "shows this message");
options.addOption("l", "lang", true, "client language to generate.\nAvailable languages include:\n\t[" + configString + "]");
@@ -113,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);
}
}
@@ -138,9 +142,9 @@ public class Codegen extends DefaultGenerator {
} else {
// see if it's a class
try {
System.out.println("loading class " + name);
Class customClass = Class.forName(name);
System.out.println("loaded");
LOGGER.debug("loading class " + name);
Class<?> customClass = Class.forName(name);
LOGGER.debug("loaded");
return (CodegenConfig) customClass.newInstance();
} catch (Exception e) {
throw new RuntimeException("can't load class " + name);

View File

@@ -62,4 +62,21 @@ public class CodegenConstants {
public static final String OPTIONAL_ASSEMBLY_INFO = "optionalAssemblyInfo";
public static final String OPTIONAL_ASSEMBLY_INFO_DESC = "Generate AssemblyInfo.cs (Default: true).";
public static final String USE_COLLECTION = "useCollection";
public static final String USE_COLLECTION_DESC = "Deserialize array types to Collection<T> instead of List<T>.";
public static final String RETURN_ICOLLECTION = "returnICollection";
public static final String RETURN_ICOLLECTION_DESC = "Return ICollection<T> instead of the concrete type.";
public static final String OPTIONAL_PROJECT_FILE = "optionalProjectFile";
public static final String OPTIONAL_PROJECT_FILE_DESC = "Generate {PackageName}.csproj (Default: false).";
public static final String OPTIONAL_PROJECT_GUID = "packageGuid";
public static final String OPTIONAL_PROJECT_GUID_DESC = "The GUID that will be associated with the C# project";
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

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -2,15 +2,17 @@ package io.swagger.codegen;
import com.samskivert.mustache.Mustache;
import com.samskivert.mustache.Template;
import io.swagger.models.Swagger;
import org.apache.commons.cli.BasicParser;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
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;
@@ -25,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;
@@ -57,8 +62,6 @@ public class MetaGenerator extends AbstractGenerator {
}
protected void generate(String[] args) {
StringBuilder sb = new StringBuilder();
String targetLanguage = null;
String outputFolder = null;
String name = null;
String targetPackage = "io.swagger.codegen";
@@ -71,12 +74,9 @@ public class MetaGenerator extends AbstractGenerator {
options.addOption("n", "name", true, "the human-readable name of the generator");
options.addOption("p", "package", true, "the package to put the main class into (defaults to io.swagger.codegen");
ClientOptInput clientOptInput = new ClientOptInput();
Swagger swagger = null;
CommandLine cmd = null;
try {
CommandLineParser parser = new BasicParser();
cmd = parser.parse(options, args);
if (cmd.hasOption("h")) {
usage(options);
@@ -85,12 +85,11 @@ public class MetaGenerator extends AbstractGenerator {
if (cmd.hasOption("n")) {
name = cmd.getOptionValue("n");
} else {
System.out.println("name is required");
System.out.println("name is required"); //FIXME replace by LOGGER
usage(options);
return;
}
if (cmd.hasOption("l")) {
targetLanguage = cmd.getOptionValue("l");
}
if (cmd.hasOption("p")) {
targetPackage = cmd.getOptionValue("p");
@@ -98,7 +97,7 @@ public class MetaGenerator extends AbstractGenerator {
if (cmd.hasOption("o")) {
outputFolder = cmd.getOptionValue("o");
} else {
System.out.println("output folder is required");
System.out.println("output folder is required"); // FIXME replace by LOGGER
usage(options);
return;
}
@@ -106,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();
@@ -161,8 +160,6 @@ public class MetaGenerator extends AbstractGenerator {
public Reader getTemplate(String name) {
return getTemplateReader(templateDir + File.separator + name + ".mustache");
}
;
})
.defaultValue("")
.compile(template);
@@ -172,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

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

View File

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

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

View File

@@ -39,7 +39,7 @@ public class XmlExampleGenerator {
public XmlExampleGenerator(Map<String, Model> examples) {
this.examples = examples;
if (examples == null) {
examples = new HashMap<String, Model>();
this.examples = new HashMap<String, Model>();
}
}
@@ -74,10 +74,6 @@ public class XmlExampleGenerator {
Map<String, Property> elements = new LinkedHashMap<String, Property>();
String name = modelName;
String namespace;
String prefix;
Boolean wrapped;
Xml xml = model.getXml();
if (xml != null) {
if (xml.getName() != null) {
@@ -117,6 +113,7 @@ public class XmlExampleGenerator {
return sb.toString();
}
@SuppressWarnings("static-method")
protected String quote(String string) {
return "\"" + string + "\"";
}
@@ -211,14 +208,17 @@ public class XmlExampleGenerator {
return "not implemented " + property;
}
@SuppressWarnings("static-method")
protected String openTag(String name) {
return "<" + name + ">";
}
@SuppressWarnings("static-method")
protected String closeTag(String name) {
return "</" + name + ">";
}
@SuppressWarnings("static-method")
protected String indent(int indent) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < indent; i++) {

View File

@@ -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

@@ -9,10 +9,8 @@ import java.io.File;
import org.apache.commons.lang.StringUtils;
public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen implements CodegenConfig {
@Override
public CodegenType getTag() {
return CodegenType.CLIENT;
}
protected String modelPropertyNaming= "camelCase";
public AbstractTypeScriptClientCodegen() {
super();
@@ -54,7 +52,25 @@ 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() {
return CodegenType.CLIENT;
}
@Override
@@ -73,9 +89,9 @@ 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("-", "_");
name = name.replaceAll("-", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
// if it's all uppper case, do nothing
if (name.matches("^[A-Z_]*$"))
@@ -93,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
@@ -145,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

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

View File

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

View File

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

View File

@@ -7,6 +7,7 @@ import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile;
import io.swagger.codegen.CodegenProperty;
import io.swagger.codegen.CodegenModel;
import io.swagger.codegen.CodegenOperation;
import io.swagger.models.properties.*;
import io.swagger.codegen.CliOption;
@@ -22,10 +23,15 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig {
@SuppressWarnings({ "unused", "hiding" })
private static final Logger LOGGER = LoggerFactory.getLogger(CSharpClientCodegen.class);
protected boolean optionalAssemblyInfoFlag = true;
protected boolean optionalProjectFileFlag = false;
protected boolean optionalMethodArgumentFlag = true;
protected boolean useDateTimeOffsetFlag = false;
protected boolean useCollection = false;
protected boolean returnICollection = false;
protected String packageGuid = "{" + java.util.UUID.randomUUID().toString().toUpperCase() + "}";
protected String packageTitle = "Swagger Library";
protected String packageProductName = "SwaggerLibrary";
protected String packageDescription = "A library generated from a Swagger doc";
@@ -74,6 +80,8 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig
"long?",
"float?",
"byte[]",
"ICollection",
"Collection",
"List",
"Dictionary",
"DateTime?",
@@ -87,7 +95,9 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig
"Stream", // not really a primitive, we include it to avoid model import
"Object")
);
instantiationTypes.put("array", "List");
instantiationTypes.put("list", "List");
instantiationTypes.put("map", "Dictionary");
typeMapping = new HashMap<String, String>();
@@ -119,6 +129,14 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig
CodegenConstants.OPTIONAL_ASSEMBLY_INFO_DESC).defaultValue(Boolean.TRUE.toString()));
cliOptions.add(new CliOption(CodegenConstants.SOURCE_FOLDER, CodegenConstants.SOURCE_FOLDER_DESC).defaultValue(sourceFolder));
cliOptions.add(CliOption.newBoolean(CodegenConstants.USE_DATETIME_OFFSET, CodegenConstants.USE_DATETIME_OFFSET_DESC));
cliOptions.add( CliOption.newBoolean(CodegenConstants.USE_COLLECTION, CodegenConstants.USE_COLLECTION_DESC)
.defaultValue(Boolean.FALSE.toString()) );
cliOptions.add( CliOption.newBoolean(CodegenConstants.RETURN_ICOLLECTION, CodegenConstants.RETURN_ICOLLECTION_DESC)
.defaultValue(Boolean.FALSE.toString()) );
cliOptions.add(CliOption.newBoolean(CodegenConstants.OPTIONAL_PROJECT_FILE,
CodegenConstants.OPTIONAL_PROJECT_FILE_DESC).defaultValue(Boolean.FALSE.toString()));
cliOptions.add(new CliOption(CodegenConstants.OPTIONAL_PROJECT_GUID, CodegenConstants.OPTIONAL_PROJECT_GUID_DESC));
}
@Override
@@ -163,7 +181,19 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig
additionalProperties.put("packageDescription", packageDescription);
additionalProperties.put("packageCompany", packageCompany);
additionalProperties.put("packageCopyright", packageCopyright);
if (additionalProperties.containsKey(CodegenConstants.OPTIONAL_PROJECT_FILE))
{
setOptionalProjectFileFlag(Boolean.valueOf(
additionalProperties.get(CodegenConstants.OPTIONAL_PROJECT_FILE).toString()));
}
if (additionalProperties.containsKey(CodegenConstants.OPTIONAL_PROJECT_GUID))
{
setPackageGuid((String) additionalProperties.get(CodegenConstants.OPTIONAL_PROJECT_GUID));
}
additionalProperties.put("packageGuid", packageGuid);
if (additionalProperties.containsKey(CodegenConstants.OPTIONAL_METHOD_ARGUMENT)) {
setOptionalMethodArgumentFlag(Boolean.valueOf(additionalProperties
.get(CodegenConstants.OPTIONAL_METHOD_ARGUMENT).toString()));
@@ -175,14 +205,36 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig
.get(CodegenConstants.OPTIONAL_ASSEMBLY_INFO).toString()));
}
if (additionalProperties.containsKey(CodegenConstants.USE_COLLECTION)){
setUseCollection(Boolean.valueOf(additionalProperties.get(CodegenConstants.USE_COLLECTION).toString()));
}
if (additionalProperties.containsKey(CodegenConstants.RETURN_ICOLLECTION)){
setReturnICollection(Boolean.valueOf(additionalProperties.get(CodegenConstants.RETURN_ICOLLECTION).toString()));
}
String packageFolder = sourceFolder + File.separator + packageName.replace(".", java.io.File.separator);
String clientPackageDir = sourceFolder + File.separator + clientPackage.replace(".", java.io.File.separator);
//Compute the relative path to the bin directory where the external assemblies live
//This is necessary to properly generate the project file
int packageDepth = packageFolder.length() - packageFolder.replace(java.io.File.separator, "").length();
String binRelativePath = "..\\";
for (int i=0; i < packageDepth; i = i+1)
binRelativePath += "..\\";
binRelativePath += "bin\\";
additionalProperties.put("binRelativePath", binRelativePath);
supportingFiles.add(new SupportingFile("Configuration.mustache",
sourceFolder + File.separator + clientPackage.replace(".", java.io.File.separator), "Configuration.cs"));
clientPackageDir, "Configuration.cs"));
supportingFiles.add(new SupportingFile("ApiClient.mustache",
sourceFolder + File.separator + clientPackage.replace(".", java.io.File.separator), "ApiClient.cs"));
clientPackageDir, "ApiClient.cs"));
supportingFiles.add(new SupportingFile("ApiException.mustache",
sourceFolder + File.separator + clientPackage.replace(".", java.io.File.separator), "ApiException.cs"));
clientPackageDir, "ApiException.cs"));
supportingFiles.add(new SupportingFile("ApiResponse.mustache",
sourceFolder + File.separator + clientPackage.replace(".", java.io.File.separator), "ApiResponse.cs"));
clientPackageDir, "ApiResponse.cs"));
supportingFiles.add(new SupportingFile("Newtonsoft.Json.dll", "bin", "Newtonsoft.Json.dll"));
supportingFiles.add(new SupportingFile("RestSharp.dll", "bin", "RestSharp.dll"));
supportingFiles.add(new SupportingFile("compile.mustache", "", "compile.bat"));
@@ -191,9 +243,11 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig
supportingFiles.add(new SupportingFile("README.md", "", "README.md"));
if (optionalAssemblyInfoFlag) {
supportingFiles.add(new SupportingFile("AssemblyInfo.mustache", "src" + File.separator + "Properties", "AssemblyInfo.cs"));
supportingFiles.add(new SupportingFile("AssemblyInfo.mustache", packageFolder + File.separator + "Properties", "AssemblyInfo.cs"));
}
if (optionalProjectFileFlag) {
supportingFiles.add(new SupportingFile("Project.mustache", packageFolder, clientPackage + ".csproj"));
}
}
@Override
@@ -229,7 +283,7 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig
@Override
public String toVarName(String name) {
// sanitize name
name = sanitizeName(name);
name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
// if it's all uppper case, do nothing
if (name.matches("^[A-Z_]*$")) {
@@ -288,6 +342,32 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig
return toModelName(name);
}
@Override
public Map<String, Object> postProcessOperations(Map<String, Object> objs) {
super.postProcessOperations(objs);
if(objs != null) {
Map<String, Object> operations = (Map<String, Object>) objs.get("operations");
if (operations != null) {
List<CodegenOperation> ops = (List<CodegenOperation>) operations.get("operation");
for (CodegenOperation operation : ops) {
if (operation.returnType != null) {
operation.returnContainer = operation.returnType;
if( this.returnICollection && (
operation.returnType.startsWith("List")||
operation.returnType.startsWith("Collection")) ) {
// NOTE: ICollection works for both List<T> and Collection<T>
int genericStart = operation.returnType.indexOf("<");
if(genericStart > 0) {
operation.returnType = "ICollection" + operation.returnType.substring(genericStart);
}
}
}
}
}
}
return objs;
}
@Override
public String getTypeDeclaration(Property p) {
@@ -338,10 +418,29 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig
this.optionalAssemblyInfoFlag = flag;
}
public void setOptionalProjectFileFlag(boolean flag) {
this.optionalProjectFileFlag = flag;
}
public void setOptionalMethodArgumentFlag(boolean flag) {
this.optionalMethodArgumentFlag = flag;
}
public void setReturnICollection(boolean returnICollection) {
this.returnICollection = returnICollection;
}
public void setUseCollection(boolean useCollection) {
this.useCollection = useCollection;
if(useCollection){
typeMapping.put("array", "Collection");
typeMapping.put("list", "Collection");
instantiationTypes.put("array", "Collection");
instantiationTypes.put("list", "Collection");
}
}
public void useDateTimeOffset(boolean flag) {
this.useDateTimeOffsetFlag = flag;
if (flag)
@@ -350,7 +449,10 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig
typeMapping.put("datetime", "DateTime?");
}
public void setPackageGuid(String packageGuid) {
this.packageGuid = packageGuid;
}
public void setPackageName(String packageName) {
this.packageName = packageName;
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,283 @@
package io.swagger.codegen.languages;
import io.swagger.codegen.*;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
import java.io.File;
import java.util.*;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class GoClientCodegen extends DefaultCodegen implements CodegenConfig {
static Logger LOGGER = LoggerFactory.getLogger(GoClientCodegen.class);
protected String packageName = "swagger";
protected String packageVersion = "1.0.0";
public CodegenType getTag() {
return CodegenType.CLIENT;
}
public String getName() {
return "go";
}
public String getHelp() {
return "Generates a Go client library (beta).";
}
public GoClientCodegen() {
super();
outputFolder = "generated-code/go";
modelTemplateFiles.put("model.mustache", ".go");
apiTemplateFiles.put("api.mustache", ".go");
templateDir = "go";
reservedWords = new HashSet<String> (
Arrays.asList(
"break", "default", "func", "interface", "select",
"case", "defer", "go", "map", "struct",
"chan", "else", "goto", "package", "switch",
"const", "fallthrough", "if", "range", "type",
"continue", "for", "import", "return", "var")
);
defaultIncludes = new HashSet<String>(
Arrays.asList(
"map",
"array")
);
languageSpecificPrimitives = new HashSet<String>(
Arrays.asList(
"string",
"bool",
"uint",
"uint32",
"uint64",
"int",
"int32",
"int64",
"float32",
"float64",
"complex64",
"complex128",
"rune",
"byte")
);
instantiationTypes.clear();
/*instantiationTypes.put("array", "GoArray");
instantiationTypes.put("map", "GoMap");*/
typeMapping.clear();
typeMapping.put("integer", "int32");
typeMapping.put("long", "int64");
typeMapping.put("float", "float32");
typeMapping.put("double", "float64");
typeMapping.put("boolean", "bool");
typeMapping.put("string", "string");
typeMapping.put("Date", "time.Time");
typeMapping.put("DateTime", "time.Time");
typeMapping.put("password", "string");
typeMapping.put("File", "*os.File");
typeMapping.put("file", "*os.File");
// map binary to string as a workaround
// the correct solution is to use []byte
typeMapping.put("binary", "string");
importMapping = new HashMap<String, String>();
importMapping.put("time.Time", "time");
importMapping.put("*os.File", "os");
cliOptions.clear();
cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME, "Go package name (convention: lowercase).")
.defaultValue("swagger"));
cliOptions.add(new CliOption(CodegenConstants.PACKAGE_VERSION, "Go package version.")
.defaultValue("1.0.0"));
}
@Override
public void processOpts() {
//super.processOpts();
if (additionalProperties.containsKey(CodegenConstants.PACKAGE_NAME)) {
setPackageName((String) additionalProperties.get(CodegenConstants.PACKAGE_NAME));
}
else {
setPackageName("swagger");
}
if (additionalProperties.containsKey(CodegenConstants.PACKAGE_VERSION)) {
setPackageVersion((String) additionalProperties.get(CodegenConstants.PACKAGE_VERSION));
}
else {
setPackageVersion("1.0.0");
}
additionalProperties.put(CodegenConstants.PACKAGE_NAME, packageName);
additionalProperties.put(CodegenConstants.PACKAGE_VERSION, packageVersion);
modelPackage = packageName;
apiPackage = packageName;
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
}
@Override
public String escapeReservedWord(String name) {
return "_" + name;
}
@Override
public String apiFileFolder() {
return outputFolder + File.separator + packageName;
}
public String modelFileFolder() {
return outputFolder + File.separator + packageName;
}
@Override
public String toVarName(String name) {
// replace - with _ e.g. created-at => created_at
name = name.replaceAll("-", "_");
// if it's all uppper case, do nothing
if (name.matches("^[A-Z_]*$"))
return name;
// camelize (lower first character) the variable name
// pet_id => PetId
name = camelize(name);
// for reserved word or word starting with number, append _
if(reservedWords.contains(name) || name.matches("^\\d.*"))
name = escapeReservedWord(name);
return name;
}
@Override
public String toParamName(String name) {
// should be the same as variable name
return toVarName(name);
}
@Override
public String toModelName(String name) {
// model name cannot use reserved keyword, e.g. return
if(reservedWords.contains(name))
throw new RuntimeException(name + " (reserved word) cannot be used as a model name");
// camelize the model name
// phone_number => PhoneNumber
return camelize(name);
}
@Override
public String toModelFilename(String name) {
// should be the same as the model name
return toModelName(name);
}
@Override
public String getTypeDeclaration(Property p) {
if(p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
return "[]" + getTypeDeclaration(inner);
}
else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
return getSwaggerType(p) + "[string]" + getTypeDeclaration(inner);
}
return super.getTypeDeclaration(p);
}
@Override
public String getSwaggerType(Property p) {
String swaggerType = super.getSwaggerType(p);
String type = null;
if(typeMapping.containsKey(swaggerType)) {
type = typeMapping.get(swaggerType);
if(languageSpecificPrimitives.contains(type))
return (type);
}
else
type = swaggerType;
return type;
}
@Override
public String toOperationId(String operationId) {
// method name cannot use reserved keyword, e.g. return
if(reservedWords.contains(operationId))
throw new RuntimeException(operationId + " (reserved word) cannot be used as method name");
return camelize(operationId);
}
@Override
public Map<String, Object> postProcessOperations(Map<String, Object> objs) {
@SuppressWarnings("unchecked")
Map<String, Object> objectMap = (Map<String, Object>) objs.get("operations");
@SuppressWarnings("unchecked")
List<CodegenOperation> operations = (List<CodegenOperation>) objectMap.get("operation");
for (CodegenOperation operation : operations) {
// http method verb conversion (e.g. PUT => Put)
operation.httpMethod = camelize(operation.httpMethod.toLowerCase());
}
// remove model imports to avoid error
List<Map<String, String>> imports = (List<Map<String, String>>) objs.get("imports");
if (imports == null)
return objs;
Iterator<Map<String, String>> iterator = imports.iterator();
while (iterator.hasNext()) {
String _import = iterator.next().get("import");
if (_import.startsWith(apiPackage()))
iterator.remove();
}
return objs;
}
@Override
public Map<String, Object> postProcessModels(Map<String, Object> objs) {
// remove model imports to avoid error
List<Map<String, String>> imports = (List<Map<String, String>>) objs.get("imports");
final String prefix = modelPackage();
Iterator<Map<String, String>> iterator = imports.iterator();
while (iterator.hasNext()) {
String _import = iterator.next().get("import");
if (_import.startsWith(prefix))
iterator.remove();
}
return objs;
}
@Override
protected boolean needToImport(String type) {
return !defaultIncludes.contains(type)
&& !languageSpecificPrimitives.contains(type);
}
public void setPackageName(String packageName) {
this.packageName = packageName;
}
public void setPackageVersion(String packageVersion) {
this.packageVersion = packageVersion;
}
}

View File

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

View File

@@ -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,27 +1,57 @@
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 java.util.regex.Pattern;
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 java.util.regex.Pattern;
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")
private static final Logger LOGGER = LoggerFactory.getLogger(JavaClientCodegen.class);
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 +65,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 +119,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 +216,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.";
}
@@ -242,7 +279,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"));
@@ -259,7 +296,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())) {
@@ -287,6 +324,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
@@ -325,7 +370,7 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
@Override
public String toVarName(String name) {
// sanitize name
name = sanitizeName(name);
name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
if("_".equals(name)) {
name = "_u";
@@ -356,7 +401,7 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
@Override
public String toModelName(String name) {
name = sanitizeName(name);
name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
// model name cannot use reserved keyword, e.g. return
if (reservedWords.contains(name)) {
@@ -495,7 +540,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;
@@ -617,7 +662,7 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
}
}
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");
@@ -633,7 +678,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);
}
}
@@ -667,7 +712,7 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
}
}
private String getAccept(Operation operation) {
private static String getAccept(Operation operation) {
String accepts = null;
String defaultContentType = "application/json";
if (operation.getProduces() != null && !operation.getProduces().isEmpty()) {
@@ -698,14 +743,14 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
return super.needToImport(type) && type.indexOf(".") < 0;
}
private String findCommonPrefixOfVars(List<String> vars) {
private static String findCommonPrefixOfVars(List<String> vars) {
String prefix = StringUtils.getCommonPrefix(vars.toArray(new String[vars.size()]));
// exclude trailing characters that should be part of a valid variable
// e.g. ["status-on", "status-off"] => "status-" (not "status-o")
return prefix.replaceAll("[a-zA-Z0-9]+\\z", "");
}
private String toEnumVarName(String value) {
private static String toEnumVarName(String value) {
String var = value.replaceAll("\\W+", "_").toUpperCase();
if (var.matches("\\d.*")) {
return "_" + var;
@@ -714,7 +759,7 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
}
}
private CodegenModel reconcileInlineEnums(CodegenModel codegenModel, CodegenModel parentCodegenModel) {
private static CodegenModel reconcileInlineEnums(CodegenModel codegenModel, CodegenModel parentCodegenModel) {
// This generator uses inline classes to define enums, which breaks when
// dealing with models that have subTypes. To clean this up, we will analyze
// the parent and child models, look for enums that match, and remove
@@ -798,8 +843,8 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
this.serializableModel = serializableModel;
}
private String sanitizePackageName(String packageName) {
packageName = packageName.trim();
private static String sanitizePackageName(String packageName) {
packageName = packageName.trim(); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
packageName = packageName.replaceAll("[^a-zA-Z0-9_\\.]", "_");
if(Strings.isNullOrEmpty(packageName)) {
return "invalidPackageName";
@@ -811,6 +856,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.*;
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 implements Cod
try {
objs.put("swagger-yaml", Yaml.mapper().writeValueAsString(swagger));
} catch (JsonProcessingException e) {
e.printStackTrace();
LOGGER.error(e.getMessage(), e);
}
}
return super.postProcessSupportingFileData(objs);
@@ -175,12 +181,15 @@ public class JavaInflectorServerCodegen extends JavaClientCodegen implements Cod
if (name.length() == 0) {
return "DefaultController";
}
name = name.replaceAll("[^a-zA-Z0-9]+", "_");
name = name.replaceAll("[^a-zA-Z0-9]+", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
return camelize(name)+ "Controller";
}
@Override
public boolean shouldOverwrite(String filename) {
return super.shouldOverwrite(filename);
return super.shouldOverwrite(filename) &&
!filename.endsWith("pom.xml") &&
!filename.endsWith("README.md") &&
!filename.endsWith("inflector.yaml");
}
}

View File

@@ -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

@@ -13,7 +13,6 @@ import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile;
import io.swagger.models.*;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.LongProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
import io.swagger.models.properties.RefProperty;
@@ -32,6 +31,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class JavascriptClientCodegen extends DefaultCodegen implements CodegenConfig {
@SuppressWarnings("hiding")
private static final Logger LOGGER = LoggerFactory.getLogger(JavascriptClientCodegen.class);
private static final String PROJECT_NAME = "projectName";
@@ -133,6 +133,8 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
typeMapping.put("double", "Number");
typeMapping.put("number", "Number");
typeMapping.put("DateTime", "Date");
// binary not supported in JavaScript client right now, using String as a workaround
typeMapping.put("binary", "String");
importMapping.clear();
}
@@ -205,6 +207,7 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
supportingFiles.add(new SupportingFile("package.mustache", "", "package.json"));
supportingFiles.add(new SupportingFile("index.mustache", sourceFolder, "index.js"));
supportingFiles.add(new SupportingFile("ApiClient.mustache", sourceFolder, "ApiClient.js"));
}
@Override
@@ -225,7 +228,7 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
@Override
public String toVarName(String name) {
// sanitize name
name = sanitizeName(name);
name = sanitizeName(name); // FIXME parameter should not be assigned. Also declare it as "final"
if("_".equals(name)) {
name = "_u";
@@ -256,7 +259,7 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
@Override
public String toModelName(String name) {
name = sanitizeName(name);
name = sanitizeName(name); // FIXME parameter should not be assigned. Also declare it as "final"
// model name cannot use reserved keyword, e.g. return
if (reservedWords.contains(name)) {
@@ -276,7 +279,7 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
@Override
public String toModelImport(String name) {
return name;
return toModelName(name);
}
@Override
@@ -287,8 +290,8 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
@Override
public String getTypeDeclaration(Property p) {
if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
// ArrayProperty ap = (ArrayProperty) p;
// Property inner = ap.getItems();
return getSwaggerType(p); // TODO: + "/* <" + getTypeDeclaration(inner) + "> */";
} else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
@@ -305,43 +308,22 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
return "[]";
} else if (p instanceof MapProperty) {
return "{}";
} else if (p instanceof LongProperty) {
LongProperty dp = (LongProperty) p;
if (dp.getDefault() != null) {
return dp.getDefault().toString()+"l";
}
return "null";
// added for Javascript
} else if (p instanceof RefProperty) {
RefProperty rp = (RefProperty)p;
return "new " +rp.getSimpleRef() + "()";
return "new " + getTypeDeclaration(p) + "()";
}
return super.toDefaultValue(p);
}
@Override
public String toDefaultValueWithParam(String name, Property p) {
if (p instanceof ArrayProperty) {
return " = new Array();";
} else if (p instanceof MapProperty) {
return " = {}";
} else if (p instanceof LongProperty) {
LongProperty dp = (LongProperty) p;
return " = data." + name + ";";
// added for Javascript
} else if (p instanceof RefProperty) {
RefProperty rp = (RefProperty)p;
if (p instanceof RefProperty) {
return ".constructFromObject(data." + name + ");";
}
return super.toDefaultValueWithParam(name, p);
}
@Override
public String getSwaggerType(Property p) {
String swaggerType = super.getSwaggerType(p);
@@ -382,7 +364,7 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
if (allDefinitions != null && codegenModel != null && codegenModel.parent != null && codegenModel.hasEnums) {
final Model parentModel = allDefinitions.get(toModelName(codegenModel.parent));
final CodegenModel parentCodegenModel = super.fromModel(codegenModel.parent, parentModel);
codegenModel = this.reconcileInlineEnums(codegenModel, parentCodegenModel);
codegenModel = JavascriptClientCodegen.reconcileInlineEnums(codegenModel, parentCodegenModel);
}
return codegenModel;
@@ -437,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;
}
@@ -465,14 +428,14 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
&& !languageSpecificPrimitives.contains(type);
}
private String findCommonPrefixOfVars(List<String> vars) {
private static String findCommonPrefixOfVars(List<String> vars) {
String prefix = StringUtils.getCommonPrefix(vars.toArray(new String[vars.size()]));
// exclude trailing characters that should be part of a valid variable
// e.g. ["status-on", "status-off"] => "status-" (not "status-o")
return prefix.replaceAll("[a-zA-Z0-9]+\\z", "");
}
private String toEnumVarName(String value) {
private static String toEnumVarName(String value) {
String var = value.replaceAll("\\W+", "_").toUpperCase();
if (var.matches("\\d.*")) {
return "_" + var;
@@ -481,7 +444,7 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
}
}
private CodegenModel reconcileInlineEnums(CodegenModel codegenModel, CodegenModel parentCodegenModel) {
private static CodegenModel reconcileInlineEnums(CodegenModel codegenModel, CodegenModel parentCodegenModel) {
// This generator uses inline classes to define enums, which breaks when
// dealing with models that have subTypes. To clean this up, we will analyze
// the parent and child models, look for enums that match, and remove
@@ -529,7 +492,7 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
return codegenModel;
}
private String sanitizePackageName(String packageName) {
private static String sanitizePackageName(String packageName) { // FIXME parameter should not be assigned. Also declare it as "final"
packageName = packageName.trim();
packageName = packageName.replaceAll("[^a-zA-Z0-9_\\.]", "_");
if(Strings.isNullOrEmpty(packageName)) {

View File

@@ -1,271 +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 implements CodegenConfig {
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);
}
// if("jersey2".equals(getLibrary())) {
// embeddedTemplateDir = templateDir = "JavaJaxRS" + File.separator + "jersey2";
// }
supportingFiles.clear();
supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml"));
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
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 != null && 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";
@@ -212,7 +218,7 @@ public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig
}
@SuppressWarnings("unchecked")
private List<Map<String, Object>> getOperations(Map<String, Object> objs) {
private static List<Map<String, Object>> getOperations(Map<String, Object> objs) {
List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
Map<String, Object> apiInfo = (Map<String, Object>) objs.get("apiInfo");
List<Map<String, Object>> apis = (List<Map<String, Object>>) apiInfo.get("apis");
@@ -222,7 +228,7 @@ public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig
return result;
}
private List<Map<String, Object>> sortOperationsByPath(List<CodegenOperation> ops) {
private static List<Map<String, Object>> sortOperationsByPath(List<CodegenOperation> ops) {
Multimap<String, CodegenOperation> opsByPath = ArrayListMultimap.create();
for (CodegenOperation op : ops) {
@@ -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

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

View File

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

View File

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

View File

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

View File

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

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

View File

@@ -2,7 +2,6 @@ package io.swagger.codegen.languages;
import com.fasterxml.jackson.core.JsonProcessingException;
import io.swagger.codegen.CliOption;
import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen;
@@ -19,8 +18,13 @@ 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";
@@ -149,7 +153,7 @@ public class SinatraServerCodegen extends DefaultCodegen implements CodegenConfi
@Override
public String toVarName(String name) {
// replace - with _ e.g. created-at => created_at
name = name.replaceAll("-", "_");
name = name.replaceAll("-", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
// if it's all uppper case, convert to lower case
if (name.matches("^[A-Z_]*$")) {
@@ -201,7 +205,7 @@ public class SinatraServerCodegen extends DefaultCodegen implements CodegenConfi
@Override
public String toApiFilename(String name) {
// replace - with _ e.g. created-at => created_at
name = name.replaceAll("-", "_");
name = name.replaceAll("-", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
// e.g. PhoneNumberApi.rb => phone_number_api.rb
return underscore(name) + "_api";
@@ -233,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

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

View File

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

View File

@@ -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

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

View File

@@ -131,12 +131,8 @@ public class TizenClientCodegen extends DefaultCodegen implements CodegenConfig
@Override
public String toInstantiationType(Property p) {
if (p instanceof MapProperty) {
MapProperty ap = (MapProperty) p;
String inner = getSwaggerType(ap.getAdditionalProperties());
return instantiationTypes.get("map");
} else if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
String inner = getSwaggerType(ap.getItems());
return instantiationTypes.get("array");
} else {
return null;
@@ -220,12 +216,8 @@ public class TizenClientCodegen extends DefaultCodegen implements CodegenConfig
} else if (p instanceof DecimalProperty) {
return "new Long()";
} else if (p instanceof MapProperty) {
MapProperty ap = (MapProperty) p;
String inner = getSwaggerType(ap.getAdditionalProperties());
return "new HashMap()";
} else if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
String inner = getSwaggerType(ap.getItems());
return "new ArrayList()";
}
// else

View File

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