Merge branch 'master' into javascript-auth

Conflicts:
	modules/swagger-codegen/src/main/resources/Javascript/ApiClient.mustache
	modules/swagger-codegen/src/main/resources/Javascript/api.mustache
This commit is contained in:
xhh
2016-02-16 17:08:58 +08:00
308 changed files with 23003 additions and 1833 deletions

6
.gitignore vendored
View File

@@ -62,6 +62,12 @@ samples/client/petstore/python/.projectile
samples/client/petstore/python/.venv/
samples/client/petstore/python/dev-requirements.txt.log
samples/client/petstore/objc/SwaggerClientTests/SwaggerClient.xcodeproj/xcuserdata
samples/client/petstore/swift/SwaggerClientTests/SwaggerClient.xcodeproj/xcuserdata
samples/client/petstore/swift/SwaggerClientTests/SwaggerClient.xcworkspace/xcuserdata
samples/client/petstore/swift/SwaggerClientTests/Pods/Pods.xcodeproj/xcuserdata
samples/client/petstore/swift/SwaggerClientTests/Pods/Pods.xcodeproj/xcshareddata/xcschemes
.settings
*.mustache~

View File

@@ -641,3 +641,6 @@ distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
---
<img src="http://swagger.io/wp-content/uploads/2016/02/logo.jpg"/>

View File

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

View File

@@ -26,6 +26,6 @@ fi
# if you've executed sbt assembly previously it will use that instead.
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="$@ generate -t modules/swagger-codegen/src/main/resources/javascript -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l javascript -o samples/client/petstore/javascript"
ags="$@ generate -t modules/swagger-codegen/src/main/resources/Javascript -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l javascript -o samples/client/petstore/javascript"
java -DappName=PetstoreClient $JAVA_OPTS -jar $executable $ags

View File

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

View File

@@ -32,8 +32,10 @@ import org.apache.maven.project.MavenProject;
import java.io.File;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static io.swagger.codegen.plugin.AdditionalParams.*;
@@ -156,37 +158,33 @@ public class CodeGenMojo extends AbstractMojo {
config.additionalProperties().put(INVOKER_PACKAGE_PARAM, invokerPackage);
}
if (configOptions != null) {
Set<String> definedOptions = new HashSet<String>();
for (CliOption langCliOption : config.cliOptions()) {
if (configOptions.containsKey(langCliOption.getOpt())) {
config.additionalProperties().put(langCliOption.getOpt(),
configOptions.get(langCliOption.getOpt()));
}
definedOptions.add(langCliOption.getOpt());
}
if (configOptions != null) {
if(configOptions.containsKey("import-mappings")) {
Map<String, String> mappings = createMapFromKeyValuePairs(configOptions.get("import-mappings").toString());
Map<String, String> mappings = createMapFromKeyValuePairs(configOptions.remove("import-mappings").toString());
config.importMapping().putAll(mappings);
}
if(configOptions.containsKey("type-mappings")) {
Map<String, String> mappings = createMapFromKeyValuePairs(configOptions.get("type-mappings").toString());
Map<String, String> mappings = createMapFromKeyValuePairs(configOptions.remove("type-mappings").toString());
config.typeMapping().putAll(mappings);
}
if(configOptions.containsKey("instantiation-types")) {
Map<String, String> mappings = createMapFromKeyValuePairs(configOptions.get("instantiation-types").toString());
Map<String, String> mappings = createMapFromKeyValuePairs(configOptions.remove("instantiation-types").toString());
config.instantiationTypes().putAll(mappings);
}
addAdditionalProperties(config, definedOptions, configOptions);
}
if (null != configurationFile) {
Config genConfig = ConfigParser.read(configurationFile);
if (null != genConfig) {
for (CliOption langCliOption : config.cliOptions()) {
if (genConfig.hasOption(langCliOption.getOpt())) {
config.additionalProperties().put(langCliOption.getOpt(), genConfig.getOption(langCliOption.getOpt()));
}
}
addAdditionalProperties(config, definedOptions, genConfig.getOptions());
} else {
throw new RuntimeException("Unable to read configuration file");
}
@@ -218,6 +216,15 @@ public class CodeGenMojo extends AbstractMojo {
}
}
private void addAdditionalProperties(CodegenConfig config, Set<String> definedOptions, Map<?,?> configOptions) {
for(Map.Entry<?, ?> configEntry : configOptions.entrySet()) {
config.additionalProperties().put(configEntry.getKey().toString(), configEntry.getValue());
if(!definedOptions.contains(configEntry.getKey())) {
getLog().warn("Additional property: " + configEntry.getKey() + " is not defined for this language.");
}
}
}
private static Map<String, String> createMapFromKeyValuePairs(String commaSeparatedKVPairs) {
final List<Pair<String, String>> pairs = OptionUtils.parseCommaSeparatedTuples(commaSeparatedKVPairs);

View File

@@ -19,6 +19,8 @@ public interface CodegenConfig {
Map<String, Object> additionalProperties();
Map<String, Object> vendorExtensions();
String testPackage();
String apiPackage();

View File

@@ -71,6 +71,7 @@ public class DefaultCodegen {
protected String templateDir;
protected String embeddedTemplateDir;
protected Map<String, Object> additionalProperties = new HashMap<String, Object>();
protected Map<String, Object> vendorExtensions = new HashMap<String, Object>();
protected List<SupportingFile> supportingFiles = new ArrayList<SupportingFile>();
protected List<CliOption> cliOptions = new ArrayList<CliOption>();
protected boolean skipOverwrite;
@@ -247,6 +248,10 @@ public class DefaultCodegen {
return additionalProperties;
}
public Map<String, Object> vendorExtensions() {
return vendorExtensions;
}
public List<SupportingFile> supportingFiles() {
return supportingFiles;
}
@@ -593,6 +598,9 @@ public class DefaultCodegen {
*/
@SuppressWarnings("static-method")
public String toExampleValue(Property p) {
if(p.getExample() != null) {
return p.getExample().toString();
}
if (p instanceof StringProperty) {
return "null";
} else if (p instanceof BooleanProperty) {
@@ -1411,6 +1419,8 @@ public class DefaultCodegen {
} else if (param instanceof FormParameter) {
if ("file".equalsIgnoreCase(((FormParameter) param).getType())) {
p.isFile = true;
} else if("file".equals(p.baseType)){
p.isFile = true;
} else {
p.notFile = true;
}
@@ -2205,4 +2215,22 @@ public class DefaultCodegen {
// $php_variable => php_variable
return name.replaceAll("[^a-zA-Z0-9_]", "");
}
/**
* only write if the file doesn't exist
*
* @param supportingFile
*/
public void writeOptional(SupportingFile supportingFile) {
String folder = supportingFile.folder;
if(!"".equals(folder)) {
folder += File.separator + supportingFile.destinationFilename;
}
else {
folder = supportingFile.destinationFilename;
}
if(!new File(folder).exists()) {
supportingFiles.add(supportingFile);
}
}
}

View File

@@ -134,6 +134,10 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
}
}
if(swagger.getVendorExtensions() != null) {
config.vendorExtensions().putAll(swagger.getVendorExtensions());
}
StringBuilder hostBuilder = new StringBuilder();
String scheme;
if (swagger.getSchemes() != null && swagger.getSchemes().size() > 0) {
@@ -274,6 +278,10 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
operation.put("classVarName", config.toApiVarName(tag));
operation.put("importPath", config.toApiImport(tag));
if(!config.vendorExtensions().isEmpty()) {
operation.put("vendorExtensions", config.vendorExtensions());
}
// Pass sortParamsByRequiredFlag through to the Mustache template...
boolean sortParamsByRequiredFlag = true;
if (this.config.additionalProperties().containsKey(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG)) {

View File

@@ -218,7 +218,12 @@ public class InlineModelResolver {
Map<String, Model> modelsToAdd = new HashMap<String, Model>();
for (String key : properties.keySet()) {
Property property = properties.get(key);
if (property instanceof ObjectProperty && ((ObjectProperty)property).getProperties().size() > 0) {
if(property instanceof ObjectProperty && ((ObjectProperty)property).getProperties() == null) {
MapProperty mp = new MapProperty();
mp.setAdditionalProperties(new StringProperty());
properties.put(key, mp);
}
else if (property instanceof ObjectProperty && ((ObjectProperty)property).getProperties().size() > 0) {
String modelName = uniqueName(path + "_" + key);
ObjectProperty op = (ObjectProperty) property;
@@ -276,7 +281,6 @@ public class InlineModelResolver {
swagger.addDefinition(modelName, innerModel);
}
}
} else {
}
}
if (propsToUpdate.size() > 0) {

View File

@@ -0,0 +1,511 @@
package io.swagger.codegen.languages;
import io.swagger.codegen.*;
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.*;
public abstract class AbstractCSharpCodegen extends DefaultCodegen implements CodegenConfig {
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 packageVersion = "1.0.0";
protected String packageName = "IO.Swagger";
protected String sourceFolder = "src" + File.separator + packageName;
protected Set<String> collectionTypes;
protected Set<String> mapTypes;
protected Logger LOGGER = LoggerFactory.getLogger(AbstractCSharpCodegen.class);
public AbstractCSharpCodegen() {
super();
outputFolder = "generated-code" + File.separator + this.getName();
embeddedTemplateDir = templateDir = this.getName();
collectionTypes = new HashSet<String>(
Arrays.asList(
"IList", "List",
"ICollection", "Collection",
"IEnumerable")
);
mapTypes = new HashSet<String>(
Arrays.asList("IDictionary")
);
reservedWords = new HashSet<String>(
Arrays.asList(
// local variable names in API methods (endpoints)
"path_", "pathParams", "queryParams", "headerParams", "formParams", "fileParams",
"postBody", "http_header_accepts", "http_header_accept", "apiKeyValue", "response",
"statusCode",
// C# reserved words
"abstract", "as", "base", "bool", "break", "byte", "case", "catch", "char", "checked",
"class", "const", "continue", "decimal", "default", "delegate", "do", "double", "else",
"enum", "event", "explicit", "extern", "false", "finally", "fixed", "float", "for",
"foreach", "goto", "if", "implicit", "in", "int", "interface", "internal", "is", "lock",
"long", "namespace", "new", "null", "object", "operator", "out", "override", "params",
"private", "protected", "public", "readonly", "ref", "return", "sbyte", "sealed",
"short", "sizeof", "stackalloc", "static", "string", "struct", "switch", "this", "throw",
"true", "try", "typeof", "uint", "ulong", "unchecked", "unsafe", "ushort", "using",
"virtual", "void", "volatile", "while")
);
// TODO: Either include fully qualified names here or handle in DefaultCodegen via lastIndexOf(".") search
languageSpecificPrimitives = new HashSet<String>(
Arrays.asList(
"String",
"string",
"bool?",
"double?",
"int?",
"long?",
"float?",
"byte[]",
"ICollection",
"Collection",
"List",
"Dictionary",
"DateTime?",
"DateTimeOffset?",
"String",
"Boolean",
"Double",
"Int32",
"Int64",
"Float",
"Guid",
"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");
// Nullable types here assume C# 2 support is not part of base
typeMapping = new HashMap<String, String>();
typeMapping.put("string", "string");
typeMapping.put("binary", "byte[]");
typeMapping.put("boolean", "bool?");
typeMapping.put("integer", "int?");
typeMapping.put("float", "float?");
typeMapping.put("long", "long?");
typeMapping.put("double", "double?");
typeMapping.put("number", "double?");
typeMapping.put("datetime", "DateTime?");
typeMapping.put("date", "DateTime?");
typeMapping.put("file", "Stream");
typeMapping.put("array", "List");
typeMapping.put("list", "List");
typeMapping.put("map", "Dictionary");
typeMapping.put("object", "Object");
typeMapping.put("uuid", "Guid");
}
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 setOptionalMethodArgumentFlag(boolean flag) {
this.optionalMethodArgumentFlag = flag;
}
protected void addOption(String key, String description, String defaultValue) {
CliOption option = new CliOption(key, description);
if (defaultValue != null) option.defaultValue(defaultValue);
cliOptions.add(option);
}
protected void addSwitch(String key, String description, Boolean defaultValue) {
CliOption option = CliOption.newBoolean(key, description);
if (defaultValue != null) option.defaultValue(defaultValue.toString());
cliOptions.add(option);
}
public void useDateTimeOffset(boolean flag) {
this.useDateTimeOffsetFlag = flag;
if (flag) typeMapping.put("datetime", "DateTimeOffset?");
else typeMapping.put("datetime", "DateTime?");
}
@Override
public void processOpts() {
super.processOpts();
// {{packageVersion}}
if (additionalProperties.containsKey(CodegenConstants.PACKAGE_VERSION)) {
setPackageVersion((String) additionalProperties.get(CodegenConstants.PACKAGE_VERSION));
} else {
additionalProperties.put(CodegenConstants.PACKAGE_VERSION, packageVersion);
}
// {{sourceFolder}}
if (additionalProperties.containsKey(CodegenConstants.SOURCE_FOLDER)) {
setSourceFolder((String) additionalProperties.get(CodegenConstants.SOURCE_FOLDER));
} else {
additionalProperties.put(CodegenConstants.SOURCE_FOLDER, this.sourceFolder);
}
// {{packageName}}
if (additionalProperties.containsKey(CodegenConstants.PACKAGE_NAME)) {
setPackageName((String) additionalProperties.get(CodegenConstants.PACKAGE_NAME));
} else {
additionalProperties.put(CodegenConstants.PACKAGE_NAME, packageName);
}
// {{useDateTimeOffset}}
if (additionalProperties.containsKey(CodegenConstants.USE_DATETIME_OFFSET)) {
useDateTimeOffset(Boolean.valueOf(additionalProperties.get(CodegenConstants.USE_DATETIME_OFFSET).toString()));
}
additionalProperties.put(CodegenConstants.USE_DATETIME_OFFSET, useDateTimeOffsetFlag);
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()));
}
}
@Override
public Map<String, Object> postProcessModels(Map<String, Object> objs) {
List<Object> models = (List<Object>) objs.get("models");
for (Object _mo : models) {
Map<String, Object> mo = (Map<String, Object>) _mo;
CodegenModel cm = (CodegenModel) mo.get("model");
for (CodegenProperty var : cm.vars) {
// check to see if model name is same as the property name
// which will result in compilation error
// if found, prepend with _ to workaround the limitation
if (var.name.equals(cm.name)) {
var.name = "_" + var.name;
}
}
}
return objs;
}
@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) {
// Check return types for collection
if (operation.returnType != null) {
String typeMapping;
int namespaceEnd = operation.returnType.lastIndexOf(".");
if (namespaceEnd > 0) {
typeMapping = operation.returnType.substring(namespaceEnd);
} else {
typeMapping = operation.returnType;
}
if (this.collectionTypes.contains(typeMapping)) {
operation.isListContainer = true;
operation.returnContainer = operation.returnType;
if (this.returnICollection && (
typeMapping.startsWith("List") ||
typeMapping.startsWith("Collection"))) {
// NOTE: ICollection works for both List<T> and Collection<T>
int genericStart = typeMapping.indexOf("<");
if (genericStart > 0) {
operation.returnType = "ICollection" + typeMapping.substring(genericStart);
}
}
} else {
operation.returnContainer = operation.returnType;
operation.isMapContainer = this.mapTypes.contains(typeMapping);
}
}
processOperation(operation);
}
}
}
return objs;
}
protected void processOperation(CodegenOperation operation) {
// default noop
}
@Override
public String apiFileFolder() {
return outputFolder + File.separator + sourceFolder + File.separator + apiPackage().replace('.', File.separatorChar);
}
@Override
public String modelFileFolder() {
return outputFolder + File.separator + sourceFolder + File.separator + modelPackage().replace('.', File.separatorChar);
}
@Override
public String toModelFilename(String name) {
// should be the same as the model name
return toModelName(name);
}
@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
if (reservedWords.contains(operationId)) {
throw new RuntimeException(operationId + " (reserved word) cannot be used as method name");
}
return camelize(sanitizeName(operationId));
}
@Override
public String toVarName(String name) {
// sanitize 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_]*$")) {
return name;
}
// camelize the variable name
// pet_id => PetId
name = camelize(name);
// for reserved word or word starting with number, append _
if (reservedWords.contains(name) || name.matches("^\\d.*")) {
name = escapeReservedWord(name);
}
return name;
}
@Override
public String toParamName(String name) {
// 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) the variable name
// pet_id => petId
name = camelize(name, true);
// for reserved word or word starting with number, append _
if (reservedWords.contains(name) || name.matches("^\\d.*")) {
name = escapeReservedWord(name);
}
return name;
}
@Override
public String escapeReservedWord(String name) {
return "_" + name;
}
/**
* Return the example value of the property
*
* @param p Swagger property object
* @return string presentation of the example value of the property
*/
@Override
public String toExampleValue(Property p) {
if (p instanceof StringProperty) {
StringProperty dp = (StringProperty) p;
if (dp.getExample() != null) {
return "\"" + dp.getExample().toString() + "\"";
}
} else if (p instanceof BooleanProperty) {
BooleanProperty dp = (BooleanProperty) p;
if (dp.getExample() != null) {
return dp.getExample().toString();
}
} else if (p instanceof DateProperty) {
// TODO
} else if (p instanceof DateTimeProperty) {
// TODO
} else if (p instanceof DoubleProperty) {
DoubleProperty dp = (DoubleProperty) p;
if (dp.getExample() != null) {
return dp.getExample().toString();
}
} else if (p instanceof FloatProperty) {
FloatProperty dp = (FloatProperty) p;
if (dp.getExample() != null) {
return dp.getExample().toString();
}
} else if (p instanceof IntegerProperty) {
IntegerProperty dp = (IntegerProperty) p;
if (dp.getExample() != null) {
return dp.getExample().toString();
}
} else if (p instanceof LongProperty) {
LongProperty dp = (LongProperty) p;
if (dp.getExample() != null) {
return dp.getExample().toString();
}
}
return null;
}
/**
* Return the default value of the property
*
* @param p Swagger property object
* @return string presentation of the default value of the property
*/
@Override
public String toDefaultValue(Property p) {
if (p instanceof StringProperty) {
StringProperty dp = (StringProperty) p;
if (dp.getDefault() != null) {
return "\"" + dp.getDefault().toString() + "\"";
}
} else if (p instanceof BooleanProperty) {
BooleanProperty dp = (BooleanProperty) p;
if (dp.getDefault() != null) {
return dp.getDefault().toString();
}
} else if (p instanceof DateProperty) {
// TODO
} else if (p instanceof DateTimeProperty) {
// TODO
} else if (p instanceof DoubleProperty) {
DoubleProperty dp = (DoubleProperty) p;
if (dp.getDefault() != null) {
return dp.getDefault().toString();
}
} else if (p instanceof FloatProperty) {
FloatProperty dp = (FloatProperty) p;
if (dp.getDefault() != null) {
return dp.getDefault().toString();
}
} else if (p instanceof IntegerProperty) {
IntegerProperty dp = (IntegerProperty) p;
if (dp.getDefault() != null) {
return dp.getDefault().toString();
}
} else if (p instanceof LongProperty) {
LongProperty dp = (LongProperty) p;
if (dp.getDefault() != null) {
return dp.getDefault().toString();
}
}
return null;
}
@Override
public String getSwaggerType(Property p) {
String swaggerType = super.getSwaggerType(p);
String type;
if (typeMapping.containsKey(swaggerType.toLowerCase())) {
type = typeMapping.get(swaggerType.toLowerCase());
if (languageSpecificPrimitives.contains(type)) {
return type;
}
} else {
type = swaggerType;
}
return toModelName(type);
}
@Override
public String getTypeDeclaration(Property p) {
if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">";
} else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
return getSwaggerType(p) + "<string, " + getTypeDeclaration(inner) + ">";
}
return super.getTypeDeclaration(p);
}
@Override
public String toModelName(String name) {
name = sanitizeName(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 apiTestFileFolder() {
return outputFolder + ".Test";
}
@Override
public String modelTestFileFolder() {
return outputFolder + ".Test";
}
@Override
public String toApiTestFilename(String name) {
return toApiName(name) + "Tests";
}
@Override
public String toModelTestFilename(String name) {
return toModelName(name) + "Tests";
}
public void setPackageName(String packageName) {
this.packageName = packageName;
}
public void setPackageVersion(String packageVersion) {
this.packageVersion = packageVersion;
}
public void setSourceFolder(String sourceFolder) {
this.sourceFolder = sourceFolder;
}
}

View File

@@ -9,16 +9,7 @@ import org.slf4j.LoggerFactory;
import java.io.File;
import java.util.*;
public class AspNet5ServerCodegen extends DefaultCodegen implements CodegenConfig {
protected boolean useDateTimeOffsetFlag = false;
protected String packageName = "IO.Swagger";
protected String packageVersion = "1.0.0";
protected boolean useCollection = false;
protected boolean returnICollection = false;
protected String sourceFolder = "src" + File.separator + packageName;
protected Set<String> collectionTypes;
protected Set<String> mapTypes;
public class AspNet5ServerCodegen extends AbstractCSharpCodegen {
@SuppressWarnings("hiding")
protected Logger LOGGER = LoggerFactory.getLogger(AspNet5ServerCodegen.class);
@@ -26,90 +17,21 @@ public class AspNet5ServerCodegen extends DefaultCodegen implements CodegenConfi
public AspNet5ServerCodegen() {
super();
outputFolder = "generated-code" + File.separator + "aspnet5";
embeddedTemplateDir = templateDir = "aspnet5";
outputFolder = "generated-code" + File.separator + this.getName();
modelTemplateFiles.put("model.mustache", ".cs");
apiTemplateFiles.put("controller.mustache", ".cs");
// TODO: Create a base C# abstract type to avoid duplication of language functionality
collectionTypes = new HashSet<String>(
Arrays.asList(
"IList", "List",
"ICollection", "Collection",
"IEnumerable")
);
mapTypes = new HashSet<String>(
Arrays.asList("IDictionary")
);
reservedWords = new HashSet<String>(
Arrays.asList(
// local variable names in API methods (endpoints)
"path_", "pathParams", "queryParams", "headerParams", "formParams", "fileParams",
"postBody", "http_header_accepts", "http_header_accept", "apiKeyValue", "response",
"statusCode",
// C# reserved words
"abstract", "as", "base", "bool", "break", "byte", "case", "catch", "char", "checked",
"class", "const", "continue", "decimal", "default", "delegate", "do", "double", "else",
"enum", "event", "explicit", "extern", "false", "finally", "fixed", "float", "for",
"foreach", "goto", "if", "implicit", "in", "int", "interface", "internal", "is", "lock",
"long", "namespace", "new", "null", "object", "operator", "out", "override", "params",
"private", "protected", "public", "readonly", "ref", "return", "sbyte", "sealed",
"short", "sizeof", "stackalloc", "static", "string", "struct", "switch", "this", "throw",
"true", "try", "typeof", "uint", "ulong", "unchecked", "unsafe", "ushort", "using",
"virtual", "void", "volatile", "while")
);
languageSpecificPrimitives = new HashSet<String>(
Arrays.asList(
"String",
"string",
"bool?",
"double?",
"int?",
"long?",
"float?",
"byte[]",
"ICollection",
"Collection",
"List",
"Dictionary",
"DateTime?",
"DateTimeOffset?",
"String",
"Boolean",
"Double",
"Integer",
"Long",
"Float",
"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>();
typeMapping.put("string", "string");
typeMapping.put("binary", "byte[]");
typeMapping.put("boolean", "bool?");
typeMapping.put("integer", "int?");
typeMapping.put("float", "float?");
typeMapping.put("long", "long?");
typeMapping.put("double", "double?");
typeMapping.put("number", "double?");
typeMapping.put("datetime", "DateTime?");
typeMapping.put("date", "DateTime?");
typeMapping.put("file", "Stream");
typeMapping.put("array", "List");
typeMapping.put("list", "List");
typeMapping.put("map", "Dictionary");
typeMapping.put("object", "Object");
// contextually reserved words
reservedWords.add("var");
reservedWords.add("async");
reservedWords.add("await");
reservedWords.add("dynamic");
reservedWords.add("yield");
cliOptions.clear();
// CLI options
addOption(CodegenConstants.PACKAGE_NAME,
"C# package name (convention: Title.Case).",
this.packageName);
@@ -122,82 +44,46 @@ public class AspNet5ServerCodegen extends DefaultCodegen implements CodegenConfi
CodegenConstants.SOURCE_FOLDER_DESC,
sourceFolder);
// CLI Switches
addSwitch(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG,
CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG_DESC,
Boolean.TRUE);
addSwitch(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG,
CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG_DESC,
Boolean.TRUE);
this.sortParamsByRequiredFlag);
addSwitch(CodegenConstants.USE_DATETIME_OFFSET,
CodegenConstants.USE_DATETIME_OFFSET_DESC,
Boolean.FALSE);
this.useDateTimeOffsetFlag);
addSwitch(CodegenConstants.USE_COLLECTION,
CodegenConstants.USE_COLLECTION_DESC,
Boolean.FALSE);
this.useCollection);
addSwitch(CodegenConstants.RETURN_ICOLLECTION,
CodegenConstants.RETURN_ICOLLECTION_DESC,
Boolean.FALSE);
this.returnICollection);
}
private void addOption(String key, String description, String defaultValue){
CliOption option = new CliOption(key, description);
if(defaultValue != null) option.defaultValue(defaultValue);
cliOptions.add(option);
@Override
public CodegenType getTag() {
return CodegenType.SERVER;
}
private void addSwitch(String key, String description, Boolean defaultValue){
CliOption option = CliOption.newBoolean(key, description);
if(defaultValue != null) option.defaultValue(defaultValue.toString());
cliOptions.add(option);
@Override
public String getName() {
return "aspnet5";
}
@Override
public String getHelp() {
return "Generates an ASP.NET 5 Web API server.";
}
@Override
public void processOpts() {
super.processOpts();
// {{packageVersion}}
if (additionalProperties.containsKey(CodegenConstants.PACKAGE_VERSION)) {
setPackageVersion((String) additionalProperties.get(CodegenConstants.PACKAGE_VERSION));
} else {
additionalProperties.put(CodegenConstants.PACKAGE_VERSION, packageVersion);
}
// {{sourceFolder}}
if (additionalProperties.containsKey(CodegenConstants.SOURCE_FOLDER)){
setSourceFolder((String) additionalProperties.get(CodegenConstants.SOURCE_FOLDER));
} else {
additionalProperties.put(CodegenConstants.SOURCE_FOLDER, this.sourceFolder);
}
// {{packageName}}
if (additionalProperties.containsKey(CodegenConstants.PACKAGE_NAME)) {
setPackageName((String) additionalProperties.get(CodegenConstants.PACKAGE_NAME));
} else {
additionalProperties.put(CodegenConstants.PACKAGE_NAME, packageName);
}
apiPackage = packageName + ".Controllers";
modelPackage = packageName + ".Models";
// {{useDateTimeOffset}}
if (additionalProperties.containsKey(CodegenConstants.USE_DATETIME_OFFSET))
{
useDateTimeOffset(Boolean.valueOf(additionalProperties.get(CodegenConstants.USE_DATETIME_OFFSET).toString()));
}
additionalProperties.put(CodegenConstants.USE_DATETIME_OFFSET, useDateTimeOffsetFlag);
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()));
}
supportingFiles.add(new SupportingFile("global.json", "", "global.json"));
supportingFiles.add(new SupportingFile("build.mustache", "", "build.sh"));
supportingFiles.add(new SupportingFile("Dockerfile.mustache", this.sourceFolder, "Dockerfile"));
@@ -207,43 +93,11 @@ public class AspNet5ServerCodegen extends DefaultCodegen implements CodegenConfi
supportingFiles.add(new SupportingFile("project.mustache", this.sourceFolder, "project.json"));
supportingFiles.add(new SupportingFile("Startup.mustache", this.sourceFolder, "Startup.cs"));
supportingFiles.add(new SupportingFile("Properties"+File.separator +"launchSettings.json", this.sourceFolder + File.separator + "Properties", "launchSettings.json"));
supportingFiles.add(new SupportingFile("Properties" + File.separator + "launchSettings.json", this.sourceFolder + File.separator + "Properties", "launchSettings.json"));
supportingFiles.add(new SupportingFile("wwwroot" +File.separator + "README.md", this.sourceFolder + File.separator + "wwwroot", "README.md"));
supportingFiles.add(new SupportingFile("wwwroot" +File.separator + "index.html", this.sourceFolder + File.separator + "wwwroot", "index.html"));
supportingFiles.add(new SupportingFile("wwwroot" +File.separator + "web.config", this.sourceFolder + File.separator + "wwwroot", "web.config"));
}
public void useDateTimeOffset(boolean flag) {
this.useDateTimeOffsetFlag = flag;
if (flag) typeMapping.put("datetime", "DateTimeOffset?");
else typeMapping.put("datetime", "DateTime?");
}
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");
}
}
@Override
public CodegenType getTag() { return CodegenType.SERVER; }
@Override
public String getName() { return "aspnet5"; }
@Override
public String getHelp() {
return "Generates an ASP.NET 5 Web API server.";
supportingFiles.add(new SupportingFile("wwwroot" + File.separator + "README.md", this.sourceFolder + File.separator + "wwwroot", "README.md"));
supportingFiles.add(new SupportingFile("wwwroot" + File.separator + "index.html", this.sourceFolder + File.separator + "wwwroot", "index.html"));
supportingFiles.add(new SupportingFile("wwwroot" + File.separator + "web.config", this.sourceFolder + File.separator + "wwwroot", "web.config"));
}
@Override
@@ -256,260 +110,20 @@ public class AspNet5ServerCodegen extends DefaultCodegen implements CodegenConfi
return outputFolder + File.separator + sourceFolder + File.separator + "Models";
}
// TODO: Create a base C# abstract type to avoid duplication of language functionality
@Override
public String escapeReservedWord(String name) {
return "_" + name;
}
protected void processOperation(CodegenOperation operation) {
super.processOperation(operation);
// TODO: Create a base C# abstract type to avoid duplication of language functionality
@Override
public String toVarName(String name) {
// sanitize 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_]*$")) {
return name;
}
// camelize the variable name
// pet_id => PetId
name = camelize(name);
// for reserved word or word starting with number, append _
if (reservedWords.contains(name) || name.matches("^\\d.*")) {
name = escapeReservedWord(name);
}
return name;
}
// TODO: Create a base C# abstract type to avoid duplication of language functionality
@Override
public String toParamName(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) the variable name
// pet_id => petId
name = camelize(name, true);
// for reserved word or word starting with number, append _
if (reservedWords.contains(name) || name.matches("^\\d.*")) {
name = escapeReservedWord(name);
}
return name;
}
// TODO: Create a base C# abstract type to avoid duplication of language functionality
@Override
public String toModelName(String name) {
name = sanitizeName(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);
}
// TODO: Create a base C# abstract type to avoid duplication of language functionality
@Override
public String toModelFilename(String name) {
// should be the same as the model name
return toModelName(name);
}
// TODO: Create a base C# abstract type to avoid duplication of language functionality
@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) {
// HACK: Unlikely in the wild, but we need to clean operation paths for MVC Routing
if(operation.path != null){
if (operation.path != null) {
String original = operation.path;
operation.path = operation.path.replace("?", "/");
if(!original.equals(operation.path)){
if (!original.equals(operation.path)) {
LOGGER.warn("Normalized " + original + " to " + operation.path + ". Please verify generated source.");
}
}
// Check return types for collection
if (operation.returnType != null) {
String typeMapping;
int namespaceEnd = operation.returnType.lastIndexOf(".");
if(namespaceEnd > 0) {
typeMapping = operation.returnType.substring(namespaceEnd);
} else {
typeMapping = operation.returnType;
}
if(this.collectionTypes.contains(typeMapping)){
operation.isListContainer = true;
operation.returnContainer = operation.returnType;
if( this.returnICollection && (
typeMapping.startsWith("List")||
typeMapping.startsWith("Collection")) ) {
// NOTE: ICollection works for both List<T> and Collection<T>
int genericStart = typeMapping.indexOf("<");
if(genericStart > 0) {
operation.returnType = "ICollection" + typeMapping.substring(genericStart);
}
}
} else {
operation.returnContainer = operation.returnType;
operation.isMapContainer = this.mapTypes.contains(typeMapping);
}
}
// Converts, for example, PUT to HttpPut for controller attributes
operation.httpMethod = "Http" + operation.httpMethod.substring(0,1) + operation.httpMethod.substring(1).toLowerCase();
}
}
}
return objs;
}
// TODO: Create a base C# abstract type to avoid duplication of language functionality
@Override
public String getTypeDeclaration(Property p) {
if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">";
} else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
return getSwaggerType(p) + "<string, " + getTypeDeclaration(inner) + ">";
}
return super.getTypeDeclaration(p);
}
// TODO: Create a base C# abstract type to avoid duplication of language functionality
@Override
public String getSwaggerType(Property p) {
String swaggerType = super.getSwaggerType(p);
String type = null;
if (typeMapping.containsKey(swaggerType.toLowerCase())) {
type = typeMapping.get(swaggerType.toLowerCase());
if (languageSpecificPrimitives.contains(type)) {
return type;
}
} else {
type = swaggerType;
}
return toModelName(type);
}
// TODO: Create a base C# abstract type to avoid duplication of language functionality
@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
if (reservedWords.contains(operationId)) {
throw new RuntimeException(operationId + " (reserved word) cannot be used as method name");
}
return camelize(sanitizeName(operationId));
}
// TODO: Create a base C# abstract type to avoid duplication of language functionality
@Override
public Map<String, Object> postProcessModels(Map<String, Object> objs) {
List<Object> models = (List<Object>) objs.get("models");
for (Object _mo : models) {
Map<String, Object> mo = (Map<String, Object>) _mo;
CodegenModel cm = (CodegenModel) mo.get("model");
for (CodegenProperty var : cm.vars) {
// check to see if model name is same as the property name
// which will result in compilation error
// if found, prepend with _ to workaround the limitation
if (var.name.equals(cm.name)) {
var.name = "_" + var.name;
}
}
}
return objs;
}
// TODO: Create a base C# abstract type to avoid duplication of language functionality
/**
* Return the default value of the property
*
* @param p Swagger property object
* @return string presentation of the default value of the property
*/
@Override
public String toDefaultValue(Property p) {
if (p instanceof StringProperty) {
StringProperty dp = (StringProperty) p;
if (dp.getDefault() != null) {
return "\"" + dp.getDefault().toString() + "\"";
}
} else if (p instanceof BooleanProperty) {
BooleanProperty dp = (BooleanProperty) p;
if (dp.getDefault() != null) {
return dp.getDefault().toString();
}
} else if (p instanceof DateProperty) {
// TODO
} else if (p instanceof DateTimeProperty) {
// TODO
} else if (p instanceof DoubleProperty) {
DoubleProperty dp = (DoubleProperty) p;
if (dp.getDefault() != null) {
return dp.getDefault().toString();
}
} else if (p instanceof FloatProperty) {
FloatProperty dp = (FloatProperty) p;
if (dp.getDefault() != null) {
return dp.getDefault().toString();
}
} else if (p instanceof IntegerProperty) {
IntegerProperty dp = (IntegerProperty) p;
if (dp.getDefault() != null) {
return dp.getDefault().toString();
}
} else if (p instanceof LongProperty) {
LongProperty dp = (LongProperty) p;
if (dp.getDefault() != null) {
return dp.getDefault().toString();
}
}
return null;
}
public void setPackageName(String packageName) {
this.packageName = packageName;
}
public void setPackageVersion(String packageVersion) {
this.packageVersion = packageVersion;
}
public void setSourceFolder(String sourceFolder) {
this.sourceFolder = sourceFolder;
operation.httpMethod = "Http" + operation.httpMethod.substring(0, 1) + operation.httpMethod.substring(1).toLowerCase();
}
}

View File

@@ -22,159 +22,85 @@ import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig {
@SuppressWarnings({ "unused", "hiding" })
public class CSharpClientCodegen extends AbstractCSharpCodegen {
@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";
protected String packageCompany = "Swagger";
protected String packageCopyright = "No Copyright";
protected String packageName = "IO.Swagger";
protected String packageVersion = "1.0.0";
protected String clientPackage = "IO.Swagger.Client";
protected String sourceFolder = "src" + File.separator + "main" + File.separator + "csharp";
public CSharpClientCodegen() {
super();
outputFolder = "generated-code" + File.separator + "csharp";
modelTemplateFiles.put("model.mustache", ".cs");
apiTemplateFiles.put("api.mustache", ".cs");
embeddedTemplateDir = templateDir = "csharp";
apiPackage = "IO.Swagger.Api";
modelPackage = "IO.Swagger.Model";
modelTestTemplateFiles.put("model_test.mustache", ".cs");
apiTestTemplateFiles.put("api_test.mustache", ".cs");
reservedWords = new HashSet<String>(
Arrays.asList(
// local variable names in API methods (endpoints)
"path_", "pathParams", "queryParams", "headerParams", "formParams", "fileParams",
"postBody", "http_header_accepts", "http_header_accept", "apiKeyValue", "response",
"statusCode",
// C# reserved words
"abstract", "as", "base", "bool", "break", "byte", "case", "catch", "char", "checked",
"class", "const", "continue", "decimal", "default", "delegate", "do", "double", "else",
"enum", "event", "explicit", "extern", "false", "finally", "fixed", "float", "for",
"foreach", "goto", "if", "implicit", "in", "int", "interface", "internal", "is", "lock",
"long", "namespace", "new", "null", "object", "operator", "out", "override", "params",
"private", "protected", "public", "readonly", "ref", "return", "sbyte", "sealed",
"short", "sizeof", "stackalloc", "static", "string", "struct", "switch", "this", "throw",
"true", "try", "typeof", "uint", "ulong", "unchecked", "unsafe", "ushort", "using",
"virtual", "void", "volatile", "while")
);
languageSpecificPrimitives = new HashSet<String>(
Arrays.asList(
"String",
"string",
"bool?",
"double?",
"int?",
"long?",
"float?",
"byte[]",
"ICollection",
"Collection",
"List",
"Dictionary",
"DateTime?",
"DateTimeOffset?",
"String",
"Boolean",
"Double",
"Integer",
"Long",
"Float",
"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>();
typeMapping.put("string", "string");
typeMapping.put("binary", "byte[]");
typeMapping.put("boolean", "bool?");
typeMapping.put("integer", "int?");
typeMapping.put("float", "float?");
typeMapping.put("long", "long?");
typeMapping.put("double", "double?");
typeMapping.put("number", "double?");
typeMapping.put("datetime", "DateTime?");
typeMapping.put("date", "DateTime?");
typeMapping.put("file", "Stream");
typeMapping.put("array", "List");
typeMapping.put("list", "List");
typeMapping.put("map", "Dictionary");
typeMapping.put("object", "Object");
// C# client default
setSourceFolder("src" + File.separator + "main" + File.separator + "csharp");
cliOptions.clear();
cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME, "C# package name (convention: Camel.Case).")
.defaultValue("IO.Swagger"));
cliOptions.add(new CliOption(CodegenConstants.PACKAGE_VERSION, "C# package version.").defaultValue("1.0.0"));
cliOptions.add(CliOption.newBoolean(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG,
CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG_DESC).defaultValue(Boolean.TRUE.toString()));
cliOptions.add(CliOption.newBoolean(CodegenConstants.OPTIONAL_METHOD_ARGUMENT, "C# Optional method argument, " +
"e.g. void square(int x=10) (.net 4.0+ only)."));
cliOptions.add(CliOption.newBoolean(CodegenConstants.OPTIONAL_ASSEMBLY_INFO,
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));
// CLI options
addOption(CodegenConstants.PACKAGE_NAME,
"C# package name (convention: Title.Case).",
this.packageName);
addOption(CodegenConstants.PACKAGE_VERSION,
"C# package version.",
this.packageVersion);
addOption(CodegenConstants.SOURCE_FOLDER,
CodegenConstants.SOURCE_FOLDER_DESC,
sourceFolder);
addOption(CodegenConstants.OPTIONAL_PROJECT_GUID,
CodegenConstants.OPTIONAL_PROJECT_GUID_DESC,
null);
// CLI Switches
addSwitch(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG,
CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG_DESC,
this.sortParamsByRequiredFlag);
addSwitch(CodegenConstants.USE_DATETIME_OFFSET,
CodegenConstants.USE_DATETIME_OFFSET_DESC,
this.useDateTimeOffsetFlag);
addSwitch(CodegenConstants.USE_COLLECTION,
CodegenConstants.USE_COLLECTION_DESC,
this.useCollection);
addSwitch(CodegenConstants.RETURN_ICOLLECTION,
CodegenConstants.RETURN_ICOLLECTION_DESC,
this.returnICollection);
addSwitch(CodegenConstants.OPTIONAL_METHOD_ARGUMENT,
"C# Optional method argument, e.g. void square(int x=10) (.net 4.0+ only).",
this.optionalMethodArgumentFlag);
addSwitch(CodegenConstants.OPTIONAL_ASSEMBLY_INFO,
CodegenConstants.OPTIONAL_ASSEMBLY_INFO_DESC,
this.optionalAssemblyInfoFlag);
addSwitch(CodegenConstants.OPTIONAL_PROJECT_FILE,
CodegenConstants.OPTIONAL_PROJECT_FILE_DESC,
this.optionalProjectFileFlag);
}
@Override
public void processOpts() {
super.processOpts();
if (additionalProperties.containsKey(CodegenConstants.PACKAGE_VERSION)) {
setPackageVersion((String) additionalProperties.get(CodegenConstants.PACKAGE_VERSION));
} else {
additionalProperties.put(CodegenConstants.PACKAGE_VERSION, packageVersion);
}
if (additionalProperties.containsKey(CodegenConstants.SOURCE_FOLDER)){
setSourceFolder((String) additionalProperties.get(CodegenConstants.SOURCE_FOLDER));
}
else
{
additionalProperties.put(CodegenConstants.SOURCE_FOLDER, this.sourceFolder);
}
if (additionalProperties.containsKey(CodegenConstants.PACKAGE_NAME)) {
setPackageName((String) additionalProperties.get(CodegenConstants.PACKAGE_NAME));
apiPackage = packageName + ".Api";
modelPackage = packageName + ".Model";
clientPackage = packageName + ".Client";
} else {
additionalProperties.put(CodegenConstants.PACKAGE_NAME, packageName);
}
// Use DateTimeOffset
if (additionalProperties.containsKey(CodegenConstants.USE_DATETIME_OFFSET))
{
useDateTimeOffset(Boolean.valueOf(additionalProperties.get(CodegenConstants.USE_DATETIME_OFFSET).toString()));
}
additionalProperties.put(CodegenConstants.USE_DATETIME_OFFSET, useDateTimeOffsetFlag);
additionalProperties.put("clientPackage", clientPackage);
@@ -185,14 +111,12 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig
additionalProperties.put("packageCompany", packageCompany);
additionalProperties.put("packageCopyright", packageCopyright);
if (additionalProperties.containsKey(CodegenConstants.OPTIONAL_PROJECT_FILE))
{
if (additionalProperties.containsKey(CodegenConstants.OPTIONAL_PROJECT_FILE)) {
setOptionalProjectFileFlag(Boolean.valueOf(
additionalProperties.get(CodegenConstants.OPTIONAL_PROJECT_FILE).toString()));
}
if (additionalProperties.containsKey(CodegenConstants.OPTIONAL_PROJECT_GUID))
{
if (additionalProperties.containsKey(CodegenConstants.OPTIONAL_PROJECT_GUID)) {
setPackageGuid((String) additionalProperties.get(CodegenConstants.OPTIONAL_PROJECT_GUID));
}
additionalProperties.put("packageGuid", packageGuid);
@@ -208,15 +132,6 @@ 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);
@@ -224,7 +139,7 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig
//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)
for (int i = 0; i < packageDepth; i = i + 1)
binRelativePath += "..\\";
binRelativePath += "bin\\";
additionalProperties.put("binRelativePath", binRelativePath);
@@ -253,6 +168,33 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig
}
}
@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 CodegenType getTag() {
return CodegenType.CLIENT;
@@ -268,177 +210,6 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig
return "Generates a CSharp client library.";
}
@Override
public String escapeReservedWord(String name) {
return "_" + name;
}
@Override
public String apiTestFileFolder() {
return outputFolder + ".Test";
}
@Override
public String modelTestFileFolder() {
return outputFolder + ".Test";
}
@Override
public String apiFileFolder() {
return outputFolder + File.separator + sourceFolder + File.separator + apiPackage().replace('.', File.separatorChar);
}
@Override
public String modelFileFolder() {
return outputFolder + File.separator + sourceFolder + File.separator + modelPackage().replace('.', File.separatorChar);
}
@Override
public String toVarName(String name) {
// sanitize 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_]*$")) {
return name;
}
// camelize the variable name
// pet_id => PetId
name = camelize(name);
// for reserved word or word starting with number, append _
if (reservedWords.contains(name) || name.matches("^\\d.*")) {
name = escapeReservedWord(name);
}
return name;
}
@Override
public String toParamName(String name) {
// 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) the variable name
// pet_id => petId
name = camelize(name, true);
// for reserved word or word starting with number, append _
if (reservedWords.contains(name) || name.matches("^\\d.*")) {
name = escapeReservedWord(name);
}
return name;
}
@Override
public String toModelName(String name) {
name = sanitizeName(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 toApiTestFilename(String name) {
return toApiName(name) + "Tests";
}
@Override
public String toModelTestFilename(String name) {
return toModelName(name) + "Tests";
}
@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) {
if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">";
} else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
return getSwaggerType(p) + "<string, " + getTypeDeclaration(inner) + ">";
}
return super.getTypeDeclaration(p);
}
@Override
public String getSwaggerType(Property p) {
String swaggerType = super.getSwaggerType(p);
String type = null;
if (typeMapping.containsKey(swaggerType.toLowerCase())) {
type = typeMapping.get(swaggerType.toLowerCase());
if (languageSpecificPrimitives.contains(type)) {
return type;
}
} else {
type = swaggerType;
}
return toModelName(type);
}
@Override
public String toOperationId(String operationId) {
// 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
if (reservedWords.contains(operationId)) {
throw new RuntimeException(operationId + " (reserved word) cannot be used as method name");
}
return camelize(sanitizeName(operationId));
}
public void setOptionalAssemblyInfoFlag(boolean flag) {
this.optionalAssemblyInfoFlag = flag;
}
@@ -447,158 +218,8 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig
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)
typeMapping.put("datetime", "DateTimeOffset?");
else
typeMapping.put("datetime", "DateTime?");
}
public void setPackageGuid(String packageGuid) {
this.packageGuid = packageGuid;
}
public void setPackageName(String packageName) {
this.packageName = packageName;
}
public void setPackageVersion(String packageVersion) {
this.packageVersion = packageVersion;
}
public void setSourceFolder(String sourceFolder) {
this.sourceFolder = sourceFolder;
}
@Override
public Map<String, Object> postProcessModels(Map<String, Object> objs) {
List<Object> models = (List<Object>) objs.get("models");
for (Object _mo : models) {
Map<String, Object> mo = (Map<String, Object>) _mo;
CodegenModel cm = (CodegenModel) mo.get("model");
for (CodegenProperty var : cm.vars) {
// check to see if model name is same as the property name
// which will result in compilation error
// if found, prepend with _ to workaround the limitation
if (var.name.equals(cm.name)) {
var.name = "_" + var.name;
}
}
}
return objs;
}
/**
* Return the default value of the property
*
* @param p Swagger property object
* @return string presentation of the default value of the property
*/
@Override
public String toDefaultValue(Property p) {
if (p instanceof StringProperty) {
StringProperty dp = (StringProperty) p;
if (dp.getDefault() != null) {
return "\"" + dp.getDefault().toString() + "\"";
}
} else if (p instanceof BooleanProperty) {
BooleanProperty dp = (BooleanProperty) p;
if (dp.getDefault() != null) {
return dp.getDefault().toString();
}
} else if (p instanceof DateProperty) {
// TODO
} else if (p instanceof DateTimeProperty) {
// TODO
} else if (p instanceof DoubleProperty) {
DoubleProperty dp = (DoubleProperty) p;
if (dp.getDefault() != null) {
return dp.getDefault().toString();
}
} else if (p instanceof FloatProperty) {
FloatProperty dp = (FloatProperty) p;
if (dp.getDefault() != null) {
return dp.getDefault().toString();
}
} else if (p instanceof IntegerProperty) {
IntegerProperty dp = (IntegerProperty) p;
if (dp.getDefault() != null) {
return dp.getDefault().toString();
}
} else if (p instanceof LongProperty) {
LongProperty dp = (LongProperty) p;
if (dp.getDefault() != null) {
return dp.getDefault().toString();
}
}
return null;
}
/**
* Return the example value of the property
*
* @param p Swagger property object
* @return string presentation of the example value of the property
*/
@Override
public String toExampleValue(Property p) {
if (p instanceof StringProperty) {
StringProperty dp = (StringProperty) p;
if (dp.getExample() != null) {
return "\"" + dp.getExample().toString() + "\"";
}
} else if (p instanceof BooleanProperty) {
BooleanProperty dp = (BooleanProperty) p;
if (dp.getExample() != null) {
return dp.getExample().toString();
}
} else if (p instanceof DateProperty) {
// TODO
} else if (p instanceof DateTimeProperty) {
// TODO
} else if (p instanceof DoubleProperty) {
DoubleProperty dp = (DoubleProperty) p;
if (dp.getExample() != null) {
return dp.getExample().toString();
}
} else if (p instanceof FloatProperty) {
FloatProperty dp = (FloatProperty) p;
if (dp.getExample() != null) {
return dp.getExample().toString();
}
} else if (p instanceof IntegerProperty) {
IntegerProperty dp = (IntegerProperty) p;
if (dp.getExample() != null) {
return dp.getExample().toString();
}
} else if (p instanceof LongProperty) {
LongProperty dp = (LongProperty) p;
if (dp.getExample() != null) {
return dp.getExample().toString();
}
}
return null;
}
}

View File

@@ -1,45 +1,20 @@
package io.swagger.codegen.languages;
import com.google.common.base.Strings;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import io.swagger.codegen.CliOption;
import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenConstants;
import io.swagger.codegen.CodegenModel;
import io.swagger.codegen.CodegenOperation;
import io.swagger.codegen.CodegenParameter;
import io.swagger.codegen.CodegenProperty;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile;
import io.swagger.codegen.*;
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.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;
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.*;
public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
@SuppressWarnings("hiding")
@@ -258,13 +233,13 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
importMapping.put("StringUtil", invokerPackage + ".StringUtil");
final String invokerFolder = (sourceFolder + '/' + invokerPackage).replace(".", "/");
supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml"));
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
supportingFiles.add(new SupportingFile("build.gradle.mustache", "", "build.gradle"));
supportingFiles.add(new SupportingFile("settings.gradle.mustache", "", "settings.gradle"));
supportingFiles.add(new SupportingFile("gradle.properties.mustache", "", "gradle.properties"));
supportingFiles.add(new SupportingFile("manifest.mustache", projectFolder, "AndroidManifest.xml"));
supportingFiles.add(new SupportingFile("ApiClient.mustache", invokerFolder, "ApiClient.java"));
writeOptional(new SupportingFile("pom.mustache", "", "pom.xml"));
writeOptional(new SupportingFile("README.mustache", "", "README.md"));
writeOptional(new SupportingFile("build.gradle.mustache", "", "build.gradle"));
writeOptional(new SupportingFile("settings.gradle.mustache", "", "settings.gradle"));
writeOptional(new SupportingFile("gradle.properties.mustache", "", "gradle.properties"));
writeOptional(new SupportingFile("manifest.mustache", projectFolder, "AndroidManifest.xml"));
writeOptional(new SupportingFile("ApiClient.mustache", invokerFolder, "ApiClient.java"));
supportingFiles.add(new SupportingFile("StringUtil.mustache", invokerFolder, "StringUtil.java"));
final String authFolder = (sourceFolder + '/' + invokerPackage + ".auth").replace(".", "/");

View File

@@ -8,12 +8,11 @@ import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
import io.swagger.util.Yaml;
import java.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
public class JavaInflectorServerCodegen extends JavaClientCodegen implements CodegenConfig {
private static final Logger LOGGER = LoggerFactory.getLogger(JavaInflectorServerCodegen.class);
@@ -72,10 +71,10 @@ public class JavaInflectorServerCodegen extends JavaClientCodegen implements Cod
super.processOpts();
supportingFiles.clear();
supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml"));
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
supportingFiles.add(new SupportingFile("web.mustache", "src/main/webapp/WEB-INF", "web.xml"));
supportingFiles.add(new SupportingFile("inflector.mustache", "", "inflector.yaml"));
writeOptional(new SupportingFile("pom.mustache", "", "pom.xml"));
writeOptional(new SupportingFile("README.mustache", "", "README.md"));
writeOptional(new SupportingFile("web.mustache", "src/main/webapp/WEB-INF", "web.xml"));
writeOptional(new SupportingFile("inflector.mustache", "", "inflector.yaml"));
supportingFiles.add(new SupportingFile("swagger.mustache",
"src/main/swagger",
"swagger.yaml")

View File

@@ -63,8 +63,15 @@ public class JavaJerseyServerCodegen extends AbstractJavaJAXRSServerCodegen
}
@Override
public void processOpts()
{
public void postProcessModelProperty(CodegenModel model, CodegenProperty property) {
super.postProcessModelProperty(model, property);
if("null".equals(property.example)) {
property.example = null;
}
}
@Override
public void processOpts() {
super.processOpts();
if ( additionalProperties.containsKey(CodegenConstants.IMPL_FOLDER) ) {
@@ -72,13 +79,13 @@ public class JavaJerseyServerCodegen extends AbstractJavaJAXRSServerCodegen
}
supportingFiles.clear();
supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml"));
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
writeOptional(new SupportingFile("pom.mustache", "", "pom.xml"));
writeOptional(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"));
writeOptional(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") ) {

View File

@@ -89,10 +89,10 @@ public class JavaResteasyServerCodegen extends JavaClientCodegen implements Code
}
supportingFiles.clear();
supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml"));
supportingFiles.add(new SupportingFile("gradle.mustache", "", "build.gradle"));
supportingFiles.add(new SupportingFile("settingsGradle.mustache", "", "settings.gradle"));
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
writeOptional(new SupportingFile("pom.mustache", "", "pom.xml"));
writeOptional(new SupportingFile("gradle.mustache", "", "build.gradle"));
writeOptional(new SupportingFile("settingsGradle.mustache", "", "settings.gradle"));
writeOptional(new SupportingFile("README.mustache", "", "README.md"));
supportingFiles.add(new SupportingFile("ApiException.mustache",
(sourceFolder + '/' + apiPackage).replace(".", "/"), "ApiException.java"));
supportingFiles.add(new SupportingFile("ApiOriginFilter.mustache",
@@ -101,11 +101,11 @@ public class JavaResteasyServerCodegen extends JavaClientCodegen implements Code
(sourceFolder + '/' + apiPackage).replace(".", "/"), "ApiResponseMessage.java"));
supportingFiles.add(new SupportingFile("NotFoundException.mustache",
(sourceFolder + '/' + apiPackage).replace(".", "/"), "NotFoundException.java"));
supportingFiles.add(new SupportingFile("web.mustache",
writeOptional(new SupportingFile("web.mustache",
("src/main/webapp/WEB-INF"), "web.xml"));
supportingFiles.add(new SupportingFile("jboss-web.mustache",
writeOptional(new SupportingFile("jboss-web.mustache",
("src/main/webapp/WEB-INF"), "jboss-web.xml"));
supportingFiles.add(new SupportingFile("RestApplication.mustache",
writeOptional(new SupportingFile("RestApplication.mustache",
(sourceFolder + '/' + invokerPackage).replace(".", "/"), "RestApplication.java"));
supportingFiles.add(new SupportingFile("StringUtil.mustache",
(sourceFolder + '/' + invokerPackage).replace(".", "/"), "StringUtil.java"));

View File

@@ -9,14 +9,22 @@ import io.swagger.codegen.CodegenModel;
import io.swagger.codegen.CodegenOperation;
import io.swagger.codegen.CodegenProperty;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile;
import io.swagger.models.*;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.models.Info;
import io.swagger.models.License;
import io.swagger.models.Model;
import io.swagger.models.Operation;
import io.swagger.models.Swagger;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
import io.swagger.models.properties.RefProperty;
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;
@@ -26,10 +34,6 @@ import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
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);
@@ -39,6 +43,8 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
private static final String PROJECT_DESCRIPTION = "projectDescription";
private static final String PROJECT_VERSION = "projectVersion";
private static final String PROJECT_LICENSE_NAME = "projectLicenseName";
private static final String USE_PROMISES = "usePromises";
private static final String OMIT_MODEL_METHODS = "omitModelMethods";
protected String projectName;
protected String moduleName;
@@ -47,6 +53,8 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
protected String sourceFolder = "src";
protected String localVariablePrefix = "";
protected boolean usePromises = false;
protected boolean omitModelMethods = false;
public JavascriptClientCodegen() {
super();
@@ -96,6 +104,12 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
"version of the project (Default: using info.version or \"1.0.0\")"));
cliOptions.add(new CliOption(PROJECT_LICENSE_NAME,
"name of the license the project uses (Default: using info.license.name)"));
cliOptions.add(new CliOption(USE_PROMISES,
"use Promises as return values from the client API, instead of superagent callbacks")
.defaultValue(Boolean.FALSE.toString()));
cliOptions.add(new CliOption(OMIT_MODEL_METHODS,
"omits generation of getters and setters for model classes")
.defaultValue(Boolean.FALSE.toString()));
}
@Override
@@ -133,6 +147,7 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
typeMapping.put("double", "Number");
typeMapping.put("number", "Number");
typeMapping.put("DateTime", "Date");
typeMapping.put("Date", "Date");
// binary not supported in JavaScript client right now, using String as a workaround
typeMapping.put("binary", "String");
@@ -161,6 +176,12 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
if (additionalProperties.containsKey(CodegenConstants.SOURCE_FOLDER)) {
sourceFolder = (String) additionalProperties.get(CodegenConstants.SOURCE_FOLDER);
}
if (additionalProperties.containsKey(USE_PROMISES)) {
usePromises = Boolean.parseBoolean((String)additionalProperties.get(USE_PROMISES));
}
if (additionalProperties.containsKey(OMIT_MODEL_METHODS)) {
omitModelMethods = Boolean.parseBoolean((String)additionalProperties.get(OMIT_MODEL_METHODS));
}
if (swagger.getInfo() != null) {
Info info = swagger.getInfo();
@@ -204,6 +225,8 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
additionalProperties.put(PROJECT_VERSION, projectVersion);
additionalProperties.put(CodegenConstants.LOCAL_VARIABLE_PREFIX, localVariablePrefix);
additionalProperties.put(CodegenConstants.SOURCE_FOLDER, sourceFolder);
additionalProperties.put(USE_PROMISES, usePromises);
additionalProperties.put(OMIT_MODEL_METHODS, omitModelMethods);
supportingFiles.add(new SupportingFile("package.mustache", "", "package.json"));
supportingFiles.add(new SupportingFile("index.mustache", sourceFolder, "index.js"));
@@ -316,10 +339,10 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
@Override
public String toDefaultValueWithParam(String name, Property p) {
if (p instanceof RefProperty) {
return ".constructFromObject(data['" + name + "']);";
} else {
String type = normalizeType(getTypeDeclaration(p));
if (p instanceof RefProperty) {
return " = " + type + ".constructFromObject(data['" + name + "']);";
} else {
return " = ApiClient.convertToType(data['" + name + "'], " + type + ");";
}
}
@@ -358,7 +381,7 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
// 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");
operationId = escapeReservedWord(operationId);
}
return camelize(sanitizeName(operationId), true);

View File

@@ -0,0 +1,216 @@
package io.swagger.codegen.languages;
import io.swagger.codegen.CodegenModel;
import io.swagger.codegen.*;
import io.swagger.models.properties.*;
import java.util.TreeSet;
import java.util.*;
import java.io.File;
public class JavascriptClosureAngularClientCodegen extends DefaultCodegen implements CodegenConfig {
public JavascriptClosureAngularClientCodegen() {
super();
supportsInheritance = false;
reservedWords = new HashSet<String>(Arrays.asList("abstract",
"continue", "for", "new", "switch", "assert", "default", "if",
"package", "synchronized", "do", "goto", "private",
"this", "break", "double", "implements", "protected", "throw",
"byte", "else", "import", "public", "throws", "case", "enum",
"instanceof", "return", "transient", "catch", "extends", "int",
"short", "try", "char", "final", "interface", "static", "void",
"class", "finally", "const", "super", "while"));
languageSpecificPrimitives = new HashSet<String>(Arrays.asList(
"string",
"boolean",
"number",
"Object",
"Blob",
"Date"));
instantiationTypes.put("array", "Array");
typeMapping = new HashMap<String, String>();
typeMapping.put("Array", "Array");
typeMapping.put("array", "Array");
typeMapping.put("List", "Array");
typeMapping.put("boolean", "boolean");
typeMapping.put("string", "string");
typeMapping.put("int", "number");
typeMapping.put("float", "number");
typeMapping.put("number", "number");
typeMapping.put("long", "number");
typeMapping.put("short", "number");
typeMapping.put("char", "string");
typeMapping.put("double", "number");
typeMapping.put("object", "Object");
typeMapping.put("Object", "Object");
typeMapping.put("File", "Blob");
typeMapping.put("file", "Blob");
typeMapping.put("integer", "number");
typeMapping.put("Map", "Object");
typeMapping.put("map", "Object");
typeMapping.put("DateTime", "Date");
importMapping = new HashMap<String, String>();
defaultIncludes = new HashSet<String>(Arrays.asList(
"Object",
"Array",
"Blob"
));
typeMapping.put("binary", "string");
outputFolder = "generated-code/javascript-closure-angular";
modelTemplateFiles.put("model.mustache", ".js");
apiTemplateFiles.put("api.mustache", ".js");
embeddedTemplateDir = templateDir = "Javascript-Closure-Angular";
apiPackage = "API.Client";
modelPackage = "API.Client";
}
@Override
public String getName() {
return "javascript-closure-angular";
}
@Override
public String getHelp() {
return "Generates a Javascript AngularJS client library annotated with Google Closure Compiler annotations" +
"(https://developers.google.com/closure/compiler/docs/js-for-compiler?hl=en)";
}
@Override
public CodegenType getTag() {
return CodegenType.CLIENT;
}
@Override
public String escapeReservedWord(String name) {
return "_" + name;
}
@Override
public String apiFileFolder() {
return outputFolder + "/" + apiPackage().replace('.', File.separatorChar);
}
public String modelFileFolder() {
return outputFolder + "/" + modelPackage().replace('.', File.separatorChar);
}
@Override
public String toVarName(String name) {
// replace - with _ e.g. created-at => created_at
name = name.replaceAll("-", "_");
// if it's all uppper case, do nothing
if (name.matches("^[A-Z_]*$"))
return name;
// camelize the variable name
// pet_id => PetId
name = camelize(name, true);
// for reserved word or word starting with number, append _
if (reservedWords.contains(name) || name.matches("^\\d.*"))
name = escapeReservedWord(name);
return name;
}
@Override
public String toParamName(String name) {
// should be the same as variable name
return toVarName(name);
}
@Override
public String toModelName(String name) {
// model name cannot use reserved keyword, e.g. return
if (reservedWords.contains(name))
throw new RuntimeException(name
+ " (reserved word) cannot be used as a model name");
// camelize the model name
// phone_number => PhoneNumber
return camelize(name);
}
@Override
public String toModelFilename(String name) {
// should be the same as the model name
return toModelName(name);
}
@Override
public String getTypeDeclaration(Property p) {
if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
return getSwaggerType(p) + "<!" + getTypeDeclaration(inner) + ">";
} else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
return "Object<!string, "+ getTypeDeclaration(inner) + ">";
} else if (p instanceof FileProperty) {
return "Object";
}
String type = super.getTypeDeclaration(p);
if (type.equals("boolean") ||
type.equals("Date") ||
type.equals("number") ||
type.equals("string")) {
return type;
}
return apiPackage + "." + type;
}
@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 Map<String, Object> postProcessModels(Map<String, Object> objs) {
List<Object> models = (List<Object>) objs.get("models");
for (Object _mo : models) {
Map<String, Object> mo = (Map<String, Object>) _mo;
CodegenModel cm = (CodegenModel) mo.get("model");
cm.imports = new TreeSet(cm.imports);
for (CodegenProperty var : cm.vars) {
// handle default value for enum, e.g. available => StatusEnum.available
if (var.isEnum && var.defaultValue != null && !"null".equals(var.defaultValue)) {
var.defaultValue = var.datatypeWithEnum + "." + var.defaultValue;
}
}
}
return objs;
}
@Override
public Map<String, Object> postProcessOperations(Map<String, Object> objs) {
if (objs.get("imports") instanceof List) {
List<Map<String, String>> imports = (ArrayList<Map<String, String>>)objs.get("imports");
Collections.sort(imports, new Comparator<Map<String, String>>() {
public int compare(Map<String, String> o1, Map<String, String> o2) {
return o1.get("import").compareTo(o2.get("import"));
}
});
objs.put("imports", imports);
}
return objs;
}
}

View File

@@ -89,15 +89,15 @@ public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig
"api",
"swagger.yaml")
);
supportingFiles.add(new SupportingFile("index.mustache",
writeOptional(new SupportingFile("index.mustache",
"",
"index.js")
);
supportingFiles.add(new SupportingFile("package.mustache",
writeOptional(new SupportingFile("package.mustache",
"",
"package.json")
);
supportingFiles.add(new SupportingFile("README.mustache",
writeOptional(new SupportingFile("README.mustache",
"",
"README.md")
);

View File

@@ -84,6 +84,9 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
typeMapping.put("List", "NSArray");
typeMapping.put("object", "NSObject");
typeMapping.put("file", "NSURL");
//TODO binary should be mapped to byte array
// mapped to String as a workaround
typeMapping.put("binary", "NSString");
// ref: http://www.tutorialspoint.com/objective_c/objective_c_basic_syntax.htm

View File

@@ -30,6 +30,8 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig {
outputFolder = "generated-code" + File.separatorChar + "perl";
modelTemplateFiles.put("object.mustache", ".pm");
apiTemplateFiles.put("api.mustache", ".pm");
modelTestTemplateFiles.put("object_test.mustache", ".t");
apiTestTemplateFiles.put("api_test.mustache", ".t");
embeddedTemplateDir = templateDir = "perl";
@@ -142,6 +144,17 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig {
return (outputFolder + "/lib/" + modulePathPart + modelPackage()).replace('/', File.separatorChar);
}
@Override
public String apiTestFileFolder() {
return (outputFolder + "/t").replace('/', File.separatorChar);
}
@Override
public String modelTestFileFolder() {
return (outputFolder + "/t").replace('/', File.separatorChar);
}
@Override
public String getTypeDeclaration(Property p) {
if (p instanceof ArrayProperty) {
@@ -218,6 +231,16 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig {
return toModelName(name);
}
@Override
public String toModelTestFilename(String name) {
return toModelFilename(name) + "Test";
}
@Override
public String toApiTestFilename(String name) {
return toApiFilename(name) + "Test";
}
@Override
public String toApiFilename(String name) {
// replace - with _ e.g. created-at => created_at

View File

@@ -77,7 +77,8 @@ public class SwiftCodegen extends DefaultCodegen implements CodegenConfig {
"Bool",
"Void",
"String",
"Character")
"Character",
"AnyObject")
);
defaultIncludes = new HashSet<String>(
Arrays.asList(
@@ -118,7 +119,7 @@ public class SwiftCodegen extends DefaultCodegen implements CodegenConfig {
typeMapping.put("float", "Float");
typeMapping.put("number", "Double");
typeMapping.put("double", "Double");
typeMapping.put("object", "String");
typeMapping.put("object", "AnyObject");
typeMapping.put("file", "NSURL");
//TODO binary should be mapped to byte array
// mapped to String as a workaround
@@ -188,7 +189,7 @@ public class SwiftCodegen extends DefaultCodegen implements CodegenConfig {
@Override
public String escapeReservedWord(String name) {
return "Swagger" + name; // add an underscore to the name
return "_" + name; // add an underscore to the name
}
@Override
@@ -263,7 +264,11 @@ public class SwiftCodegen extends DefaultCodegen implements CodegenConfig {
codegenProperty.allowableValues.put("values", swiftEnums);
codegenProperty.datatypeWithEnum =
StringUtils.left(codegenProperty.datatypeWithEnum, codegenProperty.datatypeWithEnum.length() - "Enum".length());
if (reservedWords.contains(codegenProperty.datatypeWithEnum)) {
// Ensure that the enum type doesn't match a reserved word or
// the variable name doesn't match the generated enum type or the
// Swift compiler will generate an error
if (reservedWords.contains(codegenProperty.datatypeWithEnum) ||
name.equals(codegenProperty.datatypeWithEnum)) {
codegenProperty.datatypeWithEnum = escapeReservedWord(codegenProperty.datatypeWithEnum);
}
}
@@ -288,6 +293,21 @@ public class SwiftCodegen extends DefaultCodegen implements CodegenConfig {
return initialCaps(name) + "API";
}
@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
if (reservedWords.contains(operationId)) {
throw new RuntimeException(operationId + " (reserved word) cannot be used as method name");
}
return camelize(sanitizeName(operationId), true);
}
@Override
public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map<String, Model> definitions, Swagger swagger) {
path = normalizePath(path); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.

View File

@@ -15,6 +15,12 @@ public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCode
return "Generates a TypeScript AngularJS client library.";
}
@Override
public void processOpts() {
super.processOpts();
supportingFiles.add(new SupportingFile("api.d.mustache", apiPackage().replace('.', File.separatorChar), "api.d.ts"));
}
public TypeScriptAngularClientCodegen() {
super();
outputFolder = "generated-code/typescript-angular";
@@ -23,6 +29,5 @@ public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCode
embeddedTemplateDir = templateDir = "TypeScript-Angular";
apiPackage = "API.Client";
modelPackage = "API.Client";
supportingFiles.add(new SupportingFile("api.d.mustache", apiPackage().replace('.', File.separatorChar), "api.d.ts"));
}
}

View File

@@ -14,11 +14,16 @@ public class TypeScriptNodeClientCodegen extends AbstractTypeScriptClientCodegen
return "Generates a TypeScript nodejs client library.";
}
@Override
public void processOpts() {
super.processOpts();
supportingFiles.add(new SupportingFile("api.mustache", null, "api.ts"));
}
public TypeScriptNodeClientCodegen() {
super();
outputFolder = "generated-code/typescript-node";
embeddedTemplateDir = templateDir = "TypeScript-node";
supportingFiles.add(new SupportingFile("api.mustache", null, "api.ts"));
}
}

View File

@@ -103,7 +103,7 @@
<stringProp name="HTTPSampler.response_timeout"></stringProp>
<stringProp name="HTTPSampler.protocol"></stringProp>
<stringProp name="HTTPSampler.contentEncoding"></stringProp>
<stringProp name="HTTPSampler.path">{{vendorExtensions.x-path}}</stringProp>
<stringProp name="HTTPSampler.path">{{basePathWithoutHost}}{{vendorExtensions.x-path}}</stringProp>
<stringProp name="HTTPSampler.method">{{httpMethod}}</stringProp>
<boolProp name="HTTPSampler.follow_redirects">true</boolProp>
<boolProp name="HTTPSampler.auto_redirects">false</boolProp>

View File

@@ -517,7 +517,10 @@ public class ApiClient {
response = builder.type(contentType).put(ClientResponse.class, serialize(body, contentType, formParams));
} else if ("DELETE".equals(method)) {
response = builder.type(contentType).delete(ClientResponse.class, serialize(body, contentType, formParams));
} else {
} else if ("PATCH".equals(method)) {
response = builder.type(contentType).header("X-HTTP-Method-Override", "PATCH").post(ClientResponse.class, serialize(body, contentType, formParams));
}
else {
throw new ApiException(500, "unknown method type " + method);
}
return response;

View File

@@ -20,7 +20,7 @@ mvn deploy
Refer to the [official documentation](https://maven.apache.org/plugins/maven-deploy-plugin/usage.html) for more information.
After the client libarary is installed/deployed, you can use it in your Maven project by adding the following to your *pom.xml*:
After the client library is installed/deployed, you can use it in your Maven project by adding the following to your *pom.xml*:
```xml
<dependency>

View File

@@ -95,8 +95,8 @@ if(hasProperty('target') && target == 'android') {
dependencies {
compile 'io.swagger:swagger-annotations:1.5.0'
compile 'com.squareup.okhttp:okhttp:2.4.0'
compile 'com.squareup.okhttp:okhttp:2.7.2'
compile 'com.squareup.okhttp:logging-interceptor:2.7.2'
compile 'com.google.code.gson:gson:2.3.1'
compile 'com.brsanthu:migbase64:2.2'
testCompile 'junit:junit:4.8.1'
}

View File

@@ -10,9 +10,9 @@ lazy val root = (project in file(".")).
resolvers += Resolver.mavenLocal,
libraryDependencies ++= Seq(
"io.swagger" % "swagger-annotations" % "1.5.0",
"com.squareup.okhttp" % "okhttp" % "2.4.0",
"com.squareup.okhttp" % "okhttp" % "2.7.2",
"com.squareup.okhttp" % "logging-interceptor" % "2.7.2",
"com.google.code.gson" % "gson" % "2.3.1",
"com.brsanthu" % "migbase64" % "2.2",
"junit" % "junit" % "4.8.1" % "test"
)
)

View File

@@ -104,6 +104,28 @@
<target>1.6</target>
</configuration>
</plugin>
<!-- For testing build.gradle -->
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.2.1</version>
<executions>
<execution>
<id>gradle-test</id>
<phase>integration-test</phase>
<goals>
<goal>exec</goal>
</goals>
<configuration>
<executable>gradle</executable>
<arguments>
<argument>check</argument>
</arguments>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<dependencies>

View File

@@ -14,8 +14,13 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#seriali
* minimum: {{minimum}}{{/minimum}}{{#maximum}}
* maximum: {{maximum}}{{/maximum}}
**/
public {{classname}} {{name}}({{{datatypeWithEnum}}} {{name}}) {
this.{{name}} = {{name}};
return this;
}
{{#vendorExtensions.extraAnnotation}}{{vendorExtensions.extraAnnotation}}{{/vendorExtensions.extraAnnotation}}
@ApiModelProperty({{#required}}required = {{required}}, {{/required}}value = "{{{description}}}")
@ApiModelProperty({{#example}}example = "{{example}}", {{/example}}{{#required}}required = {{required}}, {{/required}}value = "{{{description}}}")
@JsonProperty("{{baseName}}")
public {{{datatypeWithEnum}}} {{getter}}() {
return {{name}};

View File

@@ -14,8 +14,13 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#seriali
* minimum: {{minimum}}{{/minimum}}{{#maximum}}
* maximum: {{maximum}}{{/maximum}}
**/
public {{classname}} {{name}}({{{datatypeWithEnum}}} {{name}}) {
this.{{name}} = {{name}};
return this;
}
{{#vendorExtensions.extraAnnotation}}{{vendorExtensions.extraAnnotation}}{{/vendorExtensions.extraAnnotation}}
@ApiModelProperty({{#required}}required = {{required}}, {{/required}}value = "{{{description}}}")
@ApiModelProperty({{#example}}example = "{{example}}", {{/example}}{{#required}}required = {{required}}, {{/required}}value = "{{{description}}}")
@JsonProperty("{{baseName}}")
public {{{datatypeWithEnum}}} {{getter}}() {
return {{name}};

View File

@@ -24,7 +24,7 @@ import javax.ws.rs.core.SecurityContext;
public class {{classname}}ServiceImpl extends {{classname}}Service {
{{#operation}}
@Override
public Response {{nickname}}({{#allParams}}{{>serviceQueryParams}}{{>servicePathParams}}{{>serviceHeaderParams}}{{>serviceBodyParams}}{{>serviceFormParams}},{{/allParams}}SecurityContext securityContext)
public Response {{nickname}}({{#allParams}}{{>serviceQueryParams}}{{>servicePathParams}}{{>serviceHeaderParams}}{{>serviceBodyParams}}{{>serviceFormParams}}, {{/allParams}}SecurityContext securityContext)
throws NotFoundException {
// do some magic!
return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build();

View File

@@ -14,8 +14,13 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#seriali
* minimum: {{minimum}}{{/minimum}}{{#maximum}}
* maximum: {{maximum}}{{/maximum}}
**/
public {{classname}} {{name}}({{{datatypeWithEnum}}} {{name}}) {
this.{{name}} = {{name}};
return this;
}
{{#vendorExtensions.extraAnnotation}}{{vendorExtensions.extraAnnotation}}{{/vendorExtensions.extraAnnotation}}
@ApiModelProperty({{#required}}required = {{required}}, {{/required}}value = "{{{description}}}")
@ApiModelProperty({{#example}}example = "{{example}}", {{/example}}{{#required}}required = {{required}}, {{/required}}value = "{{{description}}}")
@JsonProperty("{{baseName}}")
public {{{datatypeWithEnum}}} {{getter}}() {
return {{name}};

View File

@@ -0,0 +1,124 @@
/**
* @fileoverview AUTOMATICALLY GENERATED service for {{package}}.{{classname}}.
* Do not edit this file by hand or your changes will be lost next time it is
* generated.{{#appDescription}}
*
* {{ appDescription }}{{/appDescription}}{{#version}}
* Version: {{version}}{{/version}}{{#appContact}}
* Contact: {{appContact}}{{/appContact}}
* Generated at: {{generatedDate}}
* Generated by: {{generatorClass}}
*/{{#licenseInfo}}
/**
* @license {{licenseInfo}}{{#licenseUrl}}
* {{licenseUrl}}{{/licenseUrl}}
*/
{{/licenseInfo}}
goog.provide('{{package}}.{{classname}}');
{{#imports}}
goog.require('{{import}}');
{{/imports}}
{{#operations}}
/**
{{#description}}
* {{&description}}
{{/description}}
* @constructor
* @param {!angular.$http} $http
* @param {!Object} $httpParamSerializer
* @param {!angular.$injector} $injector
* @struct
*/
{{package}}.{{classname}} = function($http, $httpParamSerializer, $injector) {
/** @private {!string} */
this.basePath_ = $injector.has('{{classname}}BasePath') ?
/** @type {!string} */ ($injector.get('{{classname}}BasePath')) :
'{{basePath}}';
/** @private {!Object<string, string>} */
this.defaultHeaders_ = $injector.has('{{classname}}DefaultHeaders') ?
/** @type {!Object<string, string>} */ (
$injector.get('{{classname}}DefaultHeaders')) :
{};
/** @private {!angular.$http} */
this.http_ = $http;
/** @private {!Object} */
this.httpParamSerializer_ = $injector.get('$httpParamSerializer');
}
{{package}}.{{classname}}.$inject = ['$http', '$httpParamSerializer', '$injector'];
{{#operation}}
/**
* {{summary}}
* {{notes}}{{#allParams}}
* @param {!{{{dataType}}}{{^required}}={{/required}}} {{^required}}opt_{{/required}}{{paramName}} {{description}}{{/allParams}}
* @param {!angular.$http.Config=} opt_extraHttpRequestParams Extra HTTP parameters to send.
* @return {!angular.$q.Promise{{#returnType}}<!{{{returnType}}}>{{/returnType}}}
*/
{{package}}.{{classname}}.prototype.{{nickname}} = function({{#allParams}}{{^required}}opt_{{/required}}{{paramName}}, {{/allParams}}opt_extraHttpRequestParams) {
/** @const {string} */
var path = this.basePath_ + '{{path}}'{{#pathParams}}
.replace('{' + '{{baseName}}' + '}', String({{^required}}opt_{{/required}}{{paramName}})){{/pathParams}};
/** @type {!Object} */
var queryParameters = {};
/** @type {!Object} */
var headerParams = angular.extend({}, this.defaultHeaders);
{{#hasFormParams}}
/** @type {!Object} */
var formParams = {};
{{/hasFormParams}}
{{#allParams}}
{{#required}}
// verify required parameter '{{^required}}opt_{{/required}}{{paramName}}' is set
if (!{{^required}}opt_{{/required}}{{paramName}}) {
throw new Error('Missing required parameter {{^required}}opt_{{/required}}{{paramName}} when calling {{nickname}}');
}
{{/required}}
{{/allParams}}
{{#queryParams}}
if ({{^required}}opt_{{/required}}{{paramName}} !== undefined) {
queryParameters['{{baseName}}'] = {{^required}}opt_{{/required}}{{paramName}};
}
{{/queryParams}}
{{#headerParams}}
headerParams['{{baseName}}'] = {{^required}}opt_{{/required}}{{paramName}};
{{/headerParams}}
{{#hasFormParams}}
headerParams['Content-Type'] = 'application/x-www-form-urlencoded';
{{/hasFormParams}}
{{#formParams}}
formParams['{{baseName}}'] = {{^required}}opt_{{/required}}{{paramName}};
{{/formParams}}
/** @type {!Object} */
var httpRequestParams = {
method: '{{httpMethod}}',
url: path,
json: {{#hasFormParams}}false{{/hasFormParams}}{{^hasFormParams}}true{{/hasFormParams}},
{{#bodyParam}}data: {{^required}}opt_{{/required}}{{paramName}},
{{/bodyParam}}
{{#hasFormParams}}data: this.httpParamSerializer_(formParams),
{{/hasFormParams}}
params: queryParameters,
headers: headerParams
};
if (opt_extraHttpRequestParams) {
httpRequestParams = angular.extend(httpRequestParams, opt_extraHttpRequestParams);
}
return this.http_(httpRequestParams);
}
{{/operation}}
{{/operations}}

View File

@@ -0,0 +1,40 @@
{{#models}}
{{#model}}
goog.provide('{{package}}.{{name}}');
{{/model}}
{{/models}}
{{#models}}
{{#model}}
/**
{{#description}}
* {{{description}}}
{{/description}}
* @record
*/
{{package}}.{{classname}} = function() {}
{{#vars}}
/**
{{#description}}
* {{{description}}}
{{/description}}
{{! Explicitly force types to be non-nullable using !. This is redundant but valid }}
* @type {!{{{datatype}}}}
* @export
*/
{{package}}.{{classname}}.prototype.{{name}};
{{/vars}}
{{#hasEnums}}
{{#vars}}
{{#isEnum}}
/** @enum {string} */
{{package}}.{{classname}}.{{datatypeWithEnum}} = { {{#allowableValues}}{{#values}}
{{.}}: '{{.}}',{{/values}}{{/allowableValues}}
}
{{/isEnum}}
{{/vars}}
{{/hasEnums}}
{{/model}}
{{/models}}

View File

@@ -215,7 +215,7 @@
ApiClient.prototype.callApi = function callApi(path, httpMethod, pathParams,
queryParams, headerParams, formParams, bodyParam, authNames, contentTypes,
accepts, returnType, callback) {
accepts, returnType{{^usePromises}}, callback{{/usePromises}}) {
var _this = this;
var url = this.buildUrl(path, pathParams);
var request = superagent(httpMethod, url);
@@ -259,6 +259,20 @@
request.accept(accept);
}
{{#usePromises}}
return new Promise( function(resolve,reject) {
request.end(function(error, response) {
if (error) {
reject(error);
}
else {
var data = _this.deserialize(response, returnType);
resolve(data);
}
});
});
{{/usePromises}}
{{^usePromises}}
request.end(function(error, response) {
if (callback) {
var data = null;
@@ -270,6 +284,7 @@
});
return request;
{{/usePromises}}
};
ApiClient.parseDate = function parseDate(str) {
@@ -292,8 +307,7 @@
default:
if (typeof type === 'function') {
// for model type like: User
var model = new type();
model.constructFromObject(data);
var model = type.constructFromObject(data);
return model;
} else if (Array.isArray(type)) {
// for array type like: ['String']

View File

@@ -25,10 +25,10 @@
* {{summary}}
* {{notes}}
{{#allParams}} * @param {{=<% %>=}}{<% dataType %>} <%={{ }}=%> {{paramName}} {{description}}
{{/allParams}} * @param {function} callback the callback function, accepting three arguments: error, data, response{{#returnType}}
{{/allParams}} {{^usePromises}}* @param {function} callback the callback function, accepting three arguments: error, data, response{{/usePromises}}{{#returnType}}
* data is of type: {{{returnType}}}{{/returnType}}
*/
self.{{nickname}} = function({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}{{#hasParams}}, {{/hasParams}}callback) {
self.{{nickname}} = function({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}{{^usePromises}}{{#hasParams}}, {{/hasParams}}callback{{/usePromises}}) {
var postBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}};
{{#allParams}}{{#required}}
// verify the required parameter '{{paramName}}' is set
@@ -59,7 +59,7 @@
return this.apiClient.callApi(
'<&path>', '<httpMethod>',
pathParams, queryParams, headerParams, formParams, postBody,
authNames, contentTypes, accepts, returnType, callback
authNames, contentTypes, accepts, returnType<^usePromises>, callback</usePromises>
);
<={{ }}=>
}

View File

@@ -1,19 +1,10 @@
//export module
if ( typeof define === "function" && define.amd ) {
define('{{datatypeWithEnum}}', [], function() {
return {{datatypeWithEnum}};
});
}
var {{datatypeWithEnum}} = function {{datatypeWithEnum}}() {
var self = this;
var {{datatypeWithEnum}} = {
{{#allowableValues}}{{#enumVars}}
/**
* @const
*/
self.{{name}} = "{{value}}"{{^-last}},
{{/-last}}{{#-last}};{{/-last}}{{/enumVars}}{{/allowableValues}}
{{name}}: "{{value}}"{{^-last}},
{{/-last}}{{/enumVars}}{{/allowableValues}}
};
}
{{classname}}.{{datatypeWithEnum}} = {{datatypeWithEnum}};

View File

@@ -14,16 +14,11 @@
}
}(this, function(module, ApiClient{{#imports}}, {{import}}{{/imports}}) {
'use strict';
{{#models}}{{#model}}
{{#vars}}{{#isEnum}}{{>enumClass}}{{/isEnum}}{{#items.isEnum}}{{#items}}
{{>enumClass}}{{/items}}*/{{/items.isEnum}}{{/vars}}
{{#description}}/**
* {{description}}
**/{{/description}}
var {{classname}} = function {{classname}}({{#mandatory}}{{this}}{{^-last}}, {{/-last}}{{/mandatory}}) { {{#parent}}/* extends {{{parent}}}*/{{/parent}}
var self = this;
{{#vars}}
/**{{#description}}
* {{{description}}}{{/description}}
@@ -32,19 +27,24 @@
* minimum: {{minimum}}{{/minimum}}{{#maximum}}
* maximum: {{maximum}}{{/maximum}}
**/
self['{{baseName}}'] = {{#required}}{{name}}{{/required}}{{^required}}{{{defaultValue}}}{{/required}};
this['{{baseName}}'] = {{#required}}{{name}}{{/required}}{{^required}}{{{defaultValue}}}{{/required}};
{{/vars}}
};
self.constructFromObject = function(data) {
{{classname}}.constructFromObject = function(data) {
if (!data) {
return this;
return null;
}
var _this = new {{classname}}();
{{#vars}}
self['{{baseName}}']{{{defaultValueWithParam}}}
if (data['{{baseName}}']) {
_this['{{baseName}}']{{{defaultValueWithParam}}}
}
{{/vars}}
return this;
return _this;
}
{{^omitModelMethods}}
{{#vars}}
/**{{#description}}
* get {{{description}}}{{/description}}{{#minimum}}
@@ -52,23 +52,26 @@
* maximum: {{maximum}}{{/maximum}}
* @return {{=<% %>=}}{<% datatypeWithEnum %>}<%={{ }}=%>
**/
self.{{getter}} = function() {
return self['{{baseName}}'];
{{classname}}.prototype.{{getter}} = function() {
return this['{{baseName}}'];
}
/**{{#description}}
* set {{{description}}}{{/description}}
* @param {{=<% %>=}}{<% datatypeWithEnum %>}<%={{ }}=%> {{name}}
**/
self.{{setter}} = function({{name}}) {
self['{{baseName}}'] = {{name}};
{{classname}}.prototype.{{setter}} = function({{name}}) {
this['{{baseName}}'] = {{name}};
}
{{/vars}}
{{/omitModelMethods}}
self.toJson = function() {
return JSON.stringify(self);
{{classname}}.prototype.toJson = function() {
return JSON.stringify(this);
}
};
{{#vars}}{{#isEnum}}{{>enumClass}}{{/isEnum}}{{#items.isEnum}}{{#items}}
{{>enumClass}}{{/items}}*/{{/items.isEnum}}{{/vars}}
if (module) {
module.{{classname}} = {{classname}};

View File

@@ -12,6 +12,7 @@ io.swagger.codegen.languages.JavaCXFServerCodegen
io.swagger.codegen.languages.JavaResteasyServerCodegen
io.swagger.codegen.languages.JavaInflectorServerCodegen
io.swagger.codegen.languages.JavascriptClientCodegen
io.swagger.codegen.languages.JavascriptClosureAngularClientCodegen
io.swagger.codegen.languages.JMeterCodegen
io.swagger.codegen.languages.NodeJSServerCodegen
io.swagger.codegen.languages.ObjcClientCodegen

View File

@@ -98,9 +98,9 @@ namespace {{packageName}}.Client
public ApiClient ApiClient;
/// <summary>
/// Set the ApiClient using Default or ApiClient instance
/// Set the ApiClient using Default or ApiClient instance.
/// </summary>
/// <param name="apiClient">An instance of ApiClient
/// <param name="apiClient">An instance of ApiClient.</param>
/// <returns></returns>
public void setApiClientUsingDefault (ApiClient apiClient = null)
{

View File

@@ -0,0 +1,46 @@
#
# Copyright 2016 SmartBear Software
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
#
# NOTE: This class is auto generated by the swagger code generator program.
# Do not edit the class manually.
#
use Test::More tests => 1; #TODO update number of test cases
use Test::Exception;
use lib 'lib';
use strict;
use warnings;
use_ok('{{moduleName}}::{{classname}}');
my $api = {{moduleName}}::{{classname}}->new();
isa_ok($api, '{{moduleName}}::{{classname}}');
{{#operations}}
{{#operation}}
#
# {{{nickname}}} test
#
{
{{#allParams}} my ${{paramName}} = undef; # replace NULL with a proper value
{{/allParams}}
my $result = $api->{{nickname}}({{#allParams}}{{paramName}} => ${{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}});
}
{{/operation}}
{{/operations}}
1;

View File

@@ -0,0 +1,18 @@
use Test::More tests => 2;
use Test::Exception;
use lib 'lib';
use strict;
use warnings;
{{#models}}
{{#model}}
use_ok('{{moduleName}}::Object::{{classname}}');
my $instance = {{moduleName}}::Object::{{classname}}->new();
isa_ok($instance, '{{moduleName}}::Object::{{classname}}');
{{/model}}
{{/models}}

View File

@@ -117,11 +117,11 @@ class {{classname}}(object):
header_params['{{baseName}}'] = params['{{paramName}}']
{{/headerParams}}
form_params = {}
form_params = []
files = {}
{{#formParams}}
if '{{paramName}}' in params:
{{#notFile}}form_params['{{baseName}}'] = params['{{paramName}}']{{/notFile}}{{#isFile}}files['{{baseName}}'] = params['{{paramName}}']{{/isFile}}
{{#notFile}}form_params.append(('{{baseName}}', params['{{paramName}}'])){{/notFile}}{{#isFile}}files['{{baseName}}'] = params['{{paramName}}']{{/isFile}}
{{/formParams}}
body_params = None

View File

@@ -386,22 +386,23 @@ class ApiClient(object):
:param files: File parameters.
:return: Form parameters with files.
"""
params = {}
params = []
if post_params:
params.update(post_params)
params = post_params
if files:
for k, v in iteritems(files):
if not v:
continue
with open(v, 'rb') as f:
file_names = v if type(v) is list else [v]
for n in file_names:
with open(n, 'rb') as f:
filename = os.path.basename(f.name)
filedata = f.read()
mimetype = mimetypes.\
guess_type(filename)[0] or 'application/octet-stream'
params[k] = tuple([filename, filedata, mimetype])
params.append(tuple([k, tuple([filename, filedata, mimetype])]))
return params

View File

@@ -97,6 +97,12 @@ class {{classname}}(object):
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value

View File

@@ -31,7 +31,7 @@
when :Float
value.to_f
when :BOOLEAN
if value =~ /^(true|t|yes|y|1)$/i
if value.to_s =~ /^(true|t|yes|y|1)$/i
true
else
false

View File

@@ -109,13 +109,19 @@ class Decoders {
}
// Decoder for NSDate
Decoders.addDecoder(clazz: NSDate.self) { (source: AnyObject) -> NSDate in
let sourceString = source as! String
if let sourceString = source as? String {
for formatter in formatters {
if let date = formatter.dateFromString(sourceString) {
return date
}
}
fatalError("formatter failed to parse \(sourceString)")
}
if let sourceInt = source as? Int {
// treat as a java date
return NSDate(timeIntervalSince1970: Double(sourceInt / 1000) )
}
fatalError("formatter failed to parse \(source)")
} {{#models}}{{#model}}
// Decoder for [{{{classname}}}]
@@ -126,7 +132,7 @@ class Decoders {
Decoders.addDecoder(clazz: {{{classname}}}.self) { (source: AnyObject) -> {{{classname}}} in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = {{classname}}(){{#vars}}{{#isEnum}}
instance.{{name}} = (sourceDictionary["{{name}}"] as? String).map { {{classname}}.{{datatypeWithEnum}}(rawValue: $0)! }{{#unwrapRequired}}{{#required}}!{{/required}}{{/unwrapRequired}} {{/isEnum}}{{^isEnum}}
instance.{{name}} = {{classname}}.{{datatypeWithEnum}}(rawValue: (sourceDictionary["{{name}}"] as? String) ?? ""){{#unwrapRequired}}{{#required}}!{{/required}}{{/unwrapRequired}} {{/isEnum}}{{^isEnum}}
instance.{{name}} = Decoders.decode{{^unwrapRequired}}Optional{{/unwrapRequired}}{{#unwrapRequired}}{{^required}}Optional{{/required}}{{/unwrapRequired}}(clazz: {{{baseType}}}.self, source: sourceDictionary["{{name}}"]{{#unwrapRequired}}{{#required}}!{{/required}}{{/unwrapRequired}}){{/isEnum}}{{/vars}}
return instance
}{{/model}}

View File

@@ -164,8 +164,8 @@ public class DefaultGeneratorTest {
changeContent(order);
//delete file
final File pom = new File(output, POM_FILE);
if (!pom.delete()) {
fail();
if (pom.exists() && !pom.delete()) {
fail("it doesn't delete");
}
//generate content third time with skipOverwrite flag, so changed file should not be rewritten
@@ -173,7 +173,8 @@ public class DefaultGeneratorTest {
codegenConfig.setSkipOverwrite(true);
new DefaultGenerator().opts(clientOptInput).generate();
assertEquals(FileUtils.readFileToString(order, StandardCharsets.UTF_8), TEST_SKIP_OVERWRITE);
assertTrue(pom.exists());
// Disabling this check, it's not valid with the DefaultCodegen.writeOptional(...) arg
// assertTrue(pom.exists());
}
@Test

View File

@@ -3,9 +3,7 @@ package io.swagger.codegen.aspnet5;
import io.swagger.codegen.AbstractOptionsTest;
import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.languages.AspNet5ServerCodegen;
import io.swagger.codegen.languages.CSharpClientCodegen;
import io.swagger.codegen.options.AspNet5ServerOptionsProvider;
import io.swagger.codegen.options.CSharpClientOptionsProvider;
import mockit.Expectations;
import mockit.Tested;

View File

@@ -32,7 +32,8 @@ public class JavaModelTest {
final Model model = new ModelImpl()
.description("a sample model")
.property("id", new LongProperty())
.property("name", new StringProperty())
.property("name", new StringProperty()
.example("Tony"))
.property("createdAt", new DateTimeProperty())
.required("id")
.required("name");
@@ -66,6 +67,7 @@ public class JavaModelTest {
Assert.assertEquals(property2.name, "name");
Assert.assertEquals(property2.defaultValue, "null");
Assert.assertEquals(property2.baseType, "String");
Assert.assertEquals(property2.example, "Tony");
Assert.assertTrue(property2.hasMore);
Assert.assertTrue(property2.required);
Assert.assertTrue(property2.isNotContainer);

View File

@@ -0,0 +1,30 @@
package io.swagger.codegen.options;
import io.swagger.codegen.CodegenConstants;
import com.google.common.collect.ImmutableMap;
import java.util.Map;
public class JavascriptClosureAnularClientOptionsProvider implements OptionsProvider {
public static final String SORT_PARAMS_VALUE = "false";
public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true";
@Override
public String getLanguage() {
return "javascript-closure-angular";
}
@Override
public Map<String, String> createOptions() {
ImmutableMap.Builder<String, String> builder = new ImmutableMap.Builder<String, String>();
return builder.put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE)
.put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE)
.build();
}
@Override
public boolean isServer() {
return false;
}
}

View File

@@ -0,0 +1,20 @@
package io.swagger.generator.util;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider;
import io.swagger.util.Json;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.ext.Provider;
@Provider
@Produces({MediaType.APPLICATION_JSON})
public class JacksonJsonProvider extends JacksonJaxbJsonProvider {
private static ObjectMapper commonMapper = Json.mapper();
public JacksonJsonProvider() {
super.setMapper(commonMapper);
}
}

View File

@@ -17,6 +17,7 @@
<param-name>jersey.config.server.provider.classnames</param-name>
<param-value>
io.swagger.online.ExceptionWriter,
io.swagger.generator.util.JacksonJsonProvider,
io.swagger.jersey.listing.ApiListingResourceJSON,
io.swagger.jersey.listing.JerseyApiDeclarationProvider,
io.swagger.jersey.listing.JerseyResourceListingProvider

View File

@@ -14,7 +14,8 @@
<script src='lib/jquery.wiggle.min.js' type='text/javascript'></script>
<script src='lib/jquery.ba-bbq.min.js' type='text/javascript'></script>
<script src='lib/handlebars-2.0.0.js' type='text/javascript'></script>
<script src='lib/underscore-min.js' type='text/javascript'></script>
<script src='lib/js-yaml.min.js' type='text/javascript'></script>
<script src='lib/lodash.min.js' type='text/javascript'></script>
<script src='lib/backbone-min.js' type='text/javascript'></script>
<script src='swagger-ui.js' type='text/javascript'></script>
<script src='lib/highlight.7.3.pack.js' type='text/javascript'></script>

23
pom.xml
View File

@@ -122,8 +122,8 @@
<artifactId>maven-compiler-plugin</artifactId>
<version>3.0</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
<plugin>
@@ -399,7 +399,19 @@
</property>
</activation>
<modules>
<module>samples/client/petstore/objc</module>
<module>samples/client/petstore/objc/SwaggerClientTests</module>
</modules>
</profile>
<profile>
<id>swift-client</id>
<activation>
<property>
<name>env</name>
<value>swift</value>
</property>
</activation>
<modules>
<module>samples/client/petstore/swift/SwaggerClientTests</module>
</modules>
</profile>
<profile>
@@ -459,9 +471,10 @@
<module>samples/client/petstore/javascript</module>
<module>samples/client/petstore/scala</module>
<module>samples/server/petstore/spring-mvc</module>
<!--module>samples/client/petstore/objc</module-->
<module>samples/client/petstore/ruby</module>
<module>samples/server/petstore/jaxrs</module>
<!--module>samples/client/petstore/objc/SwaggerClientTests</module-->
<!--module>samples/client/petstore/swift/SwaggerClientTests</module-->
</modules>
</profile>
</profiles>
@@ -533,7 +546,7 @@
</repository>
</repositories>
<properties>
<swagger-parser-version>1.0.17</swagger-parser-version>
<swagger-parser-version>1.0.18-SNAPSHOT</swagger-parser-version>
<scala-version>2.11.1</scala-version>
<felix-version>2.3.4</felix-version>
<swagger-core-version>1.5.7</swagger-core-version>

View File

@@ -98,9 +98,9 @@ namespace IO.Swagger.Client
public ApiClient ApiClient;
/// <summary>
/// Set the ApiClient using Default or ApiClient instance
/// Set the ApiClient using Default or ApiClient instance.
/// </summary>
/// <param name="apiClient">An instance of ApiClient
/// <param name="apiClient">An instance of ApiClient.</param>
/// <returns></returns>
public void setApiClientUsingDefault (ApiClient apiClient = null)
{

View File

@@ -0,0 +1,14 @@
#!/usr/bin/env bash
wget -nc https://nuget.org/nuget.exe;
mozroots --import --sync
# remove bin/Debug/SwaggerClientTest.dll
rm bin/Debug/SwaggerClientTest.dll 2> /dev/null
# install NUnit runners via NuGet
mono nuget.exe install NUnit.Runners -Version 2.6.4 -OutputDirectory testrunner
# build the solution and run the unit test
xbuild SwaggerClientTest.sln && \
mono ./testrunner/NUnit.Runners.2.6.4/tools/nunit-console.exe bin/Debug/SwaggerClientTest.dll

View File

@@ -0,0 +1,56 @@
<project>
<modelVersion>4.0.0</modelVersion>
<groupId>com.wordnik</groupId>
<artifactId>CsharpPetstoreClientTests</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<name>C# Swagger Petstore Client</name>
<build>
<plugins>
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.2.1</version>
<executions>
<!--execution>
<id>bundle-install</id>
<phase>pre-integration-test</phase>
<goals>
<goal>exec</goal>
</goals>
<configuration>
<executable>bundle</executable>
<arguments>
<argument>install</argument>
</arguments>
</configuration>
</execution-->
<execution>
<id>mono-test</id>
<phase>integration-test</phase>
<goals>
<goal>exec</goal>
</goals>
<configuration>
<executable>mono-nunit.sh</executable>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

View File

@@ -41,7 +41,7 @@ import io.swagger.client.auth.HttpBasicAuth;
import io.swagger.client.auth.ApiKeyAuth;
import io.swagger.client.auth.OAuth;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-15T19:19:23.415+08:00")
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-02-12T18:48:10.013-08:00")
public class ApiClient {
private Map<String, String> defaultHeaderMap = new HashMap<String, String>();
private String basePath = "http://petstore.swagger.io/v2";
@@ -83,8 +83,8 @@ public class ApiClient {
// Setup authentications (key: authentication name, value: authentication).
authentications = new HashMap<String, Authentication>();
authentications.put("petstore_auth", new OAuth());
authentications.put("api_key", new ApiKeyAuth("header", "api_key"));
authentications.put("petstore_auth", new OAuth());
// Prevent the authentications from being modified.
authentications = Collections.unmodifiableMap(authentications);
}
@@ -516,7 +516,10 @@ public class ApiClient {
response = builder.type(contentType).put(ClientResponse.class, serialize(body, contentType, formParams));
} else if ("DELETE".equals(method)) {
response = builder.type(contentType).delete(ClientResponse.class, serialize(body, contentType, formParams));
} else {
} else if ("PATCH".equals(method)) {
response = builder.type(contentType).header("X-HTTP-Method-Override", "PATCH").post(ClientResponse.class, serialize(body, contentType, formParams));
}
else {
throw new ApiException(500, "unknown method type " + method);
}
return response;

View File

@@ -3,7 +3,7 @@ package io.swagger.client;
import java.util.Map;
import java.util.List;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-05T14:39:16.440+08:00")
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-02-12T18:48:10.013-08:00")
public class ApiException extends Exception {
private int code = 0;
private Map<String, List<String>> responseHeaders = null;

View File

@@ -1,6 +1,6 @@
package io.swagger.client;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-05T14:39:16.440+08:00")
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-02-12T18:48:10.013-08:00")
public class Configuration {
private static ApiClient defaultApiClient = new ApiClient();

View File

@@ -1,6 +1,6 @@
package io.swagger.client;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-05T14:39:16.440+08:00")
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-02-12T18:48:10.013-08:00")
public class Pair {
private String name = "";
private String value = "";

View File

@@ -1,6 +1,6 @@
package io.swagger.client;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-05T14:39:16.440+08:00")
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-02-12T18:48:10.013-08:00")
public class StringUtil {
/**
* Check if the given array contains the given value (with case-insensitive comparison).

View File

@@ -12,7 +12,7 @@ import java.io.File;
import java.util.*;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-15T19:19:23.415+08:00")
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-02-12T18:48:10.013-08:00")
public class PetApi {
private ApiClient apiClient;

View File

@@ -12,7 +12,7 @@ import io.swagger.client.model.Order;
import java.util.*;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-05T14:39:16.440+08:00")
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-02-12T18:48:10.013-08:00")
public class StoreApi {
private ApiClient apiClient;

View File

@@ -12,7 +12,7 @@ import java.util.*;
import java.util.*;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-05T14:39:16.440+08:00")
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-02-12T18:48:10.013-08:00")
public class UserApi {
private ApiClient apiClient;

View File

@@ -5,7 +5,7 @@ import io.swagger.client.Pair;
import java.util.Map;
import java.util.List;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-05T14:39:16.440+08:00")
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-02-12T18:48:10.013-08:00")
public class ApiKeyAuth implements Authentication {
private final String location;
private final String paramName;

View File

@@ -9,7 +9,7 @@ import java.util.List;
import java.io.UnsupportedEncodingException;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-05T14:39:16.440+08:00")
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-02-12T18:48:10.013-08:00")
public class HttpBasicAuth implements Authentication {
private String username;
private String password;

View File

@@ -5,7 +5,7 @@ import io.swagger.client.Pair;
import java.util.Map;
import java.util.List;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-05T14:39:16.440+08:00")
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-02-12T18:48:10.013-08:00")
public class OAuth implements Authentication {
private String accessToken;

View File

@@ -10,7 +10,7 @@ import io.swagger.annotations.ApiModelProperty;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-15T19:19:23.415+08:00")
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-02-12T18:48:10.013-08:00")
public class Category {
private Long id = null;
@@ -19,8 +19,13 @@ public class Category {
/**
**/
public Category id(Long id) {
this.id = id;
return this;
}
@ApiModelProperty(value = "")
@ApiModelProperty(example = "null", value = "")
@JsonProperty("id")
public Long getId() {
return id;
@@ -32,8 +37,13 @@ public class Category {
/**
**/
public Category name(String name) {
this.name = name;
return this;
}
@ApiModelProperty(value = "")
@ApiModelProperty(example = "null", value = "")
@JsonProperty("name")
public String getName() {
return name;

View File

@@ -11,7 +11,7 @@ import java.util.Date;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-15T19:19:23.415+08:00")
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-02-12T18:48:10.013-08:00")
public class Order {
private Long id = null;
@@ -44,8 +44,13 @@ public class Order {
/**
**/
public Order id(Long id) {
this.id = id;
return this;
}
@ApiModelProperty(value = "")
@ApiModelProperty(example = "null", value = "")
@JsonProperty("id")
public Long getId() {
return id;
@@ -57,8 +62,13 @@ public class Order {
/**
**/
public Order petId(Long petId) {
this.petId = petId;
return this;
}
@ApiModelProperty(value = "")
@ApiModelProperty(example = "null", value = "")
@JsonProperty("petId")
public Long getPetId() {
return petId;
@@ -70,8 +80,13 @@ public class Order {
/**
**/
public Order quantity(Integer quantity) {
this.quantity = quantity;
return this;
}
@ApiModelProperty(value = "")
@ApiModelProperty(example = "null", value = "")
@JsonProperty("quantity")
public Integer getQuantity() {
return quantity;
@@ -83,8 +98,13 @@ public class Order {
/**
**/
public Order shipDate(Date shipDate) {
this.shipDate = shipDate;
return this;
}
@ApiModelProperty(value = "")
@ApiModelProperty(example = "null", value = "")
@JsonProperty("shipDate")
public Date getShipDate() {
return shipDate;
@@ -97,8 +117,13 @@ public class Order {
/**
* Order Status
**/
public Order status(StatusEnum status) {
this.status = status;
return this;
}
@ApiModelProperty(value = "Order Status")
@ApiModelProperty(example = "null", value = "Order Status")
@JsonProperty("status")
public StatusEnum getStatus() {
return status;
@@ -110,8 +135,13 @@ public class Order {
/**
**/
public Order complete(Boolean complete) {
this.complete = complete;
return this;
}
@ApiModelProperty(value = "")
@ApiModelProperty(example = "null", value = "")
@JsonProperty("complete")
public Boolean getComplete() {
return complete;

View File

@@ -13,7 +13,7 @@ import java.util.*;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-15T19:19:23.415+08:00")
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-02-12T18:48:10.013-08:00")
public class Pet {
private Long id = null;
@@ -46,8 +46,13 @@ public class Pet {
/**
**/
public Pet id(Long id) {
this.id = id;
return this;
}
@ApiModelProperty(value = "")
@ApiModelProperty(example = "null", value = "")
@JsonProperty("id")
public Long getId() {
return id;
@@ -59,8 +64,13 @@ public class Pet {
/**
**/
public Pet category(Category category) {
this.category = category;
return this;
}
@ApiModelProperty(value = "")
@ApiModelProperty(example = "null", value = "")
@JsonProperty("category")
public Category getCategory() {
return category;
@@ -72,8 +82,13 @@ public class Pet {
/**
**/
public Pet name(String name) {
this.name = name;
return this;
}
@ApiModelProperty(required = true, value = "")
@ApiModelProperty(example = "doggie", required = true, value = "")
@JsonProperty("name")
public String getName() {
return name;
@@ -85,8 +100,13 @@ public class Pet {
/**
**/
public Pet photoUrls(List<String> photoUrls) {
this.photoUrls = photoUrls;
return this;
}
@ApiModelProperty(required = true, value = "")
@ApiModelProperty(example = "null", required = true, value = "")
@JsonProperty("photoUrls")
public List<String> getPhotoUrls() {
return photoUrls;
@@ -98,8 +118,13 @@ public class Pet {
/**
**/
public Pet tags(List<Tag> tags) {
this.tags = tags;
return this;
}
@ApiModelProperty(value = "")
@ApiModelProperty(example = "null", value = "")
@JsonProperty("tags")
public List<Tag> getTags() {
return tags;
@@ -112,8 +137,13 @@ public class Pet {
/**
* pet status in the store
**/
public Pet status(StatusEnum status) {
this.status = status;
return this;
}
@ApiModelProperty(value = "pet status in the store")
@ApiModelProperty(example = "null", value = "pet status in the store")
@JsonProperty("status")
public StatusEnum getStatus() {
return status;

View File

@@ -10,7 +10,7 @@ import io.swagger.annotations.ApiModelProperty;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-15T19:19:23.415+08:00")
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-02-12T18:48:10.013-08:00")
public class Tag {
private Long id = null;
@@ -19,8 +19,13 @@ public class Tag {
/**
**/
public Tag id(Long id) {
this.id = id;
return this;
}
@ApiModelProperty(value = "")
@ApiModelProperty(example = "null", value = "")
@JsonProperty("id")
public Long getId() {
return id;
@@ -32,8 +37,13 @@ public class Tag {
/**
**/
public Tag name(String name) {
this.name = name;
return this;
}
@ApiModelProperty(value = "")
@ApiModelProperty(example = "null", value = "")
@JsonProperty("name")
public String getName() {
return name;

View File

@@ -10,7 +10,7 @@ import io.swagger.annotations.ApiModelProperty;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-15T19:19:23.415+08:00")
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-02-12T18:48:10.013-08:00")
public class User {
private Long id = null;
@@ -25,8 +25,13 @@ public class User {
/**
**/
public User id(Long id) {
this.id = id;
return this;
}
@ApiModelProperty(value = "")
@ApiModelProperty(example = "null", value = "")
@JsonProperty("id")
public Long getId() {
return id;
@@ -38,8 +43,13 @@ public class User {
/**
**/
public User username(String username) {
this.username = username;
return this;
}
@ApiModelProperty(value = "")
@ApiModelProperty(example = "null", value = "")
@JsonProperty("username")
public String getUsername() {
return username;
@@ -51,8 +61,13 @@ public class User {
/**
**/
public User firstName(String firstName) {
this.firstName = firstName;
return this;
}
@ApiModelProperty(value = "")
@ApiModelProperty(example = "null", value = "")
@JsonProperty("firstName")
public String getFirstName() {
return firstName;
@@ -64,8 +79,13 @@ public class User {
/**
**/
public User lastName(String lastName) {
this.lastName = lastName;
return this;
}
@ApiModelProperty(value = "")
@ApiModelProperty(example = "null", value = "")
@JsonProperty("lastName")
public String getLastName() {
return lastName;
@@ -77,8 +97,13 @@ public class User {
/**
**/
public User email(String email) {
this.email = email;
return this;
}
@ApiModelProperty(value = "")
@ApiModelProperty(example = "null", value = "")
@JsonProperty("email")
public String getEmail() {
return email;
@@ -90,8 +115,13 @@ public class User {
/**
**/
public User password(String password) {
this.password = password;
return this;
}
@ApiModelProperty(value = "")
@ApiModelProperty(example = "null", value = "")
@JsonProperty("password")
public String getPassword() {
return password;
@@ -103,8 +133,13 @@ public class User {
/**
**/
public User phone(String phone) {
this.phone = phone;
return this;
}
@ApiModelProperty(value = "")
@ApiModelProperty(example = "null", value = "")
@JsonProperty("phone")
public String getPhone() {
return phone;
@@ -117,8 +152,13 @@ public class User {
/**
* User Status
**/
public User userStatus(Integer userStatus) {
this.userStatus = userStatus;
return this;
}
@ApiModelProperty(value = "User Status")
@ApiModelProperty(example = "null", value = "User Status")
@JsonProperty("userStatus")
public Integer getUserStatus() {
return userStatus;

View File

@@ -85,7 +85,7 @@ public class PetstoreProfiling {
private void writeResultsToFile(List<Map<String, String>> results) {
try {
File file = new File(outputFile);
java.io.File file = new java.io.File(outputFile);
PrintWriter writer = new PrintWriter(file);
String command = "mvn compile test-compile exec:java -Dexec.classpathScope=test -Dexec.mainClass=\"io.swagger.PetstoreProfiling\"";
writer.println("# To run the profiling:");

View File

@@ -1,3 +1,6 @@
apply plugin: 'idea'
apply plugin: 'eclipse'
group = 'io.swagger'
version = '1.0.0'
@@ -92,8 +95,8 @@ if(hasProperty('target') && target == 'android') {
dependencies {
compile 'io.swagger:swagger-annotations:1.5.0'
compile 'com.squareup.okhttp:okhttp:2.4.0'
compile 'com.squareup.okhttp:okhttp:2.7.2'
compile 'com.squareup.okhttp:logging-interceptor:2.7.2'
compile 'com.google.code.gson:gson:2.3.1'
compile 'com.brsanthu:migbase64:2.2'
testCompile 'junit:junit:4.8.1'
}

View File

@@ -10,9 +10,9 @@ lazy val root = (project in file(".")).
resolvers += Resolver.mavenLocal,
libraryDependencies ++= Seq(
"io.swagger" % "swagger-annotations" % "1.5.0",
"com.squareup.okhttp" % "okhttp" % "2.4.0",
"com.squareup.okhttp" % "okhttp" % "2.7.2",
"com.squareup.okhttp" % "logging-interceptor" % "2.7.2",
"com.google.code.gson" % "gson" % "2.3.1",
"com.brsanthu" % "migbase64" % "2.2",
"junit" % "junit" % "4.8.1" % "test"
)
)

View File

@@ -104,6 +104,26 @@
<target>1.6</target>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.2.1</version>
<executions>
<execution>
<id>gradle-test</id>
<phase>integration-test</phase>
<goals>
<goal>exec</goal>
</goals>
<configuration>
<executable>gradle</executable>
<arguments>
<argument>check</argument>
</arguments>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<dependencies>

View File

@@ -145,8 +145,8 @@ public class ApiClient {
// Setup authentications (key: authentication name, value: authentication).
authentications = new HashMap<String, Authentication>();
authentications.put("petstore_auth", new OAuth());
authentications.put("api_key", new ApiKeyAuth("header", "api_key"));
authentications.put("petstore_auth", new OAuth());
// Prevent the authentications from being modified.
authentications = Collections.unmodifiableMap(authentications);
}

View File

@@ -3,7 +3,7 @@ package io.swagger.client;
import java.util.Map;
import java.util.List;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-05T14:39:20.056+08:00")
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-02-15T18:20:42.151+08:00")
public class ApiException extends Exception {
private int code = 0;
private Map<String, List<String>> responseHeaders = null;

View File

@@ -1,6 +1,6 @@
package io.swagger.client;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-05T14:39:20.056+08:00")
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-02-15T18:20:42.151+08:00")
public class Configuration {
private static ApiClient defaultApiClient = new ApiClient();

View File

@@ -1,6 +1,6 @@
package io.swagger.client;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-05T14:39:20.056+08:00")
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-02-15T18:20:42.151+08:00")
public class Pair {
private String name = "";
private String value = "";

View File

@@ -1,6 +1,6 @@
package io.swagger.client;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-05T14:39:20.056+08:00")
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-02-15T18:20:42.151+08:00")
public class StringUtil {
/**
* Check if the given array contains the given value (with case-insensitive comparison).

View File

@@ -5,7 +5,7 @@ import io.swagger.client.Pair;
import java.util.Map;
import java.util.List;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-05T14:39:20.056+08:00")
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-02-15T18:20:42.151+08:00")
public class ApiKeyAuth implements Authentication {
private final String location;
private final String paramName;

View File

@@ -5,7 +5,7 @@ import io.swagger.client.Pair;
import java.util.Map;
import java.util.List;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-05T14:39:20.056+08:00")
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-02-15T18:20:42.151+08:00")
public class OAuth implements Authentication {
private String accessToken;

View File

@@ -0,0 +1,2 @@
*.compiled.js
node_modules

View File

@@ -0,0 +1,19 @@
goog.provide('API.Client.Category');
/**
* @record
*/
API.Client.Category = function() {}
/**
* @type {!number}
* @export
*/
API.Client.Category.prototype.id;
/**
* @type {!string}
* @export
*/
API.Client.Category.prototype.name;

View File

@@ -0,0 +1,50 @@
goog.provide('API.Client.Order');
/**
* @record
*/
API.Client.Order = function() {}
/**
* @type {!number}
* @export
*/
API.Client.Order.prototype.id;
/**
* @type {!number}
* @export
*/
API.Client.Order.prototype.petId;
/**
* @type {!number}
* @export
*/
API.Client.Order.prototype.quantity;
/**
* @type {!Date}
* @export
*/
API.Client.Order.prototype.shipDate;
/**
* Order Status
* @type {!string}
* @export
*/
API.Client.Order.prototype.status;
/**
* @type {!boolean}
* @export
*/
API.Client.Order.prototype.complete;
/** @enum {string} */
API.Client.Order.StatusEnum = {
placed: 'placed',
approved: 'approved',
delivered: 'delivered',
}

View File

@@ -0,0 +1,50 @@
goog.provide('API.Client.Pet');
/**
* @record
*/
API.Client.Pet = function() {}
/**
* @type {!number}
* @export
*/
API.Client.Pet.prototype.id;
/**
* @type {!API.Client.Category}
* @export
*/
API.Client.Pet.prototype.category;
/**
* @type {!string}
* @export
*/
API.Client.Pet.prototype.name;
/**
* @type {!Array<!string>}
* @export
*/
API.Client.Pet.prototype.photoUrls;
/**
* @type {!Array<!API.Client.Tag>}
* @export
*/
API.Client.Pet.prototype.tags;
/**
* pet status in the store
* @type {!string}
* @export
*/
API.Client.Pet.prototype.status;
/** @enum {string} */
API.Client.Pet.StatusEnum = {
available: 'available',
pending: 'pending',
sold: 'sold',
}

View File

@@ -0,0 +1,448 @@
/**
* @fileoverview AUTOMATICALLY GENERATED service for API.Client.PetApi.
* Do not edit this file by hand or your changes will be lost next time it is
* generated.
*
* This is a sample server Petstore server. You can find out more about Swagger at &lt;a href=\&quot;http://swagger.io\&quot;&gt;http://swagger.io&lt;/a&gt; or on irc.freenode.net, #swagger. For this sample, you can use the api key \&quot;special-key\&quot; to test the authorization filters
* Version: 1.0.0
* Generated at: 2016-02-02T00:45:38.616-07:00
* Generated by: class io.swagger.codegen.languages.JavascriptClosureAngularClientCodegen
*/
/**
* @license Apache 2.0
* http://www.apache.org/licenses/LICENSE-2.0.html
*/
goog.provide('API.Client.PetApi');
goog.require('API.Client.Pet');
/**
* @constructor
* @param {!angular.$http} $http
* @param {!Object} $httpParamSerializer
* @param {!angular.$injector} $injector
* @struct
*/
API.Client.PetApi = function($http, $httpParamSerializer, $injector) {
/** @private {!string} */
this.basePath_ = $injector.has('PetApiBasePath') ?
/** @type {!string} */ ($injector.get('PetApiBasePath')) :
'http://petstore.swagger.io/v2';
/** @private {!Object<string, string>} */
this.defaultHeaders_ = $injector.has('PetApiDefaultHeaders') ?
/** @type {!Object<string, string>} */ (
$injector.get('PetApiDefaultHeaders')) :
{};
/** @private {!angular.$http} */
this.http_ = $http;
/** @private {!Object} */
this.httpParamSerializer_ = $injector.get('$httpParamSerializer');
}
API.Client.PetApi.$inject = ['$http', '$httpParamSerializer', '$injector'];
/**
* Update an existing pet
*
* @param {!Pet=} opt_body Pet object that needs to be added to the store
* @param {!angular.$http.Config=} opt_extraHttpRequestParams Extra HTTP parameters to send.
* @return {!angular.$q.Promise}
*/
API.Client.PetApi.prototype.updatePet = function(opt_body, opt_extraHttpRequestParams) {
/** @const {string} */
var path = this.basePath_ + '/pet';
/** @type {!Object} */
var queryParameters = {};
/** @type {!Object} */
var headerParams = angular.extend({}, this.defaultHeaders);
/** @type {!Object} */
var httpRequestParams = {
method: 'PUT',
url: path,
json: true,
data: opt_body,
params: queryParameters,
headers: headerParams
};
if (opt_extraHttpRequestParams) {
httpRequestParams = angular.extend(httpRequestParams, opt_extraHttpRequestParams);
}
return this.http_(httpRequestParams);
}
/**
* Add a new pet to the store
*
* @param {!Pet=} opt_body Pet object that needs to be added to the store
* @param {!angular.$http.Config=} opt_extraHttpRequestParams Extra HTTP parameters to send.
* @return {!angular.$q.Promise}
*/
API.Client.PetApi.prototype.addPet = function(opt_body, opt_extraHttpRequestParams) {
/** @const {string} */
var path = this.basePath_ + '/pet';
/** @type {!Object} */
var queryParameters = {};
/** @type {!Object} */
var headerParams = angular.extend({}, this.defaultHeaders);
/** @type {!Object} */
var httpRequestParams = {
method: 'POST',
url: path,
json: true,
data: opt_body,
params: queryParameters,
headers: headerParams
};
if (opt_extraHttpRequestParams) {
httpRequestParams = angular.extend(httpRequestParams, opt_extraHttpRequestParams);
}
return this.http_(httpRequestParams);
}
/**
* Finds Pets by status
* Multiple status values can be provided with comma seperated strings
* @param {!Array<!string>=} opt_status Status values that need to be considered for filter
* @param {!angular.$http.Config=} opt_extraHttpRequestParams Extra HTTP parameters to send.
* @return {!angular.$q.Promise<!Array<!API.Client.Pet>>}
*/
API.Client.PetApi.prototype.findPetsByStatus = function(opt_status, opt_extraHttpRequestParams) {
/** @const {string} */
var path = this.basePath_ + '/pet/findByStatus';
/** @type {!Object} */
var queryParameters = {};
/** @type {!Object} */
var headerParams = angular.extend({}, this.defaultHeaders);
if (opt_status !== undefined) {
queryParameters['status'] = opt_status;
}
/** @type {!Object} */
var httpRequestParams = {
method: 'GET',
url: path,
json: true,
params: queryParameters,
headers: headerParams
};
if (opt_extraHttpRequestParams) {
httpRequestParams = angular.extend(httpRequestParams, opt_extraHttpRequestParams);
}
return this.http_(httpRequestParams);
}
/**
* Finds Pets by tags
* Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.
* @param {!Array<!string>=} opt_tags Tags to filter by
* @param {!angular.$http.Config=} opt_extraHttpRequestParams Extra HTTP parameters to send.
* @return {!angular.$q.Promise<!Array<!API.Client.Pet>>}
*/
API.Client.PetApi.prototype.findPetsByTags = function(opt_tags, opt_extraHttpRequestParams) {
/** @const {string} */
var path = this.basePath_ + '/pet/findByTags';
/** @type {!Object} */
var queryParameters = {};
/** @type {!Object} */
var headerParams = angular.extend({}, this.defaultHeaders);
if (opt_tags !== undefined) {
queryParameters['tags'] = opt_tags;
}
/** @type {!Object} */
var httpRequestParams = {
method: 'GET',
url: path,
json: true,
params: queryParameters,
headers: headerParams
};
if (opt_extraHttpRequestParams) {
httpRequestParams = angular.extend(httpRequestParams, opt_extraHttpRequestParams);
}
return this.http_(httpRequestParams);
}
/**
* Find pet by ID
* Returns a pet when ID &lt; 10. ID &gt; 10 or nonintegers will simulate API error conditions
* @param {!number} petId ID of pet that needs to be fetched
* @param {!angular.$http.Config=} opt_extraHttpRequestParams Extra HTTP parameters to send.
* @return {!angular.$q.Promise<!API.Client.Pet>}
*/
API.Client.PetApi.prototype.getPetById = function(petId, opt_extraHttpRequestParams) {
/** @const {string} */
var path = this.basePath_ + '/pet/{petId}'
.replace('{' + 'petId' + '}', String(petId));
/** @type {!Object} */
var queryParameters = {};
/** @type {!Object} */
var headerParams = angular.extend({}, this.defaultHeaders);
// verify required parameter 'petId' is set
if (!petId) {
throw new Error('Missing required parameter petId when calling getPetById');
}
/** @type {!Object} */
var httpRequestParams = {
method: 'GET',
url: path,
json: true,
params: queryParameters,
headers: headerParams
};
if (opt_extraHttpRequestParams) {
httpRequestParams = angular.extend(httpRequestParams, opt_extraHttpRequestParams);
}
return this.http_(httpRequestParams);
}
/**
* Updates a pet in the store with form data
*
* @param {!string} petId ID of pet that needs to be updated
* @param {!string=} opt_name Updated name of the pet
* @param {!string=} opt_status Updated status of the pet
* @param {!angular.$http.Config=} opt_extraHttpRequestParams Extra HTTP parameters to send.
* @return {!angular.$q.Promise}
*/
API.Client.PetApi.prototype.updatePetWithForm = function(petId, opt_name, opt_status, opt_extraHttpRequestParams) {
/** @const {string} */
var path = this.basePath_ + '/pet/{petId}'
.replace('{' + 'petId' + '}', String(petId));
/** @type {!Object} */
var queryParameters = {};
/** @type {!Object} */
var headerParams = angular.extend({}, this.defaultHeaders);
/** @type {!Object} */
var formParams = {};
// verify required parameter 'petId' is set
if (!petId) {
throw new Error('Missing required parameter petId when calling updatePetWithForm');
}
headerParams['Content-Type'] = 'application/x-www-form-urlencoded';
formParams['name'] = opt_name;
formParams['status'] = opt_status;
/** @type {!Object} */
var httpRequestParams = {
method: 'POST',
url: path,
json: false,
data: this.httpParamSerializer_(formParams),
params: queryParameters,
headers: headerParams
};
if (opt_extraHttpRequestParams) {
httpRequestParams = angular.extend(httpRequestParams, opt_extraHttpRequestParams);
}
return this.http_(httpRequestParams);
}
/**
* Deletes a pet
*
* @param {!number} petId Pet id to delete
* @param {!string=} opt_apiKey
* @param {!angular.$http.Config=} opt_extraHttpRequestParams Extra HTTP parameters to send.
* @return {!angular.$q.Promise}
*/
API.Client.PetApi.prototype.deletePet = function(petId, opt_apiKey, opt_extraHttpRequestParams) {
/** @const {string} */
var path = this.basePath_ + '/pet/{petId}'
.replace('{' + 'petId' + '}', String(petId));
/** @type {!Object} */
var queryParameters = {};
/** @type {!Object} */
var headerParams = angular.extend({}, this.defaultHeaders);
// verify required parameter 'petId' is set
if (!petId) {
throw new Error('Missing required parameter petId when calling deletePet');
}
headerParams['api_key'] = opt_apiKey;
/** @type {!Object} */
var httpRequestParams = {
method: 'DELETE',
url: path,
json: true,
params: queryParameters,
headers: headerParams
};
if (opt_extraHttpRequestParams) {
httpRequestParams = angular.extend(httpRequestParams, opt_extraHttpRequestParams);
}
return this.http_(httpRequestParams);
}
/**
* uploads an image
*
* @param {!number} petId ID of pet to update
* @param {!string=} opt_additionalMetadata Additional data to pass to server
* @param {!Object=} opt_file file to upload
* @param {!angular.$http.Config=} opt_extraHttpRequestParams Extra HTTP parameters to send.
* @return {!angular.$q.Promise}
*/
API.Client.PetApi.prototype.uploadFile = function(petId, opt_additionalMetadata, opt_file, opt_extraHttpRequestParams) {
/** @const {string} */
var path = this.basePath_ + '/pet/{petId}/uploadImage'
.replace('{' + 'petId' + '}', String(petId));
/** @type {!Object} */
var queryParameters = {};
/** @type {!Object} */
var headerParams = angular.extend({}, this.defaultHeaders);
/** @type {!Object} */
var formParams = {};
// verify required parameter 'petId' is set
if (!petId) {
throw new Error('Missing required parameter petId when calling uploadFile');
}
headerParams['Content-Type'] = 'application/x-www-form-urlencoded';
formParams['additionalMetadata'] = opt_additionalMetadata;
formParams['file'] = opt_file;
/** @type {!Object} */
var httpRequestParams = {
method: 'POST',
url: path,
json: false,
data: this.httpParamSerializer_(formParams),
params: queryParameters,
headers: headerParams
};
if (opt_extraHttpRequestParams) {
httpRequestParams = angular.extend(httpRequestParams, opt_extraHttpRequestParams);
}
return this.http_(httpRequestParams);
}
/**
* Fake endpoint to test byte array return by &#39;Find pet by ID&#39;
* Returns a pet when ID &lt; 10. ID &gt; 10 or nonintegers will simulate API error conditions
* @param {!number} petId ID of pet that needs to be fetched
* @param {!angular.$http.Config=} opt_extraHttpRequestParams Extra HTTP parameters to send.
* @return {!angular.$q.Promise<!string>}
*/
API.Client.PetApi.prototype.getPetByIdWithByteArray = function(petId, opt_extraHttpRequestParams) {
/** @const {string} */
var path = this.basePath_ + '/pet/{petId}?testing_byte_array=true'
.replace('{' + 'petId' + '}', String(petId));
/** @type {!Object} */
var queryParameters = {};
/** @type {!Object} */
var headerParams = angular.extend({}, this.defaultHeaders);
// verify required parameter 'petId' is set
if (!petId) {
throw new Error('Missing required parameter petId when calling getPetByIdWithByteArray');
}
/** @type {!Object} */
var httpRequestParams = {
method: 'GET',
url: path,
json: true,
params: queryParameters,
headers: headerParams
};
if (opt_extraHttpRequestParams) {
httpRequestParams = angular.extend(httpRequestParams, opt_extraHttpRequestParams);
}
return this.http_(httpRequestParams);
}
/**
* Fake endpoint to test byte array in body parameter for adding a new pet to the store
*
* @param {!string=} opt_body Pet object in the form of byte array
* @param {!angular.$http.Config=} opt_extraHttpRequestParams Extra HTTP parameters to send.
* @return {!angular.$q.Promise}
*/
API.Client.PetApi.prototype.addPetUsingByteArray = function(opt_body, opt_extraHttpRequestParams) {
/** @const {string} */
var path = this.basePath_ + '/pet?testing_byte_array=true';
/** @type {!Object} */
var queryParameters = {};
/** @type {!Object} */
var headerParams = angular.extend({}, this.defaultHeaders);
/** @type {!Object} */
var httpRequestParams = {
method: 'POST',
url: path,
json: true,
data: opt_body,
params: queryParameters,
headers: headerParams
};
if (opt_extraHttpRequestParams) {
httpRequestParams = angular.extend(httpRequestParams, opt_extraHttpRequestParams);
}
return this.http_(httpRequestParams);
}

View File

@@ -0,0 +1,191 @@
/**
* @fileoverview AUTOMATICALLY GENERATED service for API.Client.StoreApi.
* Do not edit this file by hand or your changes will be lost next time it is
* generated.
*
* This is a sample server Petstore server. You can find out more about Swagger at &lt;a href=\&quot;http://swagger.io\&quot;&gt;http://swagger.io&lt;/a&gt; or on irc.freenode.net, #swagger. For this sample, you can use the api key \&quot;special-key\&quot; to test the authorization filters
* Version: 1.0.0
* Generated at: 2016-02-02T00:45:38.616-07:00
* Generated by: class io.swagger.codegen.languages.JavascriptClosureAngularClientCodegen
*/
/**
* @license Apache 2.0
* http://www.apache.org/licenses/LICENSE-2.0.html
*/
goog.provide('API.Client.StoreApi');
goog.require('API.Client.Order');
/**
* @constructor
* @param {!angular.$http} $http
* @param {!Object} $httpParamSerializer
* @param {!angular.$injector} $injector
* @struct
*/
API.Client.StoreApi = function($http, $httpParamSerializer, $injector) {
/** @private {!string} */
this.basePath_ = $injector.has('StoreApiBasePath') ?
/** @type {!string} */ ($injector.get('StoreApiBasePath')) :
'http://petstore.swagger.io/v2';
/** @private {!Object<string, string>} */
this.defaultHeaders_ = $injector.has('StoreApiDefaultHeaders') ?
/** @type {!Object<string, string>} */ (
$injector.get('StoreApiDefaultHeaders')) :
{};
/** @private {!angular.$http} */
this.http_ = $http;
/** @private {!Object} */
this.httpParamSerializer_ = $injector.get('$httpParamSerializer');
}
API.Client.StoreApi.$inject = ['$http', '$httpParamSerializer', '$injector'];
/**
* Returns pet inventories by status
* Returns a map of status codes to quantities
* @param {!angular.$http.Config=} opt_extraHttpRequestParams Extra HTTP parameters to send.
* @return {!angular.$q.Promise<!Object<!string, number>>}
*/
API.Client.StoreApi.prototype.getInventory = function(opt_extraHttpRequestParams) {
/** @const {string} */
var path = this.basePath_ + '/store/inventory';
/** @type {!Object} */
var queryParameters = {};
/** @type {!Object} */
var headerParams = angular.extend({}, this.defaultHeaders);
/** @type {!Object} */
var httpRequestParams = {
method: 'GET',
url: path,
json: true,
params: queryParameters,
headers: headerParams
};
if (opt_extraHttpRequestParams) {
httpRequestParams = angular.extend(httpRequestParams, opt_extraHttpRequestParams);
}
return this.http_(httpRequestParams);
}
/**
* Place an order for a pet
*
* @param {!Order=} opt_body order placed for purchasing the pet
* @param {!angular.$http.Config=} opt_extraHttpRequestParams Extra HTTP parameters to send.
* @return {!angular.$q.Promise<!API.Client.Order>}
*/
API.Client.StoreApi.prototype.placeOrder = function(opt_body, opt_extraHttpRequestParams) {
/** @const {string} */
var path = this.basePath_ + '/store/order';
/** @type {!Object} */
var queryParameters = {};
/** @type {!Object} */
var headerParams = angular.extend({}, this.defaultHeaders);
/** @type {!Object} */
var httpRequestParams = {
method: 'POST',
url: path,
json: true,
data: opt_body,
params: queryParameters,
headers: headerParams
};
if (opt_extraHttpRequestParams) {
httpRequestParams = angular.extend(httpRequestParams, opt_extraHttpRequestParams);
}
return this.http_(httpRequestParams);
}
/**
* Find purchase order by ID
* For valid response try integer IDs with value &lt;= 5 or &gt; 10. Other values will generated exceptions
* @param {!string} orderId ID of pet that needs to be fetched
* @param {!angular.$http.Config=} opt_extraHttpRequestParams Extra HTTP parameters to send.
* @return {!angular.$q.Promise<!API.Client.Order>}
*/
API.Client.StoreApi.prototype.getOrderById = function(orderId, opt_extraHttpRequestParams) {
/** @const {string} */
var path = this.basePath_ + '/store/order/{orderId}'
.replace('{' + 'orderId' + '}', String(orderId));
/** @type {!Object} */
var queryParameters = {};
/** @type {!Object} */
var headerParams = angular.extend({}, this.defaultHeaders);
// verify required parameter 'orderId' is set
if (!orderId) {
throw new Error('Missing required parameter orderId when calling getOrderById');
}
/** @type {!Object} */
var httpRequestParams = {
method: 'GET',
url: path,
json: true,
params: queryParameters,
headers: headerParams
};
if (opt_extraHttpRequestParams) {
httpRequestParams = angular.extend(httpRequestParams, opt_extraHttpRequestParams);
}
return this.http_(httpRequestParams);
}
/**
* Delete purchase order by ID
* For valid response try integer IDs with value &lt; 1000. Anything above 1000 or nonintegers will generate API errors
* @param {!string} orderId ID of the order that needs to be deleted
* @param {!angular.$http.Config=} opt_extraHttpRequestParams Extra HTTP parameters to send.
* @return {!angular.$q.Promise}
*/
API.Client.StoreApi.prototype.deleteOrder = function(orderId, opt_extraHttpRequestParams) {
/** @const {string} */
var path = this.basePath_ + '/store/order/{orderId}'
.replace('{' + 'orderId' + '}', String(orderId));
/** @type {!Object} */
var queryParameters = {};
/** @type {!Object} */
var headerParams = angular.extend({}, this.defaultHeaders);
// verify required parameter 'orderId' is set
if (!orderId) {
throw new Error('Missing required parameter orderId when calling deleteOrder');
}
/** @type {!Object} */
var httpRequestParams = {
method: 'DELETE',
url: path,
json: true,
params: queryParameters,
headers: headerParams
};
if (opt_extraHttpRequestParams) {
httpRequestParams = angular.extend(httpRequestParams, opt_extraHttpRequestParams);
}
return this.http_(httpRequestParams);
}

View File

@@ -0,0 +1,19 @@
goog.provide('API.Client.Tag');
/**
* @record
*/
API.Client.Tag = function() {}
/**
* @type {!number}
* @export
*/
API.Client.Tag.prototype.id;
/**
* @type {!string}
* @export
*/
API.Client.Tag.prototype.name;

View File

@@ -0,0 +1,56 @@
goog.provide('API.Client.User');
/**
* @record
*/
API.Client.User = function() {}
/**
* @type {!number}
* @export
*/
API.Client.User.prototype.id;
/**
* @type {!string}
* @export
*/
API.Client.User.prototype.username;
/**
* @type {!string}
* @export
*/
API.Client.User.prototype.firstName;
/**
* @type {!string}
* @export
*/
API.Client.User.prototype.lastName;
/**
* @type {!string}
* @export
*/
API.Client.User.prototype.email;
/**
* @type {!string}
* @export
*/
API.Client.User.prototype.password;
/**
* @type {!string}
* @export
*/
API.Client.User.prototype.phone;
/**
* User Status
* @type {!number}
* @export
*/
API.Client.User.prototype.userStatus;

View File

@@ -0,0 +1,345 @@
/**
* @fileoverview AUTOMATICALLY GENERATED service for API.Client.UserApi.
* Do not edit this file by hand or your changes will be lost next time it is
* generated.
*
* This is a sample server Petstore server. You can find out more about Swagger at &lt;a href=\&quot;http://swagger.io\&quot;&gt;http://swagger.io&lt;/a&gt; or on irc.freenode.net, #swagger. For this sample, you can use the api key \&quot;special-key\&quot; to test the authorization filters
* Version: 1.0.0
* Generated at: 2016-02-02T00:45:38.616-07:00
* Generated by: class io.swagger.codegen.languages.JavascriptClosureAngularClientCodegen
*/
/**
* @license Apache 2.0
* http://www.apache.org/licenses/LICENSE-2.0.html
*/
goog.provide('API.Client.UserApi');
goog.require('API.Client.User');
/**
* @constructor
* @param {!angular.$http} $http
* @param {!Object} $httpParamSerializer
* @param {!angular.$injector} $injector
* @struct
*/
API.Client.UserApi = function($http, $httpParamSerializer, $injector) {
/** @private {!string} */
this.basePath_ = $injector.has('UserApiBasePath') ?
/** @type {!string} */ ($injector.get('UserApiBasePath')) :
'http://petstore.swagger.io/v2';
/** @private {!Object<string, string>} */
this.defaultHeaders_ = $injector.has('UserApiDefaultHeaders') ?
/** @type {!Object<string, string>} */ (
$injector.get('UserApiDefaultHeaders')) :
{};
/** @private {!angular.$http} */
this.http_ = $http;
/** @private {!Object} */
this.httpParamSerializer_ = $injector.get('$httpParamSerializer');
}
API.Client.UserApi.$inject = ['$http', '$httpParamSerializer', '$injector'];
/**
* Create user
* This can only be done by the logged in user.
* @param {!User=} opt_body Created user object
* @param {!angular.$http.Config=} opt_extraHttpRequestParams Extra HTTP parameters to send.
* @return {!angular.$q.Promise}
*/
API.Client.UserApi.prototype.createUser = function(opt_body, opt_extraHttpRequestParams) {
/** @const {string} */
var path = this.basePath_ + '/user';
/** @type {!Object} */
var queryParameters = {};
/** @type {!Object} */
var headerParams = angular.extend({}, this.defaultHeaders);
/** @type {!Object} */
var httpRequestParams = {
method: 'POST',
url: path,
json: true,
data: opt_body,
params: queryParameters,
headers: headerParams
};
if (opt_extraHttpRequestParams) {
httpRequestParams = angular.extend(httpRequestParams, opt_extraHttpRequestParams);
}
return this.http_(httpRequestParams);
}
/**
* Creates list of users with given input array
*
* @param {!Array<!API.Client.User>=} opt_body List of user object
* @param {!angular.$http.Config=} opt_extraHttpRequestParams Extra HTTP parameters to send.
* @return {!angular.$q.Promise}
*/
API.Client.UserApi.prototype.createUsersWithArrayInput = function(opt_body, opt_extraHttpRequestParams) {
/** @const {string} */
var path = this.basePath_ + '/user/createWithArray';
/** @type {!Object} */
var queryParameters = {};
/** @type {!Object} */
var headerParams = angular.extend({}, this.defaultHeaders);
/** @type {!Object} */
var httpRequestParams = {
method: 'POST',
url: path,
json: true,
data: opt_body,
params: queryParameters,
headers: headerParams
};
if (opt_extraHttpRequestParams) {
httpRequestParams = angular.extend(httpRequestParams, opt_extraHttpRequestParams);
}
return this.http_(httpRequestParams);
}
/**
* Creates list of users with given input array
*
* @param {!Array<!API.Client.User>=} opt_body List of user object
* @param {!angular.$http.Config=} opt_extraHttpRequestParams Extra HTTP parameters to send.
* @return {!angular.$q.Promise}
*/
API.Client.UserApi.prototype.createUsersWithListInput = function(opt_body, opt_extraHttpRequestParams) {
/** @const {string} */
var path = this.basePath_ + '/user/createWithList';
/** @type {!Object} */
var queryParameters = {};
/** @type {!Object} */
var headerParams = angular.extend({}, this.defaultHeaders);
/** @type {!Object} */
var httpRequestParams = {
method: 'POST',
url: path,
json: true,
data: opt_body,
params: queryParameters,
headers: headerParams
};
if (opt_extraHttpRequestParams) {
httpRequestParams = angular.extend(httpRequestParams, opt_extraHttpRequestParams);
}
return this.http_(httpRequestParams);
}
/**
* Logs user into the system
*
* @param {!string=} opt_username The user name for login
* @param {!string=} opt_password The password for login in clear text
* @param {!angular.$http.Config=} opt_extraHttpRequestParams Extra HTTP parameters to send.
* @return {!angular.$q.Promise<!string>}
*/
API.Client.UserApi.prototype.loginUser = function(opt_username, opt_password, opt_extraHttpRequestParams) {
/** @const {string} */
var path = this.basePath_ + '/user/login';
/** @type {!Object} */
var queryParameters = {};
/** @type {!Object} */
var headerParams = angular.extend({}, this.defaultHeaders);
if (opt_username !== undefined) {
queryParameters['username'] = opt_username;
}
if (opt_password !== undefined) {
queryParameters['password'] = opt_password;
}
/** @type {!Object} */
var httpRequestParams = {
method: 'GET',
url: path,
json: true,
params: queryParameters,
headers: headerParams
};
if (opt_extraHttpRequestParams) {
httpRequestParams = angular.extend(httpRequestParams, opt_extraHttpRequestParams);
}
return this.http_(httpRequestParams);
}
/**
* Logs out current logged in user session
*
* @param {!angular.$http.Config=} opt_extraHttpRequestParams Extra HTTP parameters to send.
* @return {!angular.$q.Promise}
*/
API.Client.UserApi.prototype.logoutUser = function(opt_extraHttpRequestParams) {
/** @const {string} */
var path = this.basePath_ + '/user/logout';
/** @type {!Object} */
var queryParameters = {};
/** @type {!Object} */
var headerParams = angular.extend({}, this.defaultHeaders);
/** @type {!Object} */
var httpRequestParams = {
method: 'GET',
url: path,
json: true,
params: queryParameters,
headers: headerParams
};
if (opt_extraHttpRequestParams) {
httpRequestParams = angular.extend(httpRequestParams, opt_extraHttpRequestParams);
}
return this.http_(httpRequestParams);
}
/**
* Get user by user name
*
* @param {!string} username The name that needs to be fetched. Use user1 for testing.
* @param {!angular.$http.Config=} opt_extraHttpRequestParams Extra HTTP parameters to send.
* @return {!angular.$q.Promise<!API.Client.User>}
*/
API.Client.UserApi.prototype.getUserByName = function(username, opt_extraHttpRequestParams) {
/** @const {string} */
var path = this.basePath_ + '/user/{username}'
.replace('{' + 'username' + '}', String(username));
/** @type {!Object} */
var queryParameters = {};
/** @type {!Object} */
var headerParams = angular.extend({}, this.defaultHeaders);
// verify required parameter 'username' is set
if (!username) {
throw new Error('Missing required parameter username when calling getUserByName');
}
/** @type {!Object} */
var httpRequestParams = {
method: 'GET',
url: path,
json: true,
params: queryParameters,
headers: headerParams
};
if (opt_extraHttpRequestParams) {
httpRequestParams = angular.extend(httpRequestParams, opt_extraHttpRequestParams);
}
return this.http_(httpRequestParams);
}
/**
* Updated user
* This can only be done by the logged in user.
* @param {!string} username name that need to be deleted
* @param {!User=} opt_body Updated user object
* @param {!angular.$http.Config=} opt_extraHttpRequestParams Extra HTTP parameters to send.
* @return {!angular.$q.Promise}
*/
API.Client.UserApi.prototype.updateUser = function(username, opt_body, opt_extraHttpRequestParams) {
/** @const {string} */
var path = this.basePath_ + '/user/{username}'
.replace('{' + 'username' + '}', String(username));
/** @type {!Object} */
var queryParameters = {};
/** @type {!Object} */
var headerParams = angular.extend({}, this.defaultHeaders);
// verify required parameter 'username' is set
if (!username) {
throw new Error('Missing required parameter username when calling updateUser');
}
/** @type {!Object} */
var httpRequestParams = {
method: 'PUT',
url: path,
json: true,
data: opt_body,
params: queryParameters,
headers: headerParams
};
if (opt_extraHttpRequestParams) {
httpRequestParams = angular.extend(httpRequestParams, opt_extraHttpRequestParams);
}
return this.http_(httpRequestParams);
}
/**
* Delete user
* This can only be done by the logged in user.
* @param {!string} username The name that needs to be deleted
* @param {!angular.$http.Config=} opt_extraHttpRequestParams Extra HTTP parameters to send.
* @return {!angular.$q.Promise}
*/
API.Client.UserApi.prototype.deleteUser = function(username, opt_extraHttpRequestParams) {
/** @const {string} */
var path = this.basePath_ + '/user/{username}'
.replace('{' + 'username' + '}', String(username));
/** @type {!Object} */
var queryParameters = {};
/** @type {!Object} */
var headerParams = angular.extend({}, this.defaultHeaders);
// verify required parameter 'username' is set
if (!username) {
throw new Error('Missing required parameter username when calling deleteUser');
}
/** @type {!Object} */
var httpRequestParams = {
method: 'DELETE',
url: path,
json: true,
params: queryParameters,
headers: headerParams
};
if (opt_extraHttpRequestParams) {
httpRequestParams = angular.extend(httpRequestParams, opt_extraHttpRequestParams);
}
return this.http_(httpRequestParams);
}

View File

@@ -0,0 +1,63 @@
#!/usr/bin/python
import httplib, urllib, sys
# Collect all the files in an order that will work. That is Models first then APIs
def concatFiles(files):
code = ""
for file in files:
code += open(file).read()
return code
def makeRequest(params):
# Always use the following value for the Content-type header.
headers = { "Content-type": "application/x-www-form-urlencoded" }
conn = httplib.HTTPConnection('closure-compiler.appspot.com')
conn.request('POST', '/compile', params, headers)
response = conn.getresponse()
data = response.read()
conn.close()
return data
def checkForCompilerErrors(files):
params = urllib.urlencode([
('js_code', concatFiles(files)),
('compilation_level', 'SIMPLE_OPTIMIZATIONS'),
('language', 'ECMASCRIPT5_STRICT'),
('output_format', 'text'),
('output_info', 'errors'),
])
return makeRequest(params)
def compile(output, files):
params = urllib.urlencode([
('js_code', concatFiles(files)),
('compilation_level', 'SIMPLE_OPTIMIZATIONS'),
('language', 'ECMASCRIPT5_STRICT'),
('output_format', 'text'),
('output_info', 'compiled_code'),
])
f = open(output, 'w')
f.write(makeRequest(params))
f.close()
targets = {
"PetAPI": ["API/Client/Tag.js", "API/Client/Category.js", "API/Client/Pet.js", "API/Client/PetApi.js"],
"StoreAPI": ["API/Client/Order.js", "API/Client/StoreApi.js"],
"UserAPI": ["API/Client/User.js", "API/Client/UserApi.js"],
}
def main():
for name, targetFiles in targets.iteritems():
errors = checkForCompilerErrors(targetFiles)
if errors:
print "Compiler errors when building %s" % name
print errors
for name, targetFiles in targets.iteritems():
compile("%s.compiled.js" % name, targets[name])
if __name__ == "__main__":
sys.exit(main())

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