Merge remote-tracking branch 'origin/master' into 2.3.0

This commit is contained in:
wing328 2016-11-02 15:43:00 +08:00
commit c1e6f00242
140 changed files with 3059 additions and 731 deletions

View File

@ -26,7 +26,7 @@ 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/JavaSpring/libraries/spring-cloud -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l spring -c bin/spring-cloud-feign-petstore.json -o samples/client/petstore/spring-cloud -DhideGenerationTimestamp=true"
ags="$@ generate -t modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-cloud -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l spring -c bin/spring-cloud-feign-petstore.json -o samples/client/petstore/spring-cloud -DhideGenerationTimestamp=true,responseWrapper=HystrixCommand"
echo "Removing files and folders under samples/client/petstore/spring-cloud/src/main"
rm -rf samples/client/petstore/spring-cloud/src/main

207
google_checkstyle.xml Normal file
View File

@ -0,0 +1,207 @@
<?xml version="1.0"?>
<!DOCTYPE module PUBLIC "-//Puppy Crawl//DTD Check Configuration 1.3//EN" "http://www.puppycrawl.com/dtds/configuration_1_3.dtd">
<!--
Adjusted from original Google Checkstyle config - https://github.com/checkstyle/checkstyle/blob/master/src/main/resources/google_checks.xml
For details, see further comments in this file.
-->
<!--
Checkstyle configuration that checks the Google coding conventions from Google Java Style
that can be found at https://google.github.io/styleguide/javaguide.html.
Checkstyle is very configurable. Be sure to read the documentation at
http://checkstyle.sf.net (or in your downloaded distribution).
To completely disable a check, just comment it out or delete it from the file.
Authors: Max Vetrenko, Ruslan Diachenko, Roman Ivanov.
-->
<module name="Checker">
<property name="charset" value="UTF-8"/>
<property name="severity" value="warning"/>
<property name="fileExtensions" value="java, properties, xml"/>
<!-- Checks for whitespace -->
<!-- See http://checkstyle.sf.net/config_whitespace.html -->
<module name="FileTabCharacter">
<property name="eachLine" value="true"/>
</module>
<module name="TreeWalker">
<module name="OuterTypeFilename"/>
<module name="IllegalTokenText">
<property name="tokens" value="STRING_LITERAL, CHAR_LITERAL"/>
<property name="format" value="\\u00(08|09|0(a|A)|0(c|C)|0(d|D)|22|27|5(C|c))|\\(0(10|11|12|14|15|42|47)|134)"/>
<property name="message" value="Avoid using corresponding octal or Unicode escape."/>
</module>
<module name="AvoidEscapedUnicodeCharacters">
<property name="allowEscapesForControlCharacters" value="true"/>
<property name="allowByTailComment" value="true"/>
<property name="allowNonPrintableEscapes" value="true"/>
</module>
<module name="LineLength">
<property name="max" value="100"/>
<property name="ignorePattern" value="^package.*|^import.*|a href|href|http://|https://|ftp://"/>
</module>
<module name="AvoidStarImport"/>
<module name="OneTopLevelClass"/>
<module name="NoLineWrap"/>
<module name="EmptyBlock">
<property name="option" value="TEXT"/>
<property name="tokens" value="LITERAL_TRY, LITERAL_FINALLY, LITERAL_IF, LITERAL_ELSE, LITERAL_SWITCH"/>
</module>
<module name="NeedBraces"/>
<module name="LeftCurly">
<property name="maxLineLength" value="100"/>
</module>
<module name="RightCurly"/>
<module name="RightCurly">
<property name="option" value="alone"/>
<property name="tokens" value="CLASS_DEF, METHOD_DEF, CTOR_DEF, LITERAL_FOR, LITERAL_WHILE, LITERAL_DO, STATIC_INIT, INSTANCE_INIT"/>
</module>
<module name="WhitespaceAround">
<property name="allowEmptyConstructors" value="true"/>
<property name="allowEmptyMethods" value="true"/>
<property name="allowEmptyTypes" value="true"/>
<property name="allowEmptyLoops" value="true"/>
<message key="ws.notFollowed" value="WhitespaceAround: ''{0}'' is not followed by whitespace. Empty blocks may only be represented as '{}' when not part of a multi-block statement (4.1.3)"/>
<message key="ws.notPreceded" value="WhitespaceAround: ''{0}'' is not preceded with whitespace."/>
</module>
<module name="OneStatementPerLine"/>
<module name="MultipleVariableDeclarations"/>
<module name="ArrayTypeStyle"/>
<module name="MissingSwitchDefault"/>
<module name="FallThrough"/>
<module name="UpperEll"/>
<module name="ModifierOrder"/>
<module name="EmptyLineSeparator">
<property name="allowNoEmptyLineBetweenFields" value="true"/>
</module>
<module name="SeparatorWrap">
<property name="tokens" value="DOT"/>
<property name="option" value="nl"/>
</module>
<module name="SeparatorWrap">
<property name="tokens" value="COMMA"/>
<property name="option" value="EOL"/>
</module>
<module name="PackageName">
<property name="format" value="^[a-z]+(\.[a-z][a-z0-9]*)*$"/>
<message key="name.invalidPattern" value="Package name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="TypeName">
<message key="name.invalidPattern" value="Type name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="MemberName">
<property name="format" value="^[a-z][a-z0-9][a-zA-Z0-9]*$"/>
<message key="name.invalidPattern" value="Member name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="ParameterName">
<property name="format" value="^[a-z][a-z0-9][a-zA-Z0-9]*$"/>
<message key="name.invalidPattern" value="Parameter name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="CatchParameterName">
<property name="format" value="^[a-z][a-z0-9][a-zA-Z0-9]*$"/>
<message key="name.invalidPattern" value="Catch parameter name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="LocalVariableName">
<property name="tokens" value="VARIABLE_DEF"/>
<property name="format" value="^[a-z][a-z0-9][a-zA-Z0-9]*$"/>
<property name="allowOneCharVarInForLoop" value="true"/>
<message key="name.invalidPattern" value="Local variable name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="ClassTypeParameterName">
<property name="format" value="(^[A-Z][0-9]?)$|([A-Z][a-zA-Z0-9]*[T]$)"/>
<message key="name.invalidPattern" value="Class type name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="MethodTypeParameterName">
<property name="format" value="(^[A-Z][0-9]?)$|([A-Z][a-zA-Z0-9]*[T]$)"/>
<message key="name.invalidPattern" value="Method type name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="InterfaceTypeParameterName">
<property name="format" value="(^[A-Z][0-9]?)$|([A-Z][a-zA-Z0-9]*[T]$)"/>
<message key="name.invalidPattern" value="Interface type name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="NoFinalizer"/>
<module name="GenericWhitespace">
<message key="ws.followed" value="GenericWhitespace ''{0}'' is followed by whitespace."/>
<message key="ws.preceded" value="GenericWhitespace ''{0}'' is preceded with whitespace."/>
<message key="ws.illegalFollow" value="GenericWhitespace ''{0}'' should followed by whitespace."/>
<message key="ws.notPreceded" value="GenericWhitespace ''{0}'' is not preceded with whitespace."/>
</module>
<module name="Indentation">
<!-- Modified defaults for swagger-codegen (multipled Google by 2)-->
<property name="basicOffset" value="4"/>
<property name="braceAdjustment" value="0"/>
<property name="caseIndent" value="4"/>
<property name="throwsIndent" value="8"/>
<property name="lineWrappingIndentation" value="8"/>
<property name="arrayInitIndent" value="4"/>
<!-- Actual Google Java Style defaults -->
<!--
<property name="basicOffset" value="2"/>
<property name="braceAdjustment" value="0"/>
<property name="caseIndent" value="2"/>
<property name="throwsIndent" value="4"/>
<property name="lineWrappingIndentation" value="4"/>
<property name="arrayInitIndent" value="2"/>
-->
</module>
<module name="AbbreviationAsWordInName">
<property name="ignoreFinal" value="false"/>
<property name="allowedAbbreviationLength" value="1"/>
</module>
<module name="OverloadMethodsDeclarationOrder"/>
<module name="VariableDeclarationUsageDistance"/>
<module name="CustomImportOrder">
<property name="specialImportsRegExp" value="com.google"/>
<property name="sortImportsInGroupAlphabetically" value="true"/>
<property name="customImportOrderRules" value="STATIC###SPECIAL_IMPORTS###THIRD_PARTY_PACKAGE###STANDARD_JAVA_PACKAGE"/>
</module>
<module name="MethodParamPad"/>
<module name="OperatorWrap">
<property name="option" value="NL"/>
<property name="tokens" value="BAND, BOR, BSR, BXOR, DIV, EQUAL, GE, GT, LAND, LE, LITERAL_INSTANCEOF, LOR, LT, MINUS, MOD, NOT_EQUAL, PLUS, QUESTION, SL, SR, STAR "/>
</module>
<module name="AnnotationLocation">
<property name="tokens" value="CLASS_DEF, INTERFACE_DEF, ENUM_DEF, METHOD_DEF, CTOR_DEF"/>
</module>
<module name="AnnotationLocation">
<property name="tokens" value="VARIABLE_DEF"/>
<property name="allowSamelineMultipleAnnotations" value="true"/>
</module>
<module name="NonEmptyAtclauseDescription"/>
<module name="JavadocTagContinuationIndentation"/>
<module name="SummaryJavadoc">
<property name="forbiddenSummaryFragments" value="^@return the *|^This method returns |^A [{]@code [a-zA-Z0-9]+[}]( is a )"/>
</module>
<module name="JavadocParagraph"/>
<module name="AtclauseOrder">
<property name="tagOrder" value="@param, @return, @throws, @deprecated"/>
<property name="target" value="CLASS_DEF, INTERFACE_DEF, ENUM_DEF, METHOD_DEF, CTOR_DEF, VARIABLE_DEF"/>
</module>
<module name="JavadocMethod">
<property name="scope" value="public"/>
<property name="allowMissingParamTags" value="true"/>
<property name="allowMissingThrowsTags" value="true"/>
<property name="allowMissingReturnTag" value="true"/>
<property name="minLineCount" value="2"/>
<property name="allowedAnnotations" value="Override, Test"/>
<property name="allowThrowsTagsForSubclasses" value="true"/>
</module>
<module name="MethodName">
<property name="format" value="^[a-z][a-z0-9][a-zA-Z0-9_]*$"/>
<message key="name.invalidPattern" value="Method name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="SingleLineJavadoc">
<property name="ignoreInlineTags" value="false"/>
</module>
<module name="EmptyCatchBlock">
<property name="exceptionVariableName" value="expected"/>
</module>
<module name="CommentsIndentation"/>
</module>
</module>

View File

@ -19,7 +19,7 @@ public class CodegenOperation {
isRestful;
public String path, operationId, returnType, httpMethod, returnBaseType,
returnContainer, summary, unescapedNotes, notes, baseName, defaultResponse, discriminator;
public List<Map<String, String>> consumes, produces;
public List<Map<String, String>> consumes, produces, prioritizedContentTypes;
public CodegenParameter bodyParam;
public List<CodegenParameter> allParams = new ArrayList<CodegenParameter>();
public List<CodegenParameter> bodyParams = new ArrayList<CodegenParameter>();
@ -275,6 +275,8 @@ public class CodegenOperation {
return false;
if (nickname != null ? !nickname.equals(that.nickname) : that.nickname != null)
return false;
if ( prioritizedContentTypes != null ? !prioritizedContentTypes.equals(that.prioritizedContentTypes) : that.prioritizedContentTypes != null )
return false;
return operationIdLowerCase != null ? operationIdLowerCase.equals(that.operationIdLowerCase) : that.operationIdLowerCase == null;
}
@ -325,6 +327,7 @@ public class CodegenOperation {
result = 31 * result + (externalDocs != null ? externalDocs.hashCode() : 0);
result = 31 * result + (vendorExtensions != null ? vendorExtensions.hashCode() : 0);
result = 31 * result + (nickname != null ? nickname.hashCode() : 0);
result = 31 * result + (prioritizedContentTypes != null ? prioritizedContentTypes.hashCode() : 0);
result = 31 * result + (operationIdLowerCase != null ? operationIdLowerCase.hashCode() : 0);
return result;
}

View File

@ -33,7 +33,7 @@ public final class CodegenConfiguratorUtils {
public static void applyImportMappingsKvp(String importMappings, CodegenConfigurator configurator) {
final Map<String, String> map = createMapFromKeyValuePairs(importMappings);
for (Map.Entry<String, String> entry : map.entrySet()) {
configurator.addImportMapping(entry.getKey(), entry.getValue());
configurator.addImportMapping(entry.getKey().trim(), entry.getValue().trim());
}
}

View File

@ -45,6 +45,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
public static final String FULL_JAVA_UTIL = "fullJavaUtil";
public static final String DEFAULT_LIBRARY = "<default>";
public static final String DATE_LIBRARY = "dateLibrary";
public static final String SUPPORT_JAVA6 = "supportJava6";
protected String dateLibrary = "joda";
protected String invokerPackage = "io.swagger";
@ -63,6 +64,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
protected boolean hideGenerationTimestamp = false;
protected String apiDocPath = "docs/";
protected String modelDocPath = "docs/";
protected boolean supportJava6= false;
public AbstractJavaCodegen() {
super();
@ -138,6 +140,12 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
public void processOpts() {
super.processOpts();
if (additionalProperties.containsKey(SUPPORT_JAVA6)) {
this.setSupportJava6(Boolean.valueOf(additionalProperties.get(SUPPORT_JAVA6).toString()));
}
additionalProperties.put(SUPPORT_JAVA6, supportJava6);
if (additionalProperties.containsKey(CodegenConstants.INVOKER_PACKAGE)) {
this.setInvokerPackage((String) additionalProperties.get(CodegenConstants.INVOKER_PACKAGE));
} else if (additionalProperties.containsKey(CodegenConstants.API_PACKAGE)) {
@ -363,6 +371,10 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
return name;
}
if(startsWithTwoUppercaseLetters(name)){
name = name.substring(0, 2).toLowerCase() + name.substring(2);
}
// camelize (lower first character) the variable name
// pet_id => petId
name = camelize(name, true);
@ -375,6 +387,14 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
return name;
}
private boolean startsWithTwoUppercaseLetters(String name) {
boolean startsWithTwoUppercaseLetters = false;
if(name.length() > 1) {
startsWithTwoUppercaseLetters = name.substring(0, 2).equals(name.substring(0, 2).toUpperCase());
}
return startsWithTwoUppercaseLetters;
}
@Override
public String toParamName(String name) {
// to avoid conflicts with 'callback' parameter for async call
@ -935,6 +955,10 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
return sb.toString();
}
public void setSupportJava6(boolean value) {
this.supportJava6 = value;
}
public String toRegularExpression(String pattern) {
return escapeText(pattern);
}

View File

@ -200,10 +200,4 @@ public abstract class AbstractJavaJAXRSServerCodegen extends AbstractJavaCodegen
private String implFileFolder(String output) {
return outputFolder + "/" + output + "/" + apiPackage().replace('.', '/');
}
@Override
public boolean shouldOverwrite(String filename) {
return super.shouldOverwrite(filename) && !filename.endsWith("ServiceImpl.java") && !filename.endsWith("ServiceFactory.java");
}
}

View File

@ -158,6 +158,26 @@ public class HaskellServantCodegen extends DefaultCodegen implements CodegenConf
return name + "_";
}
public String firstLetterToUpper(String word) {
if (word.length() == 0) {
return word;
} else if (word.length() == 1) {
return word.substring(0, 1).toUpperCase();
} else {
return word.substring(0, 1).toUpperCase() + word.substring(1);
}
}
public String firstLetterToLower(String word) {
if (word.length() == 0) {
return word;
} else if (word.length() == 1) {
return word.substring(0, 1).toLowerCase();
} else {
return word.substring(0, 1).toLowerCase() + word.substring(1);
}
}
@Override
public void preprocessSwagger(Swagger swagger) {
// From the title, compute a reasonable name for the package and the API
@ -185,7 +205,7 @@ public class HaskellServantCodegen extends DefaultCodegen implements CodegenConf
// The API name is made by appending the capitalized words of the title
List<String> wordsCaps = new ArrayList<String>();
for (String word : words) {
wordsCaps.add(word.substring(0, 1).toUpperCase() + word.substring(1));
wordsCaps.add(firstLetterToUpper(word));
}
String apiName = joinStrings("", wordsCaps);
@ -196,7 +216,7 @@ public class HaskellServantCodegen extends DefaultCodegen implements CodegenConf
additionalProperties.put("title", apiName);
additionalProperties.put("titleLower", apiName.substring(0, 1).toLowerCase() + apiName.substring(1));
additionalProperties.put("titleLower", firstLetterToLower(apiName));
additionalProperties.put("package", cabalName);
// Due to the way servant resolves types, we need a high context stack limit

View File

@ -10,14 +10,16 @@ import org.slf4j.LoggerFactory;
import java.io.File;
import java.util.*;
import java.util.regex.Pattern;
public class JavaClientCodegen extends AbstractJavaCodegen implements BeanValidationFeatures {
static final String MEDIA_TYPE = "mediaType";
@SuppressWarnings("hiding")
private static final Logger LOGGER = LoggerFactory.getLogger(JavaClientCodegen.class);
public static final String USE_RX_JAVA = "useRxJava";
public static final String PARCELABLE_MODEL = "parcelableModel";
public static final String SUPPORT_JAVA6 = "supportJava6";
public static final String RETROFIT_1 = "retrofit";
public static final String RETROFIT_2 = "retrofit2";
@ -25,7 +27,6 @@ public class JavaClientCodegen extends AbstractJavaCodegen implements BeanValida
protected String gradleWrapperPackage = "gradle.wrapper";
protected boolean useRxJava = false;
protected boolean parcelableModel = false;
protected boolean supportJava6= false;
protected boolean useBeanValidation = false;
public JavaClientCodegen() {
@ -94,11 +95,6 @@ public class JavaClientCodegen extends AbstractJavaCodegen implements BeanValida
additionalProperties.put(USE_BEANVALIDATION, useBeanValidationProp);
}
if (additionalProperties.containsKey(SUPPORT_JAVA6)) {
this.setSupportJava6(Boolean.valueOf(additionalProperties.get(SUPPORT_JAVA6).toString()));
}
additionalProperties.put(SUPPORT_JAVA6, supportJava6);
final String invokerFolder = (sourceFolder + '/' + invokerPackage).replace(".", "/");
final String authFolder = (sourceFolder + '/' + invokerPackage + ".auth").replace(".", "/");
@ -188,11 +184,12 @@ public class JavaClientCodegen extends AbstractJavaCodegen implements BeanValida
List<CodegenOperation> ops = (List<CodegenOperation>) operations.get("operation");
for (CodegenOperation operation : ops) {
if (operation.hasConsumes == Boolean.TRUE) {
Map<String, String> firstType = operation.consumes.get(0);
if (firstType != null) {
if ("multipart/form-data".equals(firstType.get("mediaType"))) {
if ( isMultipartType(operation.consumes) ) {
operation.isMultipart = Boolean.TRUE;
}
else {
operation.prioritizedContentTypes = prioritizeContentTypes(operation.consumes);
}
}
if (operation.returnType == null) {
@ -206,6 +203,54 @@ public class JavaClientCodegen extends AbstractJavaCodegen implements BeanValida
return objs;
}
/**
* Prioritizes consumes mime-type list by moving json-vendor and json mime-types up front, but
* otherwise preserves original consumes definition order.
* [application/vnd...+json,... application/json, ..as is..]
*
* @param consumes consumes mime-type list
* @return
*/
static List<Map<String, String>> prioritizeContentTypes(List<Map<String, String>> consumes) {
if ( consumes.size() <= 1 )
return consumes;
List<Map<String, String>> prioritizedContentTypes = new ArrayList<>(consumes.size());
List<Map<String, String>> jsonVendorMimeTypes = new ArrayList<>(consumes.size());
List<Map<String, String>> jsonMimeTypes = new ArrayList<>(consumes.size());
for ( Map<String, String> consume : consumes) {
if ( isJsonVendorMimeType(consume.get(MEDIA_TYPE))) {
jsonVendorMimeTypes.add(consume);
}
else if ( isJsonMimeType(consume.get(MEDIA_TYPE))) {
jsonMimeTypes.add(consume);
}
else
prioritizedContentTypes.add(consume);
consume.put("hasMore", "true");
}
prioritizedContentTypes.addAll(0, jsonMimeTypes);
prioritizedContentTypes.addAll(0, jsonVendorMimeTypes);
prioritizedContentTypes.get(prioritizedContentTypes.size()-1).put("hasMore", null);
return prioritizedContentTypes;
}
private static boolean isMultipartType(List<Map<String, String>> consumes) {
Map<String, String> firstType = consumes.get(0);
if (firstType != null) {
if ("multipart/form-data".equals(firstType.get(MEDIA_TYPE))) {
return true;
}
}
return false;
}
@Override
public void postProcessModelProperty(CodegenModel model, CodegenProperty property) {
super.postProcessModelProperty(model, property);
@ -256,12 +301,32 @@ public class JavaClientCodegen extends AbstractJavaCodegen implements BeanValida
this.parcelableModel = parcelableModel;
}
public void setSupportJava6(boolean value) {
this.supportJava6 = value;
}
public void setUseBeanValidation(boolean useBeanValidation) {
this.useBeanValidation = useBeanValidation;
}
final private static Pattern JSON_MIME_PATTERN = Pattern.compile("(?i)application\\/json(;.*)?");
final private static Pattern JSON_VENDOR_MIME_PATTERN = Pattern.compile("(?i)application\\/vnd.(.*)+json(;.*)?");
/**
* Check if the given MIME is a JSON MIME.
* JSON MIME examples:
* application/json
* application/json; charset=UTF8
* APPLICATION/JSON
*/
static boolean isJsonMimeType(String mime) {
return mime != null && ( JSON_MIME_PATTERN.matcher(mime).matches());
}
/**
* Check if the given MIME is a JSON Vendor MIME.
* JSON MIME examples:
* application/vnd.mycompany+json
* application/vnd.mycompany.resourceA.version1+json
*/
static boolean isJsonVendorMimeType(String mime) {
return mime != null && JSON_VENDOR_MIME_PATTERN.matcher(mime).matches();
}
}

View File

@ -6,12 +6,10 @@ import io.swagger.codegen.CodegenProperty;
import java.io.File;
public class JavaJAXRSCXFCDIServerCodegen extends JavaJAXRSSpecServerCodegen
{
public JavaJAXRSCXFCDIServerCodegen()
{
public class JavaJAXRSCXFCDIServerCodegen extends JavaJAXRSSpecServerCodegen {
public JavaJAXRSCXFCDIServerCodegen() {
outputFolder = "generated-code/JavaJaxRS-CXF-CDI";
artifactId = "swagger-jaxrs-cxf-cdi-server";
sourceFolder = "src" + File.separator + "gen" + File.separator + "java";
// Three API templates to support CDI injection
@ -26,18 +24,14 @@ public class JavaJAXRSCXFCDIServerCodegen extends JavaJAXRSSpecServerCodegen
}
@Override
public String getName()
{
public String getName() {
return "jaxrs-cxf-cdi";
}
@Override
public void processOpts()
{
public void processOpts() {
super.processOpts();
supportingFiles.clear(); // Don't need extra files provided by AbstractJAX-RS & Java Codegen
writeOptional(outputFolder, new SupportingFile("pom.mustache", "", "pom.xml"));
}
@ -50,8 +44,7 @@ public class JavaJAXRSCXFCDIServerCodegen extends JavaJAXRSSpecServerCodegen
}
@Override
public String getHelp()
{
public String getHelp() {
return "Generates a Java JAXRS Server according to JAXRS 2.0 specification, assuming an Apache CXF runtime and a Java EE runtime with CDI enabled.";
}

View File

@ -24,7 +24,6 @@ public class JavaJAXRSSpecServerCodegen extends AbstractJavaJAXRSServerCodegen
public JavaJAXRSSpecServerCodegen()
{
super();
sourceFolder = "src/main/java";
invokerPackage = "io.swagger.api";
artifactId = "swagger-jaxrs-server";
outputFolder = "generated-code/JavaJaxRS-Spec";

View File

@ -44,7 +44,7 @@ public class JavaJerseyServerCodegen extends AbstractJavaJAXRSServerCodegen {
library.setDefault(DEFAULT_LIBRARY);
cliOptions.add(library);
cliOptions.add(CliOption.newBoolean(SUPPORT_JAVA6, "Whether to support Java6 with the Jersey1/2 library."));
}
@Override
@ -110,6 +110,7 @@ public class JavaJerseyServerCodegen extends AbstractJavaJAXRSServerCodegen {
supportingFiles.add(new SupportingFile("StringUtil.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "StringUtil.java"));
}
@Override
public Map<String, Object> postProcessModelsEnum(Map<String, Object> objs) {
objs = super.postProcessModelsEnum(objs);

View File

@ -18,7 +18,7 @@ public class JavaMSF4JServerCodegen extends AbstractJavaJAXRSServerCodegen {
public JavaMSF4JServerCodegen() {
super();
outputFolder = "generated-code/JavaJaxRS-Jersey";
outputFolder = "generated-code/JavaJaxRS-MSF4J";
apiTemplateFiles.put("apiService.mustache", ".java");
apiTemplateFiles.put("apiServiceImpl.mustache", ".java");
apiTemplateFiles.put("apiServiceFactory.mustache", ".java");

View File

@ -16,7 +16,7 @@ public class JavaResteasyServerCodegen extends AbstractJavaJAXRSServerCodegen {
artifactId = "swagger-jaxrs-resteasy-server";
outputFolder = "generated-code/javaJaxRS";
outputFolder = "generated-code/JavaJaxRS-Resteasy";
apiTemplateFiles.put("apiService.mustache", ".java");
apiTemplateFiles.put("apiServiceImpl.mustache", ".java");
apiTemplateFiles.put("apiServiceFactory.mustache", ".java");

View File

@ -21,8 +21,11 @@ import java.util.Map;
import org.apache.commons.lang3.StringUtils;
public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig {
public static final String PACKAGE_URL = "packageUrl";
protected String packageName;
protected String packageVersion;
protected String packageUrl;
protected String apiDocPath = "docs/";
protected String modelDocPath = "docs/";
@ -112,6 +115,7 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig
.defaultValue("swagger_client"));
cliOptions.add(new CliOption(CodegenConstants.PACKAGE_VERSION, "python package version.")
.defaultValue("1.0.0"));
cliOptions.add(new CliOption(PACKAGE_URL, "python package URL."));
cliOptions.add(CliOption.newBoolean(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG,
CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG_DESC).defaultValue(Boolean.TRUE.toString()));
cliOptions.add(new CliOption(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "hides the timestamp when files were generated")
@ -156,6 +160,10 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig
additionalProperties.put("apiDocPath", apiDocPath);
additionalProperties.put("modelDocPath", modelDocPath);
if (additionalProperties.containsKey(PACKAGE_URL)) {
setPackageUrl((String) additionalProperties.get(PACKAGE_URL));
}
String swaggerFolder = packageName;
modelPackage = swaggerFolder + File.separatorChar + "models";
@ -480,6 +488,10 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig
this.packageVersion = packageVersion;
}
public void setPackageUrl(String packageUrl) {
this.packageUrl = packageUrl;
}
/**
* Generate Python package name from String `packageName`
*

View File

@ -17,6 +17,7 @@ public class SpringCodegen extends AbstractJavaCodegen {
public static final String SINGLE_CONTENT_TYPES = "singleContentTypes";
public static final String JAVA_8 = "java8";
public static final String ASYNC = "async";
public static final String RESPONSE_WRAPPER = "responseWrapper";
public static final String SPRING_MVC_LIBRARY = "spring-mvc";
public static final String SPRING_CLOUD_LIBRARY = "spring-cloud";
@ -27,6 +28,7 @@ public class SpringCodegen extends AbstractJavaCodegen {
protected boolean singleContentTypes = false;
protected boolean java8 = false;
protected boolean async = false;
protected String responseWrapper = "";
public SpringCodegen() {
super();
@ -51,6 +53,7 @@ public class SpringCodegen extends AbstractJavaCodegen {
cliOptions.add(CliOption.newBoolean(SINGLE_CONTENT_TYPES, "Whether to select only one produces/consumes content-type by operation."));
cliOptions.add(CliOption.newBoolean(JAVA_8, "use java8 default interface"));
cliOptions.add(CliOption.newBoolean(ASYNC, "use async Callable controllers"));
cliOptions.add(new CliOption(RESPONSE_WRAPPER, "wrap the responses in given type (Future,Callable,CompletableFuture,ListenableFuture,DeferredResult,HystrixCommand,RxObservable,RxSingle or fully qualified type)"));
supportedLibraries.put(DEFAULT_LIBRARY, "Spring-boot Server application using the SpringFox integration.");
supportedLibraries.put(SPRING_MVC_LIBRARY, "Spring-MVC Server application using the SpringFox integration.");
@ -117,6 +120,10 @@ public class SpringCodegen extends AbstractJavaCodegen {
this.setAsync(Boolean.valueOf(additionalProperties.get(ASYNC).toString()));
}
if (additionalProperties.containsKey(RESPONSE_WRAPPER)) {
this.setResponseWrapper((String) additionalProperties.get(RESPONSE_WRAPPER));
}
supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml"));
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
@ -173,11 +180,43 @@ public class SpringCodegen extends AbstractJavaCodegen {
if (this.java8) {
additionalProperties.put("javaVersion", "1.8");
additionalProperties.put("jdk8", "true");
if (this.async) {
additionalProperties.put(RESPONSE_WRAPPER, "CompletableFuture");
}
typeMapping.put("date", "LocalDate");
typeMapping.put("DateTime", "OffsetDateTime");
importMapping.put("LocalDate", "java.time.LocalDate");
importMapping.put("OffsetDateTime", "java.time.OffsetDateTime");
} else if (this.async) {
additionalProperties.put(RESPONSE_WRAPPER, "Callable");
}
// Some well-known Spring or Spring-Cloud response wrappers
switch (this.responseWrapper) {
case "Future":
case "Callable":
case "CompletableFuture":
additionalProperties.put(RESPONSE_WRAPPER, "java.util.concurrent" + this.responseWrapper);
break;
case "ListenableFuture":
additionalProperties.put(RESPONSE_WRAPPER, "org.springframework.util.concurrent.ListenableFuture");
break;
case "DeferredResult":
additionalProperties.put(RESPONSE_WRAPPER, "org.springframework.web.context.request.DeferredResult");
break;
case "HystrixCommand":
additionalProperties.put(RESPONSE_WRAPPER, "com.netflix.hystrix.HystrixCommand");
break;
case "RxObservable":
additionalProperties.put(RESPONSE_WRAPPER, "rx.Observable");
break;
case "RxSingle":
additionalProperties.put(RESPONSE_WRAPPER, "rx.Single");
break;
default:
break;
}
}
@Override
@ -355,6 +394,8 @@ public class SpringCodegen extends AbstractJavaCodegen {
public void setAsync(boolean async) { this.async = async; }
public void setResponseWrapper(String responseWrapper) { this.responseWrapper = responseWrapper; }
@Override
public void postProcessModelProperty(CodegenModel model, CodegenProperty property) {
super.postProcessModelProperty(model, property);

View File

@ -65,6 +65,12 @@ public class StaticHtml2Generator extends DefaultCodegen implements CodegenConfi
return "html2";
}
@Override
public String escapeText(String input) {
// newline escaping disabled for HTML documentation for markdown to work correctly
return input;
}
@Override
public String getHelp() {
return "Generates a static HTML file.";

View File

@ -60,6 +60,12 @@ public class StaticHtmlGenerator extends DefaultCodegen implements CodegenConfig
importMapping = new HashMap<String, String>();
}
@Override
public String escapeText(String input) {
// newline escaping disabled for HTML documentation for markdown to work correctly
return input;
}
@Override
public CodegenType getTag() {
return CodegenType.DOCUMENTATION;

View File

@ -102,7 +102,7 @@ public class Swift3Codegen extends DefaultCodegen implements CodegenConfig {
);
reservedWords = new HashSet<>(
Arrays.asList(
"Int", "Int32", "Int64", "Int64", "Float", "Double", "Bool", "Void", "String", "Character", "AnyObject", "Any",
"Int", "Int32", "Int64", "Int64", "Float", "Double", "Bool", "Void", "String", "Character", "AnyObject", "Any", "Error", "URL",
"class", "Class", "break", "as", "associativity", "deinit", "case", "dynamicType", "convenience", "enum", "continue",
"false", "dynamic", "extension", "default", "is", "didSet", "func", "do", "nil", "final", "import", "else",
"self", "get", "init", "fallthrough", "Self", "infix", "internal", "for", "super", "inout", "let", "if",
@ -421,6 +421,21 @@ public class Swift3Codegen extends DefaultCodegen implements CodegenConfig {
return name;
}
@Override
public CodegenModel fromModel(String name, Model model, Map<String, Model> allDefinitions) {
CodegenModel codegenModel = super.fromModel(name, model, allDefinitions);
if(codegenModel.description != null) {
codegenModel.imports.add("ApiModel");
}
if (allDefinitions != null && codegenModel.parentSchema != null) {
final Model parentModel = allDefinitions.get(codegenModel.parentSchema);
final CodegenModel parentCodegenModel = super.fromModel(codegenModel.parent, parentModel);
codegenModel = Swift3Codegen.reconcileProperties(codegenModel, parentCodegenModel);
}
return codegenModel;
}
@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'.
@ -546,4 +561,47 @@ public class Swift3Codegen extends DefaultCodegen implements CodegenConfig {
return input.replace("*/", "*_/").replace("/*", "/_*");
}
private static CodegenModel reconcileProperties(CodegenModel codegenModel, CodegenModel parentCodegenModel) {
// To support inheritance in this generator, we will analyze
// the parent and child models, look for properties that match, and remove
// them from the child models and leave them in the parent.
// Because the child models extend the parents, the properties will be available via the parent.
// Get the properties for the parent and child models
final List<CodegenProperty> parentModelCodegenProperties = parentCodegenModel.vars;
List<CodegenProperty> codegenProperties = codegenModel.vars;
codegenModel.allVars = new ArrayList<CodegenProperty>(codegenProperties);
codegenModel.parentVars = parentCodegenModel.allVars;
// Iterate over all of the parent model properties
boolean removedChildProperty = false;
for (CodegenProperty parentModelCodegenProperty : parentModelCodegenProperties) {
// Now that we have found a prop in the parent class,
// and search the child class for the same prop.
Iterator<CodegenProperty> iterator = codegenProperties.iterator();
while (iterator.hasNext()) {
CodegenProperty codegenProperty = iterator.next();
if (codegenProperty.equals(parentModelCodegenProperty)) {
// We found a property in the child class that is
// a duplicate of the one in the parent, so remove it.
iterator.remove();
removedChildProperty = true;
}
}
}
if(removedChildProperty) {
// If we removed an entry from this model's vars, we need to ensure hasMore is updated
int count = 0, numVars = codegenProperties.size();
for(CodegenProperty codegenProperty : codegenProperties) {
count += 1;
codegenProperty.hasMore = (count < numVars) ? true : null;
}
codegenModel.vars = codegenProperties;
}
return codegenModel;
}
}

View File

@ -635,6 +635,8 @@ public class ApiClient {
response = invocationBuilder.put(entity);
} else if ("DELETE".equals(method)) {
response = invocationBuilder.delete();
} else if ("PATCH".equals(method)) {
response = invocationBuilder.header("X-HTTP-Method-Override", "PATCH").post(entity);
} else {
throw new ApiException(500, "unknown method type " + method);
}

View File

@ -29,6 +29,15 @@ public interface {{classname}} {
*/
{{#formParams}}{{#-first}}
{{#isMultipart}}@retrofit2.http.Multipart{{/isMultipart}}{{^isMultipart}}@retrofit2.http.FormUrlEncoded{{/isMultipart}}{{/-first}}{{/formParams}}
{{^formParams}}
{{#prioritizedContentTypes}}
{{#-first}}
@Headers({
"Content-Type:{{mediaType}}"
})
{{/-first}}
{{/prioritizedContentTypes}}
{{/formParams}}
@{{httpMethod}}("{{path}}")
{{#useRxJava}}Observable{{/useRxJava}}{{^useRxJava}}Call{{/useRxJava}}<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Object{{/returnType}}> {{operationId}}({{^allParams}});{{/allParams}}
{{#allParams}}{{>libraries/retrofit2/queryParams}}{{>libraries/retrofit2/pathParams}}{{>libraries/retrofit2/headerParams}}{{>libraries/retrofit2/bodyParams}}{{>libraries/retrofit2/formParams}}{{#hasMore}}, {{/hasMore}}{{^hasMore}}

View File

@ -180,6 +180,7 @@
<artifactId>migbase64</artifactId>
<version>2.2</version>
</dependency>
{{#supportJava6}}
<dependency>
<groupId>org.apache.commons</groupId>

View File

@ -0,0 +1,23 @@
/*
* {{{appName}}}
* {{{appDescription}}}
*
* {{#version}}OpenAPI spec version: {{{version}}}{{/version}}
* {{#infoEmail}}Contact: {{{infoEmail}}}{{/infoEmail}}
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*
* 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.
*/

View File

@ -1,6 +1,13 @@
{{>licenseInfo}}
package {{package}};
{{^supportJava6}}
import java.util.Objects;
{{/supportJava6}}
{{#supportJava6}}
import org.apache.commons.lang3.ObjectUtils;
{{/supportJava6}}
{{#imports}}import {{import}};
{{/imports}}
{{#serializableModel}}
@ -9,11 +16,6 @@ import java.io.Serializable;
{{#models}}
{{#model}}
{{#isEnum}}
{{>enumOuterClass}}
{{/isEnum}}
{{^isEnum}}
{{>pojo}}
{{/isEnum}}
{{#isEnum}}{{>modelEnum}}{{/isEnum}}{{^isEnum}}{{>pojo}}{{/isEnum}}
{{/model}}
{{/models}}

View File

@ -0,0 +1,43 @@
{{#jackson}}
import com.fasterxml.jackson.annotation.JsonCreator;
{{/jackson}}
/**
* {{^description}}Gets or Sets {{{name}}}{{/description}}{{#description}}{{{description}}}{{/description}}
*/
public enum {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} {
{{#gson}}
{{#allowableValues}}{{#enumVars}}
@SerializedName({{#isInteger}}"{{/isInteger}}{{#isDouble}}"{{/isDouble}}{{#isLong}}"{{/isLong}}{{#isFloat}}"{{/isFloat}}{{{value}}}{{#isInteger}}"{{/isInteger}}{{#isDouble}}"{{/isDouble}}{{#isLong}}"{{/isLong}}{{#isFloat}}"{{/isFloat}})
{{{name}}}({{{value}}}){{^-last}},
{{/-last}}{{#-last}};{{/-last}}{{/enumVars}}{{/allowableValues}}
{{/gson}}
{{^gson}}
{{#allowableValues}}{{#enumVars}}
{{{name}}}({{{value}}}){{^-last}},
{{/-last}}{{#-last}};{{/-last}}{{/enumVars}}{{/allowableValues}}
{{/gson}}
private {{{dataType}}} value;
{{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}({{{dataType}}} value) {
this.value = value;
}
@Override
public String toString() {
return String.valueOf(value);
}
{{#jackson}}
@JsonCreator
public static {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} fromValue(String text) {
for ({{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} b : {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}.values()) {
if (String.valueOf(b.value).equals(text)) {
return b;
}
}
return null;
}
{{/jackson}}
}

View File

@ -79,6 +79,7 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#seriali
{{/vars}}
{{^supportJava6}}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
@ -99,6 +100,30 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#seriali
return Objects.hash({{#vars}}{{name}}{{#hasMore}}, {{/hasMore}}{{/vars}}{{#parent}}{{#hasVars}}, {{/hasVars}}super.hashCode(){{/parent}});
}
{{/supportJava6}}
{{#supportJava6}}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}{{#hasVars}}
{{classname}} {{classVarName}} = ({{classname}}) o;
return {{#vars}}ObjectUtils.equals(this.{{name}}, {{classVarName}}.{{name}}){{#hasMore}} &&
{{/hasMore}}{{/vars}}{{#parent}} &&
super.equals(o){{/parent}};{{/hasVars}}{{^hasVars}}
return true;{{/hasVars}}
}
@Override
public int hashCode() {
return ObjectUtils.hashCodeMulti({{#vars}}{{name}}{{#hasMore}}, {{/hasMore}}{{/vars}}{{#parent}}{{#hasVars}}, {{/hasVars}}super.hashCode(){{/parent}});
}
{{/supportJava6}}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();

View File

@ -124,6 +124,27 @@
<artifactId>jersey-media-multipart</artifactId>
<version>${jersey2-version}</version>
</dependency>
<!-- Base64 encoding that works in both JVM and Android -->
<dependency>
<groupId>com.brsanthu</groupId>
<artifactId>migbase64</artifactId>
<version>2.2</version>
</dependency>
{{#supportJava6}}
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons_lang3_version}</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons_io_version}</version>
</dependency>
{{/supportJava6}}
</dependencies>
<repositories>
<repository>
@ -141,6 +162,10 @@
<swagger-core-version>1.5.9</swagger-core-version>
<jetty-version>9.2.9.v20150224</jetty-version>
<jersey2-version>2.22.2</jersey2-version>
{{#supportJava6}}
<commons_io_version>2.5</commons_io_version>
<commons_lang3_version>3.5</commons_lang3_version>
{{/supportJava6}}
<junit-version>4.12</junit-version>
<logback-version>1.1.7</logback-version>
<servlet-api-version>2.5</servlet-api-version>

View File

@ -43,7 +43,7 @@ public interface {{classname}} {
produces = { {{#produces}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }, {{/hasProduces}}{{#hasConsumes}}
consumes = { {{#consumes}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} },{{/hasConsumes}}{{/singleContentTypes}}
method = RequestMethod.{{httpMethod}})
{{#jdk8}}default {{/jdk8}}{{#async}}{{^jdk8}}Callable{{/jdk8}}{{#jdk8}}CompletableFuture<{{/jdk8}}{{/async}}ResponseEntity<{{>returnTypes}}>{{#async}}>{{/async}} {{operationId}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}},
{{#jdk8}}default {{/jdk8}}{{#responseWrapper}}{{.}}<{{/responseWrapper}}ResponseEntity<{{>returnTypes}}>{{#responseWrapper}}>{{/responseWrapper}} {{operationId}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}},
{{/hasMore}}{{/allParams}}){{^jdk8}};{{/jdk8}}{{#jdk8}} {
// do some magic!
return {{#async}}CompletableFuture.completedFuture({{/async}}new ResponseEntity<{{>returnTypes}}>(HttpStatus.OK){{#async}}){{/async}};

View File

@ -14,7 +14,7 @@
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.6.RELEASE</version>
<version>1.4.1.RELEASE</version>
</parent>
<build>
<sourceDirectory>src/main/java</sourceDirectory>
@ -25,7 +25,7 @@
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-parent</artifactId>
<version>Brixton.SR2</version>
<version>Camden.SR1</version>
<type>pom</type>
<scope>import</scope>
</dependency>

View File

@ -4,7 +4,7 @@ description: {{pubDescription}}
dependencies:
http: '>=0.11.1 <0.12.0'
dartson: "^0.2.4"
intl: "^0.12.4+2"
intl: ">=0.12.4"
dev_dependencies:
guinness: '^0.1.17'

View File

@ -22,7 +22,7 @@ setup(
version=VERSION,
description="{{appName}}",
author_email="{{infoEmail}}",
url="{{infoUrl}}",
url="{{packageUrl}}",
keywords=["Swagger", "{{appName}}"],
install_requires=REQUIRES,
packages=find_packages(),

View File

@ -100,7 +100,7 @@ open class AlamofireRequestBuilder<T>: RequestBuilder<T> {
if stringResponse.result.isFailure {
completion(
nil,
ErrorResponse.Error(stringResponse.response?.statusCode ?? 500, stringResponse.data, stringResponse.result.error!)
ErrorResponse.Error(stringResponse.response?.statusCode ?? 500, stringResponse.data, stringResponse.result.error as Error!)
)
return
}
@ -161,6 +161,13 @@ open class AlamofireRequestBuilder<T>: RequestBuilder<T> {
return
}
// handle HTTP 204 No Content
// NSNull would crash decoders
if response.response?.statusCode == 204 && response.result.value is NSNull{
completion(nil, nil)
return;
}
if () is T {
completion(Response(response: response.response!, body: (() as! T)), nil)
return

View File

@ -44,6 +44,15 @@ class Decoders {
decoders[key] = { decoder($0) as AnyObject }
}
static func decode<T>(clazz: T.Type, discriminator: String, source: AnyObject) -> T {
let key = discriminator;
if let decoder = decoders[key] {
return decoder(source) as! T
} else {
fatalError("Source \(source) is not convertible to type \(clazz): Maybe swagger file is insufficient")
}
}
static func decode<T>(clazz: [T].Type, source: AnyObject) -> [T] {
let array = source as! [AnyObject]
return array.map { Decoders.decode(clazz: T.self, source: $0) }
@ -159,14 +168,21 @@ class Decoders {
fatalError("Source \(source) is not convertible to enum type {{classname}}: Maybe swagger file is insufficient")
{{/isEnum}}
{{^isEnum}}
{{#vars.isEmpty}}
{{#allVars.isEmpty}}
if let source = source as? {{dataType}} {
return source
}
fatalError("Source \(source) is not convertible to typealias {{classname}}: Maybe swagger file is insufficient")
{{/vars.isEmpty}}
{{^vars.isEmpty}}
{{/allVars.isEmpty}}
{{^allVars.isEmpty}}
let sourceDictionary = source as! [AnyHashable: Any]
{{#discriminator}}
// Check discriminator to support inheritance
if let discriminator = sourceDictionary["{{discriminator}}"] as? String, discriminator != "{{classname}}"{
return Decoders.decode(clazz: {{classname}}.self, discriminator: discriminator, source: source)
}
{{/discriminator}}
{{#unwrapRequired}}
let instance = {{classname}}({{#requiredVars}}{{^-first}}, {{/-first}}{{#isEnum}}{{name}}: {{classname}}.{{datatypeWithEnum}}(rawValue: (sourceDictionary["{{baseName}}"] as! {{datatype}}))! {{/isEnum}}{{^isEnum}}{{name}}: Decoders.decode(clazz: {{{baseType}}}.self, source: sourceDictionary["{{baseName}}"]! as AnyObject){{/isEnum}}{{/requiredVars}})
{{#optionalVars}}{{#isEnum}}
@ -178,15 +194,15 @@ class Decoders {
{{/optionalVars}}
{{/unwrapRequired}}
{{^unwrapRequired}}
let instance = {{classname}}(){{#vars}}{{#isEnum}}
let instance = {{classname}}(){{#allVars}}{{#isEnum}}
if let {{name}} = sourceDictionary["{{baseName}}"] as? {{datatype}} { {{^isContainer}}
instance.{{name}} = {{classname}}.{{datatypeWithEnum}}(rawValue: ({{name}})){{/isContainer}}{{#isListContainer}}
instance.{{name}} = {{name}}.map ({ {{classname}}.{{enumName}}(rawValue: $0)! }){{/isListContainer}}{{#isMapContainer}}//TODO: handle enum map scenario{{/isMapContainer}}
}{{/isEnum}}
{{^isEnum}}instance.{{name}} = Decoders.decodeOptional(clazz: {{{baseType}}}.self, source: sourceDictionary["{{baseName}}"] as AnyObject?){{/isEnum}}{{/vars}}
{{^isEnum}}instance.{{name}} = Decoders.decodeOptional(clazz: {{{baseType}}}.self, source: sourceDictionary["{{baseName}}"] as AnyObject?){{/isEnum}}{{/allVars}}
{{/unwrapRequired}}
return instance
{{/vars.isEmpty}}
{{/allVars.isEmpty}}
{{/isEnum}}
{{/isArrayModel}}
}{{/model}}

View File

@ -26,7 +26,7 @@ public enum {{classname}}: {{dataType}} {
public typealias {{classname}} = {{dataType}}
{{/vars.isEmpty}}
{{^vars.isEmpty}}
open class {{classname}}: JSONEncodable {
open class {{classname}}: {{#parent}}{{{parent}}}{{/parent}}{{^parent}}JSONEncodable{{/parent}} {
{{#vars}}
{{#isEnum}}
public enum {{enumName}}: {{^isContainer}}{{datatype}}{{/isContainer}}{{#isContainer}}String{{/isContainer}} { {{#allowableValues}}{{#enumVars}}
@ -46,19 +46,20 @@ open class {{classname}}: JSONEncodable {
{{/vars}}
{{^unwrapRequired}}
public init() {}
{{^parent}}public init() {}{{/parent}}
{{/unwrapRequired}}
{{#unwrapRequired}}
public init({{#allVars}}{{^-first}}, {{/-first}}{{name}}: {{#isEnum}}{{datatypeWithEnum}}{{/isEnum}}{{^isEnum}}{{datatype}}{{/isEnum}}{{^required}}?=nil{{/required}}{{/allVars}}) {
{{#allVars}}
{{#vars}}
self.{{name}} = {{name}}
{{/allVars}}
{{/vars}}
{{#parent}}super.init({{#parentVars}}{{^-first}}, {{/-first}}{{name}}: {{name}}{{/parentVars}}){{/parent}}
}
{{/unwrapRequired}}
// MARK: JSONEncodable
func encodeToJSON() -> Any {
var nillableDictionary = [String:Any?](){{#vars}}{{#isNotContainer}}{{#isPrimitiveType}}{{^isEnum}}{{#isInteger}}
{{#parent}}override {{/parent}}open func encodeToJSON() -> Any {
var nillableDictionary = {{#parent}}super.encodeToJSON() as? [String:Any?] ?? {{/parent}}[String:Any?](){{#vars}}{{#isNotContainer}}{{#isPrimitiveType}}{{^isEnum}}{{#isInteger}}
nillableDictionary["{{baseName}}"] = self.{{name}}{{^unwrapRequired}}?{{/unwrapRequired}}{{#unwrapRequired}}{{^required}}?{{/required}}{{/unwrapRequired}}.encodeToJSON(){{/isInteger}}{{#isLong}}
nillableDictionary["{{baseName}}"] = self.{{name}}{{^unwrapRequired}}?{{/unwrapRequired}}{{#unwrapRequired}}{{^required}}?{{/required}}{{/unwrapRequired}}.encodeToJSON(){{/isLong}}{{^isLong}}{{^isInteger}}
nillableDictionary["{{baseName}}"] = self.{{name}}{{/isInteger}}{{/isLong}}{{/isEnum}}{{/isPrimitiveType}}{{#isEnum}}

View File

@ -35,6 +35,21 @@ export class {{classname}} {
}
}
/**
*
* Extends object by coping non-existing properties.
* @param objA object to be extended
* @param objB source object
*/
private extendObj<T1,T2>(objA: T1, objB: T2) {
for(let key in objB){
if(objB.hasOwnProperty(key)){
objA[key] = objB[key];
}
}
return <T1&T2>objA;
}
{{#operation}}
/**
* {{summary}}
@ -157,10 +172,14 @@ export class {{classname}} {
{{#hasFormParams}}
body: formParams.toString(),
{{/hasFormParams}}
search: queryParameters,
responseType: ResponseContentType.Json
search: queryParameters
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = this.extendObj(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}

View File

@ -360,6 +360,32 @@ public class JavaModelTest {
Assert.assertTrue(property.isNotContainer);
}
@Test(description = "convert a model starting with two upper-case letter property names")
public void firstTwoUpperCaseLetterNamesTest() {
final Model model = new ModelImpl()
.description("a model with a property name starting with two upper-case letters")
.property("ATTName", new StringProperty())
.required("ATTName");
final DefaultCodegen codegen = new JavaClientCodegen();
final CodegenModel cm = codegen.fromModel("sample", model);
Assert.assertEquals(cm.name, "sample");
Assert.assertEquals(cm.classname, "Sample");
Assert.assertEquals(cm.vars.size(), 1);
final CodegenProperty property = cm.vars.get(0);
Assert.assertEquals(property.baseName, "ATTName");
Assert.assertEquals(property.getter, "getAtTName");
Assert.assertEquals(property.setter, "setAtTName");
Assert.assertEquals(property.datatype, "String");
Assert.assertEquals(property.name, "atTName");
Assert.assertEquals(property.defaultValue, "null");
Assert.assertEquals(property.baseType, "String");
Assert.assertNull(property.hasMore);
Assert.assertTrue(property.required);
Assert.assertTrue(property.isNotContainer);
}
@Test(description = "convert hyphens per issue 503")
public void hyphensTest() {
final Model model = new ModelImpl()

View File

@ -54,6 +54,8 @@ public class JaxRSServerOptionsTest extends AbstractOptionsTest {
times = 1;
clientCodegen.setDateLibrary("joda");
times = 1;
clientCodegen.setSupportJava6(false);
times = 1;
}};
}
}

View File

@ -0,0 +1,79 @@
package io.swagger.codegen.languages;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.testng.Assert;
import org.testng.annotations.Test;
public class JavaClientCodegenTest {
private static final String VENDOR_MIME_TYPE = "application/vnd.company.v1+json";
private static final String XML_MIME_TYPE = "application/xml";
private static final String JSON_MIME_TYPE = "application/json";
private static final String TEXT_MIME_TYPE = "text/plain";
@Test
public void testJsonMime() {
Assert.assertTrue(JavaClientCodegen.isJsonMimeType(JSON_MIME_TYPE));
Assert.assertFalse(JavaClientCodegen.isJsonMimeType(XML_MIME_TYPE));
Assert.assertFalse(JavaClientCodegen.isJsonMimeType(TEXT_MIME_TYPE));
Assert.assertTrue(JavaClientCodegen.isJsonVendorMimeType("application/vnd.mycompany+json"));
Assert.assertTrue(JavaClientCodegen.isJsonVendorMimeType("application/vnd.mycompany.v1+json"));
Assert.assertTrue(JavaClientCodegen.isJsonVendorMimeType("application/vnd.mycompany.resourceTypeA.version1+json"));
Assert.assertTrue(JavaClientCodegen.isJsonVendorMimeType("application/vnd.mycompany.resourceTypeB.version2+json"));
Assert.assertFalse(JavaClientCodegen.isJsonVendorMimeType("application/v.json"));
}
@Test
public void testContentTypePrioritization() {
Map<String, String> jsonMimeType = new HashMap<>();
jsonMimeType.put(JavaClientCodegen.MEDIA_TYPE, JSON_MIME_TYPE);
Map<String, String> xmlMimeType = new HashMap<>();
xmlMimeType.put(JavaClientCodegen.MEDIA_TYPE, XML_MIME_TYPE);
Map<String, String> vendorMimeType = new HashMap<>();
vendorMimeType.put(JavaClientCodegen.MEDIA_TYPE, VENDOR_MIME_TYPE);
Map<String, String> textMimeType = new HashMap<>();
textMimeType.put(JavaClientCodegen.MEDIA_TYPE, TEXT_MIME_TYPE);
Assert.assertEquals(JavaClientCodegen.prioritizeContentTypes(
Collections.<Map<String,String>>emptyList()), Collections.emptyList());
Assert.assertEquals(JavaClientCodegen.prioritizeContentTypes(Arrays.asList(xmlMimeType)), Arrays.asList(xmlMimeType));
Assert.assertEquals(JavaClientCodegen.prioritizeContentTypes(Arrays.asList(jsonMimeType)), Arrays.asList(jsonMimeType));
Assert.assertEquals(JavaClientCodegen.prioritizeContentTypes(Arrays.asList(vendorMimeType)), Arrays.asList(vendorMimeType));
Assert.assertEquals(JavaClientCodegen.prioritizeContentTypes(Arrays.asList(xmlMimeType, jsonMimeType)),
Arrays.asList(jsonMimeType, xmlMimeType));
Assert.assertEquals(JavaClientCodegen.prioritizeContentTypes(Arrays.asList(jsonMimeType, xmlMimeType)),
Arrays.asList(jsonMimeType, xmlMimeType));
Assert.assertEquals(JavaClientCodegen.prioritizeContentTypes(Arrays.asList(jsonMimeType, vendorMimeType)),
Arrays.asList(vendorMimeType, jsonMimeType));
Assert.assertEquals(JavaClientCodegen.prioritizeContentTypes(Arrays.asList(textMimeType, xmlMimeType)),
Arrays.asList(textMimeType, xmlMimeType));
Assert.assertEquals(JavaClientCodegen.prioritizeContentTypes(Arrays.asList(xmlMimeType, textMimeType)),
Arrays.asList(xmlMimeType, textMimeType));
System.out.println(JavaClientCodegen.prioritizeContentTypes(Arrays.asList(
xmlMimeType,textMimeType, jsonMimeType, vendorMimeType)));
List<Map<String,String>> priContentTypes = JavaClientCodegen.prioritizeContentTypes(Arrays.asList(
xmlMimeType, textMimeType, jsonMimeType, vendorMimeType));
Assert.assertEquals(priContentTypes, Arrays.asList(vendorMimeType, jsonMimeType, xmlMimeType, textMimeType));
for ( int i = 0; i < 3; i++ )
Assert.assertNotNull(priContentTypes.get(i).get("hasMore"));
Assert.assertNull(priContentTypes.get(3).get("hasMore"));
}
}

View File

@ -39,6 +39,7 @@ public class JaxRSServerOptionsProvider implements OptionsProvider {
ImmutableMap.Builder<String, String> builder = new ImmutableMap.Builder<String, String>();
builder.put(CodegenConstants.IMPL_FOLDER, IMPL_FOLDER_VALUE)
.put(JavaClientCodegen.DATE_LIBRARY, "joda") //java.lang.IllegalArgumentException: Multiple entries with same key: dateLibrary=joda and dateLibrary=joda
.put(JavaClientCodegen.SUPPORT_JAVA6, "false")
.put("title", "Test title")
.put(CodegenConstants.MODEL_PACKAGE, MODEL_PACKAGE_VALUE)
.put(CodegenConstants.API_PACKAGE, API_PACKAGE_VALUE)

View File

@ -1,6 +1,7 @@
package io.swagger.codegen.options;
import io.swagger.codegen.CodegenConstants;
import io.swagger.codegen.languages.PythonClientCodegen;
import com.google.common.collect.ImmutableMap;
@ -9,6 +10,7 @@ import java.util.Map;
public class PythonClientOptionsProvider implements OptionsProvider {
public static final String PACKAGE_NAME_VALUE = "swagger_client_python";
public static final String PACKAGE_VERSION_VALUE = "1.0.0-SNAPSHOT";
public static final String PACKAGE_URL_VALUE = "";
@Override
public String getLanguage() {
@ -18,7 +20,8 @@ public class PythonClientOptionsProvider implements OptionsProvider {
@Override
public Map<String, String> createOptions() {
ImmutableMap.Builder<String, String> builder = new ImmutableMap.Builder<String, String>();
return builder.put(CodegenConstants.PACKAGE_NAME, PACKAGE_NAME_VALUE)
return builder.put(PythonClientCodegen.PACKAGE_URL, PACKAGE_URL_VALUE)
.put(CodegenConstants.PACKAGE_NAME, PACKAGE_NAME_VALUE)
.put(CodegenConstants.PACKAGE_VERSION, PACKAGE_VERSION_VALUE)
.put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, "true")
.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "true")

View File

@ -15,6 +15,7 @@ public class SpringOptionsProvider extends JavaOptionsProvider {
public static final String SINGLE_CONTENT_TYPES = "true";
public static final String JAVA_8 = "true";
public static final String ASYNC = "true";
public static final String RESPONSE_WRAPPER = "Callable";
@Override
public String getLanguage() {
@ -32,6 +33,7 @@ public class SpringOptionsProvider extends JavaOptionsProvider {
options.put(SpringCodegen.SINGLE_CONTENT_TYPES, SINGLE_CONTENT_TYPES);
options.put(SpringCodegen.JAVA_8, JAVA_8);
options.put(SpringCodegen.ASYNC, ASYNC);
options.put(SpringCodegen.RESPONSE_WRAPPER, RESPONSE_WRAPPER);
return options;
}

View File

@ -30,6 +30,8 @@ public class PythonClientOptionsTest extends AbstractOptionsTest {
times = 1;
clientCodegen.setPackageVersion(PythonClientOptionsProvider.PACKAGE_VERSION_VALUE);
times = 1;
clientCodegen.setPackageUrl(PythonClientOptionsProvider.PACKAGE_URL_VALUE);
times = 1;
}};
}
}

View File

@ -64,6 +64,8 @@ public class SpringOptionsTest extends JavaClientOptionsTest {
times = 1;
clientCodegen.setAsync(Boolean.valueOf(SpringOptionsProvider.ASYNC));
times = 1;
clientCodegen.setResponseWrapper(SpringOptionsProvider.RESPONSE_WRAPPER);
times = 1;
}};
}

File diff suppressed because it is too large Load Diff

35
pom.xml
View File

@ -1,5 +1,4 @@
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent>
<groupId>org.sonatype.oss</groupId>
<artifactId>oss-parent</artifactId>
@ -68,6 +67,34 @@
<directory>target</directory>
<finalName>${project.artifactId}-${project.version}</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
<version>2.17</version>
<executions>
<execution>
<id>validate</id>
<phase>validate</phase>
<configuration>
<configLocation>google_checkstyle.xml</configLocation>
<encoding>UTF-8</encoding>
<consoleOutput>true</consoleOutput>
<failsOnError>true</failsOnError>
<linkXRef>false</linkXRef>
</configuration>
<goals>
<goal>check</goal>
</goals>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>com.puppycrawl.tools</groupId>
<artifactId>checkstyle</artifactId>
<version>6.19</version>
</dependency>
</dependencies>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
@ -780,10 +807,10 @@
</repository>
</repositories>
<properties>
<swagger-parser-version>1.0.22</swagger-parser-version>
<swagger-parser-version>1.0.23</swagger-parser-version>
<scala-version>2.11.1</scala-version>
<felix-version>2.3.4</felix-version>
<swagger-core-version>1.5.9</swagger-core-version>
<swagger-core-version>1.5.10</swagger-core-version>
<commons-io-version>2.4</commons-io-version>
<commons-cli-version>1.2</commons-cli-version>
<junit-version>4.8.1</junit-version>

View File

@ -1,11 +1,10 @@
# petstore_api
This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ */ ' \" =end
This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ */ ' \" =end --
This Python package is automatically generated by the [Swagger Codegen](https://github.com/swagger-api/swagger-codegen) project:
- API version: 1.0.0 */ &#39; \&quot; &#x3D;end
- API version: 1.0.0 */ &#39; \&quot; &#x3D;end -- \\r\\n \\n \\r
- Package version: 1.0.0
- Build date: 2016-06-28T16:59:35.203+08:00
- Build package: class io.swagger.codegen.languages.PythonClientCodegen
## Requirements.
@ -46,29 +45,30 @@ import petstore_api
Please follow the [installation procedure](#installation--usage) and then run the following:
```python
from __future__ import print_function
import time
import petstore_api
from petstore_api.rest import ApiException
from pprint import pprint
# create an instance of the API class
api_instance = petstore_api.FakeApi
test_code_inject____end = 'test_code_inject____end_example' # str | To test code injection */ ' \" =end (optional)
api_instance = petstore_api.FakeApi()
test_code_inject____end____rn_n_r = 'test_code_inject____end____rn_n_r_example' # str | To test code injection */ ' \" =end -- \\r\\n \\n \\r (optional)
try:
# To test code injection */ ' \" =end
api_instance.test_code_inject____end(test_code_inject____end=test_code_inject____end)
# To test code injection */ ' \" =end -- \\r\\n \\n \\r
api_instance.test_code_inject____end__rn_n_r(test_code_inject____end____rn_n_r=test_code_inject____end____rn_n_r)
except ApiException as e:
print "Exception when calling FakeApi->test_code_inject____end: %s\n" % e
print("Exception when calling FakeApi->test_code_inject____end__rn_n_r: %s\n" % e)
```
## Documentation for API Endpoints
All URIs are relative to *https://petstore.swagger.io */ &#39; &quot; &#x3D;end/v2 */ &#39; &quot; &#x3D;end*
All URIs are relative to *https://petstore.swagger.io */ &#39; \&quot; &#x3D;end -- \\r\\n \\n \\r/v2 */ &#39; \&quot; &#x3D;end -- \\r\\n \\n \\r*
Class | Method | HTTP request | Description
------------ | ------------- | ------------- | -------------
*FakeApi* | [**test_code_inject____end**](docs/FakeApi.md#test_code_inject____end) | **PUT** /fake | To test code injection */ &#39; \&quot; &#x3D;end
*FakeApi* | [**test_code_inject____end__rn_n_r**](docs/FakeApi.md#test_code_inject____end__rn_n_r) | **PUT** /fake | To test code injection */ &#39; \&quot; &#x3D;end -- \\r\\n \\n \\r
## Documentation For Models
@ -82,7 +82,7 @@ Class | Method | HTTP request | Description
## api_key
- **Type**: API key
- **API key parameter name**: api_key */ ' " =end
- **API key parameter name**: api_key */ ' " =end -- \r\n \n \r
- **Location**: HTTP header
## petstore_auth
@ -91,11 +91,11 @@ Class | Method | HTTP request | Description
- **Flow**: implicit
- **Authorization URL**: http://petstore.swagger.io/api/oauth/dialog
- **Scopes**:
- **write:pets**: modify pets in your account */ ' " =end
- **read:pets**: read your pets */ ' " =end
- **write:pets**: modify pets in your account */ ' \" =end -- \\r\\n \\n \\r
- **read:pets**: read your pets */ ' \" =end -- \\r\\n \\n \\r
## Author
apiteam@swagger.io */ &#39; \&quot; &#x3D;end
apiteam@swagger.io */ &#39; \&quot; &#x3D;end -- \\r\\n \\n \\r

View File

@ -1,19 +1,20 @@
# petstore_api.FakeApi
All URIs are relative to *https://petstore.swagger.io */ &#39; &quot; &#x3D;end/v2 */ &#39; &quot; &#x3D;end*
All URIs are relative to *https://petstore.swagger.io */ &#39; \&quot; &#x3D;end -- \\r\\n \\n \\r/v2 */ &#39; \&quot; &#x3D;end -- \\r\\n \\n \\r*
Method | HTTP request | Description
------------- | ------------- | -------------
[**test_code_inject____end**](FakeApi.md#test_code_inject____end) | **PUT** /fake | To test code injection */ &#39; \&quot; &#x3D;end
[**test_code_inject____end__rn_n_r**](FakeApi.md#test_code_inject____end__rn_n_r) | **PUT** /fake | To test code injection */ &#39; \&quot; &#x3D;end -- \\r\\n \\n \\r
# **test_code_inject____end**
> test_code_inject____end(test_code_inject____end=test_code_inject____end)
# **test_code_inject____end__rn_n_r**
> test_code_inject____end__rn_n_r(test_code_inject____end____rn_n_r=test_code_inject____end____rn_n_r)
To test code injection */ ' \" =end
To test code injection */ ' \" =end -- \\r\\n \\n \\r
### Example
```python
from __future__ import print_statement
import time
import petstore_api
from petstore_api.rest import ApiException
@ -21,20 +22,20 @@ from pprint import pprint
# create an instance of the API class
api_instance = petstore_api.FakeApi()
test_code_inject____end = 'test_code_inject____end_example' # str | To test code injection */ ' \" =end (optional)
test_code_inject____end____rn_n_r = 'test_code_inject____end____rn_n_r_example' # str | To test code injection */ ' \" =end -- \\r\\n \\n \\r (optional)
try:
# To test code injection */ ' \" =end
api_instance.test_code_inject____end(test_code_inject____end=test_code_inject____end)
# To test code injection */ ' \" =end -- \\r\\n \\n \\r
api_instance.test_code_inject____end__rn_n_r(test_code_inject____end____rn_n_r=test_code_inject____end____rn_n_r)
except ApiException as e:
print "Exception when calling FakeApi->test_code_inject____end: %s\n" % e
print("Exception when calling FakeApi->test_code_inject____end__rn_n_r: %s\n" % e)
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**test_code_inject____end** | **str**| To test code injection */ &#39; \&quot; &#x3D;end | [optional]
**test_code_inject____end____rn_n_r** | **str**| To test code injection */ &#39; \&quot; &#x3D;end -- \\r\\n \\n \\r | [optional]
### Return type
@ -46,8 +47,8 @@ No authorization required
### HTTP request headers
- **Content-Type**: application/json, */ " =end
- **Accept**: application/json, */ " =end
- **Content-Type**: application/json, */ \" =end --
- **Accept**: application/json, */ \" =end --
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)

View File

@ -3,7 +3,7 @@
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**_return** | **int** | property description */ &#39; \&quot; &#x3D;end | [optional]
**_return** | **int** | property description */ &#39; \&quot; &#x3D;end -- \\r\\n \\n \\r | [optional]
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@ -1,12 +1,12 @@
# coding: utf-8
"""
Swagger Petstore */ ' \" =end
Swagger Petstore */ ' \" =end -- \\r\\n \\n \\r
This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ */ ' \" =end
This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ */ ' \" =end --
OpenAPI spec version: 1.0.0 */ ' \" =end
Contact: apiteam@swagger.io */ ' \" =end
OpenAPI spec version: 1.0.0 */ ' \" =end -- \\r\\n \\n \\r
Contact: apiteam@swagger.io */ ' \" =end -- \\r\\n \\n \\r
Generated by: https://github.com/swagger-api/swagger-codegen.git
Licensed under the Apache License, Version 2.0 (the "License");

View File

@ -19,17 +19,15 @@ Copyright 2016 SmartBear Software
"""
from __future__ import absolute_import
from . import models
from .rest import RESTClientObject
from .rest import ApiException
import os
import re
import sys
import urllib
import json
import mimetypes
import random
import tempfile
import threading
@ -37,14 +35,8 @@ from datetime import datetime
from datetime import date
# python 2 and python 3 compatibility library
from six import iteritems
try:
# for python3
from urllib.parse import quote
except ImportError:
# for python2
from urllib import quote
from six import PY3, integer_types, iteritems, text_type
from six.moves.urllib.parse import quote
from .configuration import Configuration
@ -103,34 +95,40 @@ class ApiClient(object):
def __call_api(self, resource_path, method,
path_params=None, query_params=None, header_params=None,
body=None, post_params=None, files=None,
response_type=None, auth_settings=None, callback=None, _return_http_data_only=None):
response_type=None, auth_settings=None, callback=None,
_return_http_data_only=None, collection_formats=None):
# headers parameters
# header parameters
header_params = header_params or {}
header_params.update(self.default_headers)
if self.cookie:
header_params['Cookie'] = self.cookie
if header_params:
header_params = self.sanitize_for_serialization(header_params)
header_params = dict(self.parameters_to_tuples(header_params,
collection_formats))
# path parameters
if path_params:
path_params = self.sanitize_for_serialization(path_params)
for k, v in iteritems(path_params):
replacement = quote(str(self.to_path_value(v)))
resource_path = resource_path.\
replace('{' + k + '}', replacement)
path_params = self.parameters_to_tuples(path_params,
collection_formats)
for k, v in path_params:
resource_path = resource_path.replace(
'{%s}' % k, quote(str(v)))
# query parameters
if query_params:
query_params = self.sanitize_for_serialization(query_params)
query_params = {k: self.to_path_value(v)
for k, v in iteritems(query_params)}
query_params = self.parameters_to_tuples(query_params,
collection_formats)
# post parameters
if post_params or files:
post_params = self.prepare_post_parameters(post_params, files)
post_params = self.sanitize_for_serialization(post_params)
post_params = self.parameters_to_tuples(post_params,
collection_formats)
# auth setting
self.update_params_for_auth(header_params, query_params, auth_settings)
@ -159,31 +157,16 @@ class ApiClient(object):
if callback:
callback(deserialized_data) if _return_http_data_only else callback((deserialized_data, response_data.status, response_data.getheaders()))
elif _return_http_data_only:
return ( deserialized_data );
return (deserialized_data)
else:
return (deserialized_data, response_data.status, response_data.getheaders())
def to_path_value(self, obj):
"""
Takes value and turn it into a string suitable for inclusion in
the path, by url-encoding.
:param obj: object or string value.
:return string: quoted value.
"""
if type(obj) == list:
return ','.join(obj)
else:
return str(obj)
def sanitize_for_serialization(self, obj):
"""
Builds a JSON POST object.
If obj is None, return None.
If obj is str, int, float, bool, return directly.
If obj is str, int, long, float, bool, return directly.
If obj is datetime.datetime, datetime.date
convert to string in iso8601 format.
If obj is list, sanitize each element in the list.
@ -193,9 +176,7 @@ class ApiClient(object):
:param obj: The data to serialize.
:return: The serialized form of data.
"""
types = (str, int, float, bool, tuple)
if sys.version_info < (3, 0):
types = types + (unicode,)
types = (str, float, bool, bytes) + tuple(integer_types) + (text_type,)
if isinstance(obj, type(None)):
return None
elif isinstance(obj, types):
@ -203,6 +184,9 @@ class ApiClient(object):
elif isinstance(obj, list):
return [self.sanitize_for_serialization(sub_obj)
for sub_obj in obj]
elif isinstance(obj, tuple):
return tuple(self.sanitize_for_serialization(sub_obj)
for sub_obj in obj)
elif isinstance(obj, (datetime, date)):
return obj.isoformat()
else:
@ -227,7 +211,7 @@ class ApiClient(object):
:param response: RESTResponse object to be deserialized.
:param response_type: class literal for
deserialzied object, or string of class name.
deserialized object, or string of class name.
:return: deserialized object.
"""
@ -272,11 +256,13 @@ class ApiClient(object):
if klass in ['int', 'float', 'str', 'bool',
"date", 'datetime', "object"]:
klass = eval(klass)
elif klass == 'long':
klass = int if PY3 else long
# for model types
else:
klass = eval('models.' + klass)
if klass in [int, float, str, bool]:
if klass in integer_types or klass in (float, str, bool):
return self.__deserialize_primitive(data, klass)
elif klass == object:
return self.__deserialize_object(data)
@ -290,7 +276,8 @@ class ApiClient(object):
def call_api(self, resource_path, method,
path_params=None, query_params=None, header_params=None,
body=None, post_params=None, files=None,
response_type=None, auth_settings=None, callback=None, _return_http_data_only=None):
response_type=None, auth_settings=None, callback=None,
_return_http_data_only=None, collection_formats=None):
"""
Makes the HTTP request (synchronous) and return the deserialized data.
To make an async request, define a function for callback.
@ -312,6 +299,8 @@ class ApiClient(object):
If provide this parameter,
the request will be called asynchronously.
:param _return_http_data_only: response data without head status code and headers
:param collection_formats: dict of collection formats for path, query,
header, and post parameters.
:return:
If provide parameter callback,
the request will be called asynchronously.
@ -323,7 +312,8 @@ class ApiClient(object):
return self.__call_api(resource_path, method,
path_params, query_params, header_params,
body, post_params, files,
response_type, auth_settings, callback, _return_http_data_only)
response_type, auth_settings, callback,
_return_http_data_only, collection_formats)
else:
thread = threading.Thread(target=self.__call_api,
args=(resource_path, method,
@ -331,7 +321,8 @@ class ApiClient(object):
header_params, body,
post_params, files,
response_type, auth_settings,
callback,_return_http_data_only))
callback, _return_http_data_only,
collection_formats))
thread.start()
return thread
@ -379,10 +370,41 @@ class ApiClient(object):
body=body)
else:
raise ValueError(
"http method must be `GET`, `HEAD`,"
"http method must be `GET`, `HEAD`, `OPTIONS`,"
" `POST`, `PATCH`, `PUT` or `DELETE`."
)
def parameters_to_tuples(self, params, collection_formats):
"""
Get parameters as list of tuples, formatting collections.
:param params: Parameters as dict or list of two-tuples
:param dict collection_formats: Parameter collection formats
:return: Parameters as list of tuples, collections formatted
"""
new_params = []
if collection_formats is None:
collection_formats = {}
for k, v in iteritems(params) if isinstance(params, dict) else params:
if k in collection_formats:
collection_format = collection_formats[k]
if collection_format == 'multi':
new_params.extend((k, value) for value in v)
else:
if collection_format == 'ssv':
delimiter = ' '
elif collection_format == 'tsv':
delimiter = '\t'
elif collection_format == 'pipes':
delimiter = '|'
else: # csv is the default
delimiter = ','
new_params.append(
(k, delimiter.join(str(value) for value in v)))
else:
new_params.append((k, v))
return new_params
def prepare_post_parameters(self, post_params=None, files=None):
"""
Builds form parameters.
@ -450,7 +472,7 @@ class ApiClient(object):
Updates header and query params based on authentication setting.
:param headers: Header parameters dict to be updated.
:param querys: Query parameters dict to be updated.
:param querys: Query parameters tuple list to be updated.
:param auth_settings: Authentication setting identifiers list.
"""
config = Configuration()
@ -466,7 +488,7 @@ class ApiClient(object):
elif auth_setting['in'] == 'header':
headers[auth_setting['key']] = auth_setting['value']
elif auth_setting['in'] == 'query':
querys[auth_setting['key']] = auth_setting['value']
querys.append((auth_setting['key'], auth_setting['value']))
else:
raise ValueError(
'Authentication token must be in `query` or `header`'
@ -505,7 +527,7 @@ class ApiClient(object):
:param data: str.
:param klass: class literal.
:return: int, float, str, bool.
:return: int, long, float, str, bool.
"""
try:
value = klass(data)
@ -573,6 +595,9 @@ class ApiClient(object):
"""
instance = klass()
if not instance.swagger_types:
return data
for attr, attr_type in iteritems(instance.swagger_types):
if data is not None \
and instance.attribute_map[attr] in data\

View File

@ -1,12 +1,12 @@
# coding: utf-8
"""
Swagger Petstore */ ' \" =end
Swagger Petstore */ ' \" =end -- \\r\\n \\n \\r
This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ */ ' \" =end
This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ */ ' \" =end --
OpenAPI spec version: 1.0.0 */ ' \" =end
Contact: apiteam@swagger.io */ ' \" =end
OpenAPI spec version: 1.0.0 */ ' \" =end -- \\r\\n \\n \\r
Contact: apiteam@swagger.io */ ' \" =end -- \\r\\n \\n \\r
Generated by: https://github.com/swagger-api/swagger-codegen.git
Licensed under the Apache License, Version 2.0 (the "License");
@ -51,9 +51,9 @@ class FakeApi(object):
config.api_client = ApiClient()
self.api_client = config.api_client
def test_code_inject____end(self, **kwargs):
def test_code_inject____end__rn_n_r(self, **kwargs):
"""
To test code injection */ ' \" =end
To test code injection */ ' \" =end -- \\r\\n \\n \\r
This method makes a synchronous HTTP request by default. To make an
@ -62,25 +62,25 @@ class FakeApi(object):
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.test_code_inject____end(callback=callback_function)
>>> thread = api.test_code_inject____end__rn_n_r(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str test_code_inject____end: To test code injection */ ' \" =end
:param str test_code_inject____end____rn_n_r: To test code injection */ ' \" =end -- \\r\\n \\n \\r
:return: None
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.test_code_inject____end_with_http_info(**kwargs)
return self.test_code_inject____end__rn_n_r_with_http_info(**kwargs)
else:
(data) = self.test_code_inject____end_with_http_info(**kwargs)
(data) = self.test_code_inject____end__rn_n_r_with_http_info(**kwargs)
return data
def test_code_inject____end_with_http_info(self, **kwargs):
def test_code_inject____end__rn_n_r_with_http_info(self, **kwargs):
"""
To test code injection */ ' \" =end
To test code injection */ ' \" =end -- \\r\\n \\n \\r
This method makes a synchronous HTTP request by default. To make an
@ -89,17 +89,17 @@ class FakeApi(object):
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.test_code_inject____end_with_http_info(callback=callback_function)
>>> thread = api.test_code_inject____end__rn_n_r_with_http_info(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str test_code_inject____end: To test code injection */ ' \" =end
:param str test_code_inject____end____rn_n_r: To test code injection */ ' \" =end -- \\r\\n \\n \\r
:return: None
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['test_code_inject____end']
all_params = ['test_code_inject____end____rn_n_r']
all_params.append('callback')
all_params.append('_return_http_data_only')
@ -108,11 +108,14 @@ class FakeApi(object):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method test_code_inject____end" % key
" to method test_code_inject____end__rn_n_r" % key
)
params[key] = val
del params['kwargs']
collection_formats = {}
resource_path = '/fake'.replace('{format}', 'json')
path_params = {}
@ -122,20 +125,20 @@ class FakeApi(object):
form_params = []
local_var_files = {}
if 'test_code_inject____end' in params:
form_params.append(('test code inject */ &#39; &quot; &#x3D;end', params['test_code_inject____end']))
if 'test_code_inject____end____rn_n_r' in params:
form_params.append(('test code inject */ &#39; &quot; &#x3D;end -- \r\n \n \r', params['test_code_inject____end____rn_n_r']))
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', '*/ " =end'])
select_header_accept(['application/json', '*/ \" =end -- '])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json', '*/ " =end'])
select_header_content_type(['application/json', '*/ \" =end -- '])
# Authentication setting
auth_settings = []
@ -150,4 +153,5 @@ class FakeApi(object):
response_type=None,
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'))
_return_http_data_only=params.get('_return_http_data_only'),
collection_formats=collection_formats)

View File

@ -1,12 +1,12 @@
# coding: utf-8
"""
Swagger Petstore */ ' \" =end
Swagger Petstore */ ' \" =end -- \\r\\n \\n \\r
This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ */ ' \" =end
This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ */ ' \" =end --
OpenAPI spec version: 1.0.0 */ ' \" =end
Contact: apiteam@swagger.io */ ' \" =end
OpenAPI spec version: 1.0.0 */ ' \" =end -- \\r\\n \\n \\r
Contact: apiteam@swagger.io */ ' \" =end -- \\r\\n \\n \\r
Generated by: https://github.com/swagger-api/swagger-codegen.git
Licensed under the Apache License, Version 2.0 (the "License");
@ -23,19 +23,14 @@
"""
from __future__ import absolute_import
import base64
import urllib3
try:
import httplib
except ImportError:
# for python3
import http.client as httplib
import urllib3
import sys
import logging
from six import iteritems
from six.moves import http_client as httplib
def singleton(cls, *args, **kw):
@ -61,7 +56,7 @@ class Configuration(object):
Constructor
"""
# Default Base url
self.host = "https://petstore.swagger.io */ &#39; &quot; &#x3D;end/v2 */ &#39; &quot; &#x3D;end"
self.host = "https://petstore.swagger.io */ &#39; \&quot; &#x3D;end -- \\r\\n \\n \\r/v2 */ &#39; \&quot; &#x3D;end -- \\r\\n \\n \\r"
# Default api client
self.api_client = None
# Temp file folder for downloading files
@ -225,8 +220,8 @@ class Configuration(object):
{
'type': 'api_key',
'in': 'header',
'key': 'api_key */ &#39; &quot; &#x3D;end',
'value': self.get_api_key_with_prefix('api_key */ &#39; &quot; &#x3D;end')
'key': 'api_key */ &#39; &quot; &#x3D;end -- \r\n \n \r',
'value': self.get_api_key_with_prefix('api_key */ &#39; &quot; &#x3D;end -- \r\n \n \r')
},
'petstore_auth':
@ -248,6 +243,6 @@ class Configuration(object):
return "Python SDK Debug Report:\n"\
"OS: {env}\n"\
"Python Version: {pyversion}\n"\
"Version of the API: 1.0.0 */ &#39; \&quot; &#x3D;end\n"\
"Version of the API: 1.0.0 */ &#39; \&quot; &#x3D;end -- \\r\\n \\n \\r\n"\
"SDK Package Version: 1.0.0".\
format(env=sys.platform, pyversion=sys.version)

View File

@ -1,12 +1,12 @@
# coding: utf-8
"""
Swagger Petstore */ ' \" =end
Swagger Petstore */ ' \" =end -- \\r\\n \\n \\r
This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ */ ' \" =end
This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ */ ' \" =end --
OpenAPI spec version: 1.0.0 */ ' \" =end
Contact: apiteam@swagger.io */ ' \" =end
OpenAPI spec version: 1.0.0 */ ' \" =end -- \\r\\n \\n \\r
Contact: apiteam@swagger.io */ ' \" =end -- \\r\\n \\n \\r
Generated by: https://github.com/swagger-api/swagger-codegen.git
Licensed under the Apache License, Version 2.0 (the "License");

View File

@ -1,12 +1,12 @@
# coding: utf-8
"""
Swagger Petstore */ ' \" =end
Swagger Petstore */ ' \" =end -- \\r\\n \\n \\r
This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ */ ' \" =end
This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ */ ' \" =end --
OpenAPI spec version: 1.0.0 */ ' \" =end
Contact: apiteam@swagger.io */ ' \" =end
OpenAPI spec version: 1.0.0 */ ' \" =end -- \\r\\n \\n \\r
Contact: apiteam@swagger.io */ ' \" =end -- \\r\\n \\n \\r
Generated by: https://github.com/swagger-api/swagger-codegen.git
Licensed under the Apache License, Version 2.0 (the "License");
@ -51,11 +51,12 @@ class ModelReturn(object):
self.__return = _return
@property
def _return(self):
"""
Gets the _return of this ModelReturn.
property description */ ' \" =end
property description */ ' \" =end -- \\r\\n \\n \\r
:return: The _return of this ModelReturn.
:rtype: int
@ -66,7 +67,7 @@ class ModelReturn(object):
def _return(self, _return):
"""
Sets the _return of this ModelReturn.
property description */ ' \" =end
property description */ ' \" =end -- \\r\\n \\n \\r
:param _return: The _return of this ModelReturn.
:type: int

View File

@ -1,12 +1,12 @@
# coding: utf-8
"""
Swagger Petstore */ ' \" =end
Swagger Petstore */ ' \" =end -- \\r\\n \\n \\r
This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ */ ' \" =end
This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ */ ' \" =end --
OpenAPI spec version: 1.0.0 */ ' \" =end
Contact: apiteam@swagger.io */ ' \" =end
OpenAPI spec version: 1.0.0 */ ' \" =end -- \\r\\n \\n \\r
Contact: apiteam@swagger.io */ ' \" =end -- \\r\\n \\n \\r
Generated by: https://github.com/swagger-api/swagger-codegen.git
Licensed under the Apache License, Version 2.0 (the "License");
@ -24,15 +24,16 @@
from __future__ import absolute_import
import sys
import io
import json
import ssl
import certifi
import logging
import re
# python 2 and python 3 compatibility library
from six import iteritems
from six import PY3
from six.moves.urllib.parse import urlencode
from .configuration import Configuration
@ -41,13 +42,6 @@ try:
except ImportError:
raise ImportError('Swagger python client requires urllib3.')
try:
# for python3
from urllib.parse import urlencode
except ImportError:
# for python2
from urllib import urlencode
logger = logging.getLogger(__name__)
@ -119,7 +113,7 @@ class RESTClientObject(object):
:param headers: http request headers
:param body: request json body, for `application/json`
:param post_params: request post parameters,
`application/x-www-form-urlencode`
`application/x-www-form-urlencoded`
and `multipart/form-data`
"""
method = method.upper()
@ -141,19 +135,19 @@ class RESTClientObject(object):
if method in ['POST', 'PUT', 'PATCH', 'OPTIONS', 'DELETE']:
if query_params:
url += '?' + urlencode(query_params)
if headers['Content-Type'] == 'application/json':
if re.search('json', headers['Content-Type'], re.IGNORECASE):
request_body = None
if body:
request_body = json.dumps(body)
r = self.pool_manager.request(method, url,
body=request_body,
headers=headers)
if headers['Content-Type'] == 'application/x-www-form-urlencoded':
elif headers['Content-Type'] == 'application/x-www-form-urlencoded':
r = self.pool_manager.request(method, url,
fields=post_params,
encode_multipart=False,
headers=headers)
if headers['Content-Type'] == 'multipart/form-data':
elif headers['Content-Type'] == 'multipart/form-data':
# must del headers['Content-Type'], or the correct Content-Type
# which generated by urllib3 will be overwritten.
del headers['Content-Type']
@ -161,6 +155,19 @@ class RESTClientObject(object):
fields=post_params,
encode_multipart=True,
headers=headers)
# Pass a `string` parameter directly in the body to support
# other content types than Json when `body` argument is provided
# in serialized form
elif isinstance(body, str):
request_body = body
r = self.pool_manager.request(method, url,
body=request_body,
headers=headers)
else:
# Cannot generate the request from given parameters
msg = """Cannot prepare a request message for provided arguments.
Please check that your arguments match declared content type."""
raise ApiException(status=0, reason=msg)
# For `GET`, `HEAD`
else:
r = self.pool_manager.request(method, url,
@ -174,7 +181,7 @@ class RESTClientObject(object):
# In the python 3, the response.data is bytes.
# we need to decode it to string.
if sys.version_info > (3,):
if PY3:
r.data = r.data.decode('utf8')
# log response body

View File

@ -1,12 +1,12 @@
# coding: utf-8
"""
Swagger Petstore */ ' \" =end
Swagger Petstore */ ' \" =end -- \\r\\n \\n \\r
This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ */ ' \" =end
This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ */ ' \" =end --
OpenAPI spec version: 1.0.0 */ ' \" =end
Contact: apiteam@swagger.io */ ' \" =end
OpenAPI spec version: 1.0.0 */ ' \" =end -- \\r\\n \\n \\r
Contact: apiteam@swagger.io */ ' \" =end -- \\r\\n \\n \\r
Generated by: https://github.com/swagger-api/swagger-codegen.git
Licensed under the Apache License, Version 2.0 (the "License");
@ -40,14 +40,15 @@ REQUIRES = ["urllib3 >= 1.15", "six >= 1.10", "certifi", "python-dateutil"]
setup(
name=NAME,
version=VERSION,
description="Swagger Petstore */ &#39; \&quot; &#x3D;end",
author_email="apiteam@swagger.io */ &#39; \&quot; &#x3D;end",
description="Swagger Petstore */ &#39; \&quot; &#x3D;end -- \\r\\n \\n \\r",
author_email="apiteam@swagger.io */ &#39; \&quot; &#x3D;end -- \\r\\n \\n \\r",
url="",
keywords=["Swagger", "Swagger Petstore */ &#39; \&quot; &#x3D;end"],
keywords=["Swagger", "Swagger Petstore */ &#39; \&quot; &#x3D;end -- \\r\\n \\n \\r"],
install_requires=REQUIRES,
packages=find_packages(),
include_package_data=True,
long_description="""\
This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \&quot; \\ */ &#39; \&quot; &#x3D;end
This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \&quot; \\ */ &#39; \&quot; &#x3D;end --
"""
)

View File

@ -4,7 +4,7 @@ description: Swagger API client
dependencies:
http: '>=0.11.1 <0.12.0'
dartson: "^0.2.4"
intl: "^0.12.4+2"
intl: ">=0.12.4"
dev_dependencies:
guinness: '^0.1.17'

View File

@ -54,7 +54,7 @@ No authorization required
<a name="testEndpointParameters"></a>
# **testEndpointParameters**
> testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password)
> testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback)
Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트
@ -90,8 +90,9 @@ byte[] binary = B; // byte[] | None
LocalDate date = new LocalDate(); // LocalDate | None
DateTime dateTime = new DateTime(); // DateTime | None
String password = "password_example"; // String | None
String paramCallback = "paramCallback_example"; // String | None
try {
apiInstance.testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password);
apiInstance.testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback);
} catch (ApiException e) {
System.err.println("Exception when calling FakeApi#testEndpointParameters");
e.printStackTrace();
@ -115,6 +116,7 @@ Name | Type | Description | Notes
**date** | **LocalDate**| None | [optional]
**dateTime** | **DateTime**| None | [optional]
**password** | **String**| None | [optional]
**paramCallback** | **String**| None | [optional]
### Return type

View File

@ -22,6 +22,7 @@ import org.glassfish.jersey.media.multipart.MultiPartFeature;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.util.Collection;
import java.util.Collections;
@ -623,6 +624,8 @@ public class ApiClient {
response = invocationBuilder.put(entity);
} else if ("DELETE".equals(method)) {
response = invocationBuilder.delete();
} else if ("PATCH".equals(method)) {
response = invocationBuilder.header("X-HTTP-Method-Override", "PATCH").post(entity);
} else {
throw new ApiException(500, "unknown method type " + method);
}

View File

@ -1,4 +1,4 @@
/**
/*
* Swagger Petstore
* This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\
*

View File

@ -94,9 +94,10 @@ public class FakeApi {
* @param date None (optional)
* @param dateTime None (optional)
* @param password None (optional)
* @param paramCallback None (optional)
* @throws ApiException if fails to make API call
*/
public void testEndpointParameters(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, byte[] binary, LocalDate date, DateTime dateTime, String password) throws ApiException {
public void testEndpointParameters(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, byte[] binary, LocalDate date, DateTime dateTime, String password, String paramCallback) throws ApiException {
Object localVarPostBody = null;
// verify the required parameter 'number' is set
@ -155,6 +156,8 @@ if (dateTime != null)
localVarFormParams.put("dateTime", dateTime);
if (password != null)
localVarFormParams.put("password", password);
if (paramCallback != null)
localVarFormParams.put("callback", paramCallback);
final String[] localVarAccepts = {
"application/xml; charset=utf-8", "application/json; charset=utf-8"

View File

@ -34,7 +34,6 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* AdditionalPropertiesClass
*/
@ -111,6 +110,7 @@ public class AdditionalPropertiesClass {
return Objects.hash(mapProperty, mapOfMapProperty);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
@ -132,5 +132,6 @@ public class AdditionalPropertiesClass {
}
return o.toString().replace("\n", "\n ");
}
}

View File

@ -31,7 +31,6 @@ import com.fasterxml.jackson.annotation.JsonCreator;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
/**
* Animal
*/
@ -98,6 +97,7 @@ public class Animal {
return Objects.hash(className, color);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
@ -119,5 +119,6 @@ public class Animal {
}
return o.toString().replace("\n", "\n ");
}
}

View File

@ -30,7 +30,6 @@ import io.swagger.client.model.Animal;
import java.util.ArrayList;
import java.util.List;
/**
* AnimalFarm
*/
@ -53,6 +52,7 @@ public class AnimalFarm extends ArrayList<Animal> {
return Objects.hash(super.hashCode());
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
@ -72,5 +72,6 @@ public class AnimalFarm extends ArrayList<Animal> {
}
return o.toString().replace("\n", "\n ");
}
}

View File

@ -34,7 +34,6 @@ import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
/**
* ArrayOfArrayOfNumberOnly
*/
@ -84,6 +83,7 @@ public class ArrayOfArrayOfNumberOnly {
return Objects.hash(arrayArrayNumber);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
@ -104,5 +104,6 @@ public class ArrayOfArrayOfNumberOnly {
}
return o.toString().replace("\n", "\n ");
}
}

View File

@ -34,7 +34,6 @@ import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
/**
* ArrayOfNumberOnly
*/
@ -84,6 +83,7 @@ public class ArrayOfNumberOnly {
return Objects.hash(arrayNumber);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
@ -104,5 +104,6 @@ public class ArrayOfNumberOnly {
}
return o.toString().replace("\n", "\n ");
}
}

View File

@ -34,7 +34,6 @@ import io.swagger.client.model.ReadOnlyFirst;
import java.util.ArrayList;
import java.util.List;
/**
* ArrayTest
*/
@ -138,6 +137,7 @@ public class ArrayTest {
return Objects.hash(arrayOfString, arrayArrayOfInteger, arrayArrayOfModel);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
@ -160,5 +160,6 @@ public class ArrayTest {
}
return o.toString().replace("\n", "\n ");
}
}

View File

@ -32,7 +32,6 @@ import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.client.model.Animal;
/**
* Cat
*/
@ -78,6 +77,7 @@ public class Cat extends Animal {
return Objects.hash(declawed, super.hashCode());
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
@ -98,5 +98,6 @@ public class Cat extends Animal {
}
return o.toString().replace("\n", "\n ");
}
}

View File

@ -31,7 +31,6 @@ import com.fasterxml.jackson.annotation.JsonCreator;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
/**
* Category
*/
@ -98,6 +97,7 @@ public class Category {
return Objects.hash(id, name);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
@ -119,5 +119,6 @@ public class Category {
}
return o.toString().replace("\n", "\n ");
}
}

View File

@ -31,7 +31,6 @@ import com.fasterxml.jackson.annotation.JsonCreator;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
/**
* Client
*/
@ -76,6 +75,7 @@ public class Client {
return Objects.hash(client);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
@ -96,5 +96,6 @@ public class Client {
}
return o.toString().replace("\n", "\n ");
}
}

View File

@ -32,7 +32,6 @@ import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.client.model.Animal;
/**
* Dog
*/
@ -78,6 +77,7 @@ public class Dog extends Animal {
return Objects.hash(breed, super.hashCode());
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
@ -98,5 +98,6 @@ public class Dog extends Animal {
}
return o.toString().replace("\n", "\n ");
}
}

View File

@ -33,7 +33,6 @@ import io.swagger.annotations.ApiModelProperty;
import java.util.ArrayList;
import java.util.List;
/**
* EnumArrays
*/
@ -165,6 +164,7 @@ public class EnumArrays {
return Objects.hash(justSymbol, arrayEnum);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
@ -186,5 +186,6 @@ public class EnumArrays {
}
return o.toString().replace("\n", "\n ");
}
}

View File

@ -27,7 +27,6 @@ package io.swagger.client.model;
import java.util.Objects;
import com.fasterxml.jackson.annotation.JsonCreator;
/**

View File

@ -31,7 +31,6 @@ import com.fasterxml.jackson.annotation.JsonCreator;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
/**
* EnumTest
*/
@ -210,6 +209,7 @@ public class EnumTest {
return Objects.hash(enumString, enumInteger, enumNumber);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
@ -232,5 +232,6 @@ public class EnumTest {
}
return o.toString().replace("\n", "\n ");
}
}

View File

@ -35,7 +35,6 @@ import java.util.UUID;
import org.joda.time.DateTime;
import org.joda.time.LocalDate;
/**
* FormatTest
*/
@ -354,6 +353,7 @@ public class FormatTest {
return Objects.hash(integer, int32, int64, number, _float, _double, string, _byte, binary, date, dateTime, uuid, password);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
@ -386,5 +386,6 @@ public class FormatTest {
}
return o.toString().replace("\n", "\n ");
}
}

View File

@ -31,7 +31,6 @@ import com.fasterxml.jackson.annotation.JsonCreator;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
/**
* HasOnlyReadOnly
*/
@ -80,6 +79,7 @@ public class HasOnlyReadOnly {
return Objects.hash(bar, foo);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
@ -101,5 +101,6 @@ public class HasOnlyReadOnly {
}
return o.toString().replace("\n", "\n ");
}
}

View File

@ -34,7 +34,6 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* MapTest
*/
@ -141,6 +140,7 @@ public class MapTest {
return Objects.hash(mapMapOfString, mapOfEnumString);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
@ -162,5 +162,6 @@ public class MapTest {
}
return o.toString().replace("\n", "\n ");
}
}

View File

@ -37,7 +37,6 @@ import java.util.Map;
import java.util.UUID;
import org.joda.time.DateTime;
/**
* MixedPropertiesAndAdditionalPropertiesClass
*/
@ -131,6 +130,7 @@ public class MixedPropertiesAndAdditionalPropertiesClass {
return Objects.hash(uuid, dateTime, map);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
@ -153,5 +153,6 @@ public class MixedPropertiesAndAdditionalPropertiesClass {
}
return o.toString().replace("\n", "\n ");
}
}

View File

@ -31,7 +31,6 @@ import com.fasterxml.jackson.annotation.JsonCreator;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
/**
* Model for testing model name starting with number
*/
@ -99,6 +98,7 @@ public class Model200Response {
return Objects.hash(name, propertyClass);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
@ -120,5 +120,6 @@ public class Model200Response {
}
return o.toString().replace("\n", "\n ");
}
}

View File

@ -31,7 +31,6 @@ import com.fasterxml.jackson.annotation.JsonCreator;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
/**
* ModelApiResponse
*/
@ -120,6 +119,7 @@ public class ModelApiResponse {
return Objects.hash(code, type, message);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
@ -142,5 +142,6 @@ public class ModelApiResponse {
}
return o.toString().replace("\n", "\n ");
}
}

View File

@ -31,7 +31,6 @@ import com.fasterxml.jackson.annotation.JsonCreator;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
/**
* Model for testing reserved words
*/
@ -77,6 +76,7 @@ public class ModelReturn {
return Objects.hash(_return);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
@ -97,5 +97,6 @@ public class ModelReturn {
}
return o.toString().replace("\n", "\n ");
}
}

View File

@ -31,7 +31,6 @@ import com.fasterxml.jackson.annotation.JsonCreator;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
/**
* Model for testing model name same as property name
*/
@ -125,6 +124,7 @@ public class Name {
return Objects.hash(name, snakeCase, property, _123Number);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
@ -148,5 +148,6 @@ public class Name {
}
return o.toString().replace("\n", "\n ");
}
}

View File

@ -32,7 +32,6 @@ import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.math.BigDecimal;
/**
* NumberOnly
*/
@ -77,6 +76,7 @@ public class NumberOnly {
return Objects.hash(justNumber);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
@ -97,5 +97,6 @@ public class NumberOnly {
}
return o.toString().replace("\n", "\n ");
}
}

View File

@ -32,7 +32,6 @@ import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import org.joda.time.DateTime;
/**
* Order
*/
@ -219,6 +218,7 @@ public class Order {
return Objects.hash(id, petId, quantity, shipDate, status, complete);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
@ -244,5 +244,6 @@ public class Order {
}
return o.toString().replace("\n", "\n ");
}
}

View File

@ -35,7 +35,6 @@ import io.swagger.client.model.Tag;
import java.util.ArrayList;
import java.util.List;
/**
* Pet
*/
@ -232,6 +231,7 @@ public class Pet {
return Objects.hash(id, category, name, photoUrls, tags, status);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
@ -257,5 +257,6 @@ public class Pet {
}
return o.toString().replace("\n", "\n ");
}
}

View File

@ -31,7 +31,6 @@ import com.fasterxml.jackson.annotation.JsonCreator;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
/**
* ReadOnlyFirst
*/
@ -89,6 +88,7 @@ public class ReadOnlyFirst {
return Objects.hash(bar, baz);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
@ -110,5 +110,6 @@ public class ReadOnlyFirst {
}
return o.toString().replace("\n", "\n ");
}
}

View File

@ -31,7 +31,6 @@ import com.fasterxml.jackson.annotation.JsonCreator;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
/**
* SpecialModelName
*/
@ -76,6 +75,7 @@ public class SpecialModelName {
return Objects.hash(specialPropertyName);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
@ -96,5 +96,6 @@ public class SpecialModelName {
}
return o.toString().replace("\n", "\n ");
}
}

View File

@ -31,7 +31,6 @@ import com.fasterxml.jackson.annotation.JsonCreator;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
/**
* Tag
*/
@ -98,6 +97,7 @@ public class Tag {
return Objects.hash(id, name);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
@ -119,5 +119,6 @@ public class Tag {
}
return o.toString().replace("\n", "\n ");
}
}

View File

@ -31,7 +31,6 @@ import com.fasterxml.jackson.annotation.JsonCreator;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
/**
* User
*/
@ -230,6 +229,7 @@ public class User {
return Objects.hash(id, username, firstName, lastName, email, password, phone, userStatus);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
@ -257,5 +257,6 @@ public class User {
}
return o.toString().replace("\n", "\n ");
}
}

View File

@ -10,8 +10,8 @@ import okhttp3.RequestBody;
import io.swagger.client.model.Client;
import org.joda.time.LocalDate;
import org.joda.time.DateTime;
import java.math.BigDecimal;
import org.joda.time.DateTime;
import java.util.ArrayList;
import java.util.HashMap;
@ -26,6 +26,9 @@ public interface FakeApi {
* @return Call&lt;Client&gt;
*/
@Headers({
"Content-Type:application/json"
})
@PATCH("fake")
Call<Client> testClientModel(
@retrofit2.http.Body Client body

View File

@ -9,8 +9,8 @@ import retrofit2.http.*;
import okhttp3.RequestBody;
import io.swagger.client.model.Pet;
import java.io.File;
import io.swagger.client.model.ModelApiResponse;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
@ -25,6 +25,9 @@ public interface PetApi {
* @return Call&lt;Void&gt;
*/
@Headers({
"Content-Type:application/json"
})
@POST("pet")
Call<Void> addPet(
@retrofit2.http.Body Pet body
@ -86,6 +89,9 @@ public interface PetApi {
* @return Call&lt;Void&gt;
*/
@Headers({
"Content-Type:application/json"
})
@PUT("pet")
Call<Void> updatePet(
@retrofit2.http.Body Pet body

View File

@ -51,3 +51,4 @@ setup(
This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \&quot; \\
"""
)

View File

@ -14,7 +14,7 @@
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.6.RELEASE</version>
<version>1.4.1.RELEASE</version>
</parent>
<build>
<sourceDirectory>src/main/java</sourceDirectory>
@ -25,7 +25,7 @@
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-parent</artifactId>
<version>Brixton.SR2</version>
<version>Camden.SR1</version>
<type>pom</type>
<scope>import</scope>
</dependency>

View File

@ -33,7 +33,7 @@ public interface PetApi {
produces = "application/json",
consumes = "application/json",
method = RequestMethod.POST)
ResponseEntity<Void> addPet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @RequestBody Pet body);
com.netflix.hystrix.HystrixCommand<ResponseEntity<Void>> addPet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @RequestBody Pet body);
@ApiOperation(value = "Deletes a pet", notes = "", response = Void.class, authorizations = {
@ -48,7 +48,7 @@ public interface PetApi {
produces = "application/json",
consumes = "application/json",
method = RequestMethod.DELETE)
ResponseEntity<Void> deletePet(@ApiParam(value = "Pet id to delete",required=true ) @PathVariable("petId") Long petId,
com.netflix.hystrix.HystrixCommand<ResponseEntity<Void>> deletePet(@ApiParam(value = "Pet id to delete",required=true ) @PathVariable("petId") Long petId,
@ApiParam(value = "" ) @RequestHeader(value="api_key", required=false) String apiKey);
@ -65,7 +65,7 @@ public interface PetApi {
produces = "application/json",
consumes = "application/json",
method = RequestMethod.GET)
ResponseEntity<List<Pet>> findPetsByStatus(@ApiParam(value = "Status values that need to be considered for filter", required = true, allowableValues = "AVAILABLE, PENDING, SOLD") @RequestParam(value = "status", required = true) List<String> status);
com.netflix.hystrix.HystrixCommand<ResponseEntity<List<Pet>>> findPetsByStatus(@ApiParam(value = "Status values that need to be considered for filter", required = true, allowableValues = "AVAILABLE, PENDING, SOLD") @RequestParam(value = "status", required = true) List<String> status);
@ApiOperation(value = "Finds Pets by tags", notes = "Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.", response = Pet.class, responseContainer = "List", authorizations = {
@ -81,7 +81,7 @@ public interface PetApi {
produces = "application/json",
consumes = "application/json",
method = RequestMethod.GET)
ResponseEntity<List<Pet>> findPetsByTags(@ApiParam(value = "Tags to filter by", required = true) @RequestParam(value = "tags", required = true) List<String> tags);
com.netflix.hystrix.HystrixCommand<ResponseEntity<List<Pet>>> findPetsByTags(@ApiParam(value = "Tags to filter by", required = true) @RequestParam(value = "tags", required = true) List<String> tags);
@ApiOperation(value = "Find pet by ID", notes = "Returns a single pet", response = Pet.class, authorizations = {
@ -95,7 +95,7 @@ public interface PetApi {
produces = "application/json",
consumes = "application/json",
method = RequestMethod.GET)
ResponseEntity<Pet> getPetById(@ApiParam(value = "ID of pet to return",required=true ) @PathVariable("petId") Long petId);
com.netflix.hystrix.HystrixCommand<ResponseEntity<Pet>> getPetById(@ApiParam(value = "ID of pet to return",required=true ) @PathVariable("petId") Long petId);
@ApiOperation(value = "Update an existing pet", notes = "", response = Void.class, authorizations = {
@ -112,7 +112,7 @@ public interface PetApi {
produces = "application/json",
consumes = "application/json",
method = RequestMethod.PUT)
ResponseEntity<Void> updatePet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @RequestBody Pet body);
com.netflix.hystrix.HystrixCommand<ResponseEntity<Void>> updatePet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @RequestBody Pet body);
@ApiOperation(value = "Updates a pet in the store with form data", notes = "", response = Void.class, authorizations = {
@ -127,7 +127,7 @@ public interface PetApi {
produces = "application/json",
consumes = "application/x-www-form-urlencoded",
method = RequestMethod.POST)
ResponseEntity<Void> updatePetWithForm(@ApiParam(value = "ID of pet that needs to be updated",required=true ) @PathVariable("petId") Long petId,
com.netflix.hystrix.HystrixCommand<ResponseEntity<Void>> updatePetWithForm(@ApiParam(value = "ID of pet that needs to be updated",required=true ) @PathVariable("petId") Long petId,
@ApiParam(value = "Updated name of the pet" ) @RequestParam(value="name", required=false) String name,
@ApiParam(value = "Updated status of the pet" ) @RequestParam(value="status", required=false) String status);
@ -144,7 +144,7 @@ public interface PetApi {
produces = "application/json",
consumes = "multipart/form-data",
method = RequestMethod.POST)
ResponseEntity<ModelApiResponse> uploadFile(@ApiParam(value = "ID of pet to update",required=true ) @PathVariable("petId") Long petId,
com.netflix.hystrix.HystrixCommand<ResponseEntity<ModelApiResponse>> uploadFile(@ApiParam(value = "ID of pet to update",required=true ) @PathVariable("petId") Long petId,
@ApiParam(value = "Additional data to pass to server" ) @RequestParam(value="additionalMetadata", required=false) String additionalMetadata,
@ApiParam(value = "file detail") @RequestParam("file") MultipartFile file);

View File

@ -28,7 +28,7 @@ public interface StoreApi {
produces = "application/json",
consumes = "application/json",
method = RequestMethod.DELETE)
ResponseEntity<Void> deleteOrder(@ApiParam(value = "ID of the order that needs to be deleted",required=true ) @PathVariable("orderId") String orderId);
com.netflix.hystrix.HystrixCommand<ResponseEntity<Void>> deleteOrder(@ApiParam(value = "ID of the order that needs to be deleted",required=true ) @PathVariable("orderId") String orderId);
@ApiOperation(value = "Returns pet inventories by status", notes = "Returns a map of status codes to quantities", response = Integer.class, responseContainer = "Map", authorizations = {
@ -40,7 +40,7 @@ public interface StoreApi {
produces = "application/json",
consumes = "application/json",
method = RequestMethod.GET)
ResponseEntity<Map<String, Integer>> getInventory();
com.netflix.hystrix.HystrixCommand<ResponseEntity<Map<String, Integer>>> getInventory();
@ApiOperation(value = "Find purchase order by ID", notes = "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions", response = Order.class, tags={ "store", })
@ -52,7 +52,7 @@ public interface StoreApi {
produces = "application/json",
consumes = "application/json",
method = RequestMethod.GET)
ResponseEntity<Order> getOrderById(@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("orderId") Long orderId);
com.netflix.hystrix.HystrixCommand<ResponseEntity<Order>> getOrderById(@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("orderId") Long orderId);
@ApiOperation(value = "Place an order for a pet", notes = "", response = Order.class, tags={ "store", })
@ -63,6 +63,6 @@ public interface StoreApi {
produces = "application/json",
consumes = "application/json",
method = RequestMethod.POST)
ResponseEntity<Order> placeOrder(@ApiParam(value = "order placed for purchasing the pet" ,required=true ) @RequestBody Order body);
com.netflix.hystrix.HystrixCommand<ResponseEntity<Order>> placeOrder(@ApiParam(value = "order placed for purchasing the pet" ,required=true ) @RequestBody Order body);
}

View File

@ -27,7 +27,7 @@ public interface UserApi {
produces = "application/json",
consumes = "application/json",
method = RequestMethod.POST)
ResponseEntity<Void> createUser(@ApiParam(value = "Created user object" ,required=true ) @RequestBody User body);
com.netflix.hystrix.HystrixCommand<ResponseEntity<Void>> createUser(@ApiParam(value = "Created user object" ,required=true ) @RequestBody User body);
@ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class, tags={ "user", })
@ -37,7 +37,7 @@ public interface UserApi {
produces = "application/json",
consumes = "application/json",
method = RequestMethod.POST)
ResponseEntity<Void> createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true ) @RequestBody List<User> body);
com.netflix.hystrix.HystrixCommand<ResponseEntity<Void>> createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true ) @RequestBody List<User> body);
@ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class, tags={ "user", })
@ -47,7 +47,7 @@ public interface UserApi {
produces = "application/json",
consumes = "application/json",
method = RequestMethod.POST)
ResponseEntity<Void> createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true ) @RequestBody List<User> body);
com.netflix.hystrix.HystrixCommand<ResponseEntity<Void>> createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true ) @RequestBody List<User> body);
@ApiOperation(value = "Delete user", notes = "This can only be done by the logged in user.", response = Void.class, tags={ "user", })
@ -58,7 +58,7 @@ public interface UserApi {
produces = "application/json",
consumes = "application/json",
method = RequestMethod.DELETE)
ResponseEntity<Void> deleteUser(@ApiParam(value = "The name that needs to be deleted",required=true ) @PathVariable("username") String username);
com.netflix.hystrix.HystrixCommand<ResponseEntity<Void>> deleteUser(@ApiParam(value = "The name that needs to be deleted",required=true ) @PathVariable("username") String username);
@ApiOperation(value = "Get user by user name", notes = "", response = User.class, tags={ "user", })
@ -70,7 +70,7 @@ public interface UserApi {
produces = "application/json",
consumes = "application/json",
method = RequestMethod.GET)
ResponseEntity<User> getUserByName(@ApiParam(value = "The name that needs to be fetched. Use user1 for testing. ",required=true ) @PathVariable("username") String username);
com.netflix.hystrix.HystrixCommand<ResponseEntity<User>> getUserByName(@ApiParam(value = "The name that needs to be fetched. Use user1 for testing. ",required=true ) @PathVariable("username") String username);
@ApiOperation(value = "Logs user into the system", notes = "", response = String.class, tags={ "user", })
@ -81,7 +81,7 @@ public interface UserApi {
produces = "application/json",
consumes = "application/json",
method = RequestMethod.GET)
ResponseEntity<String> loginUser(@ApiParam(value = "The user name for login", required = true) @RequestParam(value = "username", required = true) String username,
com.netflix.hystrix.HystrixCommand<ResponseEntity<String>> loginUser(@ApiParam(value = "The user name for login", required = true) @RequestParam(value = "username", required = true) String username,
@ApiParam(value = "The password for login in clear text", required = true) @RequestParam(value = "password", required = true) String password);
@ -92,7 +92,7 @@ public interface UserApi {
produces = "application/json",
consumes = "application/json",
method = RequestMethod.GET)
ResponseEntity<Void> logoutUser();
com.netflix.hystrix.HystrixCommand<ResponseEntity<Void>> logoutUser();
@ApiOperation(value = "Updated user", notes = "This can only be done by the logged in user.", response = Void.class, tags={ "user", })
@ -103,7 +103,7 @@ public interface UserApi {
produces = "application/json",
consumes = "application/json",
method = RequestMethod.PUT)
ResponseEntity<Void> updateUser(@ApiParam(value = "name that need to be deleted",required=true ) @PathVariable("username") String username,
com.netflix.hystrix.HystrixCommand<ResponseEntity<Void>> updateUser(@ApiParam(value = "name that need to be deleted",required=true ) @PathVariable("username") String username,
@ApiParam(value = "Updated user object" ,required=true ) @RequestBody User body);
}

View File

@ -0,0 +1,20 @@
package io.swagger;
import feign.Logger;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.cloud.netflix.feign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
@EnableFeignClients
public class Application {
public static void main(String[] args) {
new SpringApplicationBuilder(Application.class).run(args);
}
@Bean
Logger.Level feignLoggerLevel() {
return Logger.Level.FULL;
}
}

View File

@ -1,30 +1,28 @@
package io.swagger.api;
import feign.FeignException;
import com.netflix.hystrix.exception.HystrixRuntimeException;
import io.swagger.Application;
import io.swagger.TestUtils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import io.swagger.model.Category;
import io.swagger.model.Pet;
import io.swagger.model.Tag;
import org.junit.*;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.cloud.netflix.feign.EnableFeignClients;
import org.springframework.http.ResponseEntity;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import static org.junit.Assert.*;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = PetApiTest.Application.class)
@SpringBootTest(classes = Application.class)
public class PetApiTest {
@Autowired
@ -33,9 +31,8 @@ public class PetApiTest {
@Test
public void testCreateAndGetPet() {
Pet pet = createRandomPet();
client.addPet(pet);
ResponseEntity<Pet> rp = client.getPetById(pet.getId());
Pet fetched = rp.getBody();
client.addPet(pet).execute();
Pet fetched = client.getPetById(pet.getId()).execute().getBody();
assertNotNull(fetched);
assertEquals(pet.getId(), fetched.getId());
assertNotNull(fetched.getCategory());
@ -47,9 +44,9 @@ public class PetApiTest {
Pet pet = createRandomPet();
pet.setName("programmer");
client.updatePet(pet);
client.updatePet(pet).execute();
Pet fetched = client.getPetById(pet.getId()).getBody();
Pet fetched = client.getPetById(pet.getId()).execute().getBody();
assertNotNull(fetched);
assertEquals(pet.getId(), fetched.getId());
assertNotNull(fetched.getCategory());
@ -63,9 +60,9 @@ public class PetApiTest {
pet.setName("programmer");
pet.setStatus(Pet.StatusEnum.AVAILABLE);
client.updatePet(pet);
client.updatePet(pet).execute();
List<Pet> pets = client.findPetsByStatus(Arrays.asList(new String[]{"available"})).getBody();
List<Pet> pets = client.findPetsByStatus(Collections.singletonList("available")).execute().getBody();
assertNotNull(pets);
boolean found = false;
@ -92,9 +89,9 @@ public class PetApiTest {
tags.add(tag1);
pet.setTags(tags);
client.updatePet(pet);
client.updatePet(pet).execute();
List<Pet> pets = client.findPetsByTags(Arrays.asList(new String[]{"friendly"})).getBody();
List<Pet> pets = client.findPetsByTags(Collections.singletonList("friendly")).execute().getBody();
assertNotNull(pets);
boolean found = false;
@ -111,12 +108,12 @@ public class PetApiTest {
public void testUpdatePetWithForm() throws Exception {
Pet pet = createRandomPet();
pet.setName("frank");
client.addPet(pet);
client.addPet(pet).execute();
Pet fetched = client.getPetById(pet.getId()).getBody();
Pet fetched = client.getPetById(pet.getId()).execute().getBody();
client.updatePetWithForm(fetched.getId(), "furt", null);
Pet updated = client.getPetById(fetched.getId()).getBody();
client.updatePetWithForm(fetched.getId(), "furt", null).execute();
Pet updated = client.getPetById(fetched.getId()).execute().getBody();
assertEquals(updated.getName(), "furt");
}
@ -124,16 +121,16 @@ public class PetApiTest {
@Test
public void testDeletePet() throws Exception {
Pet pet = createRandomPet();
client.addPet(pet);
client.addPet(pet).execute();
Pet fetched = client.getPetById(pet.getId()).getBody();
client.deletePet(fetched.getId(), null);
Pet fetched = client.getPetById(pet.getId()).execute().getBody();
client.deletePet(fetched.getId(), null).execute();
try {
client.getPetById(fetched.getId());
client.getPetById(fetched.getId()).execute();
fail("expected an error");
} catch (FeignException e) {
assertTrue(e.getMessage().startsWith("status 404 "));
} catch (HystrixRuntimeException e) {
assertTrue(e.getCause().getMessage().startsWith("status 404 "));
}
}
@ -141,10 +138,10 @@ public class PetApiTest {
@Test
public void testUploadFile() throws Exception {
Pet pet = createRandomPet();
client.addPet(pet);
client.addPet(pet).execute();
MockMultipartFile filePart = new MockMultipartFile("file", "bar".getBytes());
client.uploadFile(pet.getId(), "a test file", filePart);
client.uploadFile(pet.getId(), "a test file", filePart).execute();
}
@Test
@ -158,7 +155,7 @@ public class PetApiTest {
assertTrue(pet1.hashCode() == pet1.hashCode());
pet2.setName("really-happy");
pet2.setPhotoUrls(Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"}));
pet2.setPhotoUrls(Arrays.asList("http://foo.bar.com/1", "http://foo.bar.com/2"));
assertFalse(pet1.equals(pet2));
assertFalse(pet2.equals(pet1));
assertFalse(pet1.hashCode() == (pet2.hashCode()));
@ -166,7 +163,7 @@ public class PetApiTest {
assertTrue(pet2.hashCode() == pet2.hashCode());
pet1.setName("really-happy");
pet1.setPhotoUrls(Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"}));
pet1.setPhotoUrls(Arrays.asList("http://foo.bar.com/1", "http://foo.bar.com/2"));
assertTrue(pet1.equals(pet2));
assertTrue(pet2.equals(pet1));
assertTrue(pet1.hashCode() == pet2.hashCode());
@ -184,24 +181,10 @@ public class PetApiTest {
pet.setCategory(category);
pet.setStatus(Pet.StatusEnum.AVAILABLE);
List<String> photos = Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"});
List<String> photos = Arrays.asList("http://foo.bar.com/1", "http://foo.bar.com/2");
pet.setPhotoUrls(photos);
return pet;
}
@SpringBootApplication
@EnableFeignClients
protected static class Application {
public static void main(String[] args) {
new SpringApplicationBuilder(Application.class).run(args);
}
}
}

View File

@ -1,15 +1,13 @@
package io.swagger.api;
import feign.FeignException;
import com.netflix.hystrix.exception.HystrixRuntimeException;
import io.swagger.Application;
import io.swagger.TestUtils;
import io.swagger.model.Order;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.cloud.netflix.feign.EnableFeignClients;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.lang.reflect.Field;
@ -18,7 +16,7 @@ import java.util.Map;
import static org.junit.Assert.*;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = StoreApiTest.Application.class)
@SpringBootTest(classes = Application.class)
public class StoreApiTest {
@Autowired
@ -26,16 +24,16 @@ public class StoreApiTest {
@Test
public void testGetInventory() {
Map<String, Integer> inventory = client.getInventory().getBody();
Map<String, Integer> inventory = client.getInventory().execute().getBody();
assertTrue(inventory.keySet().size() > 0);
}
@Test
public void testPlaceOrder() {
Order order = createOrder();
client.placeOrder(order);
client.placeOrder(order).execute();
Order fetched = client.getOrderById(order.getId()).getBody();
Order fetched = client.getOrderById(order.getId()).execute().getBody();
assertEquals(order.getId(), fetched.getId());
assertEquals(order.getPetId(), fetched.getPetId());
assertEquals(order.getQuantity(), fetched.getQuantity());
@ -45,25 +43,25 @@ public class StoreApiTest {
@Test
public void testDeleteOrder() {
Order order = createOrder();
client.placeOrder(order);
client.placeOrder(order).execute();
Order fetched = client.getOrderById(order.getId()).getBody();
Order fetched = client.getOrderById(order.getId()).execute().getBody();
assertEquals(fetched.getId(), order.getId());
client.deleteOrder(String.valueOf(order.getId()));
client.deleteOrder(String.valueOf(order.getId())).execute();
try {
client.getOrderById(order.getId());
client.getOrderById(order.getId()).execute();
fail("expected an error");
} catch (FeignException e) {
assertTrue(e.getMessage().startsWith("status 404 "));
} catch (HystrixRuntimeException e) {
assertTrue(e.getCause().getMessage().startsWith("status 404 "));
}
}
private Order createOrder() {
Order order = new Order();
order.setPetId(new Long(200));
order.setQuantity(new Integer(13));
order.setPetId(200L);
order.setQuantity(13);
order.setShipDate(org.joda.time.DateTime.now());
order.setStatus(Order.StatusEnum.PLACED);
order.setComplete(true);
@ -79,11 +77,4 @@ public class StoreApiTest {
return order;
}
@SpringBootApplication
@EnableFeignClients
protected static class Application {
public static void main(String[] args) {
new SpringApplicationBuilder(StoreApiTest.Application.class).run(args);
}
}
}

View File

@ -1,23 +1,21 @@
package io.swagger.api;
import io.swagger.Application;
import io.swagger.TestUtils;
import io.swagger.model.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.cloud.netflix.feign.EnableFeignClients;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.Arrays;
import static org.junit.Assert.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = UserApiTest.Application.class)
@SpringBootTest(classes = Application.class)
public class UserApiTest {
@Autowired
@ -27,9 +25,9 @@ public class UserApiTest {
public void testCreateUser() {
User user = createUser();
client.createUser(user);
client.createUser(user).execute();
User fetched = client.getUserByName(user.getUsername()).getBody();
User fetched = client.getUserByName(user.getUsername()).execute().getBody();
assertEquals(user.getId(), fetched.getId());
}
@ -40,9 +38,9 @@ public class UserApiTest {
User user2 = createUser();
user2.setUsername("user" + user2.getId());
client.createUsersWithArrayInput(Arrays.asList(new User[]{user1, user2}));
client.createUsersWithArrayInput(Arrays.asList(user1, user2)).execute();
User fetched = client.getUserByName(user1.getUsername()).getBody();
User fetched = client.getUserByName(user1.getUsername()).execute().getBody();
assertEquals(user1.getId(), fetched.getId());
}
@ -53,24 +51,24 @@ public class UserApiTest {
User user2 = createUser();
user2.setUsername("user" + user2.getId());
client.createUsersWithListInput(Arrays.asList(new User[]{user1, user2}));
client.createUsersWithListInput(Arrays.asList(user1, user2)).execute();
User fetched = client.getUserByName(user1.getUsername()).getBody();
User fetched = client.getUserByName(user1.getUsername()).execute().getBody();
assertEquals(user1.getId(), fetched.getId());
}
@Test
public void testLoginUser() {
User user = createUser();
client.createUser(user);
client.createUser(user).execute();
String token = client.loginUser(user.getUsername(), user.getPassword()).getBody();
String token = client.loginUser(user.getUsername(), user.getPassword()).execute().getBody();
assertTrue(token.startsWith("logged in user session:"));
}
@Test
public void logoutUser() {
client.logoutUser();
client.logoutUser().execute();
}
private User createUser() {
@ -87,11 +85,4 @@ public class UserApiTest {
return user;
}
@SpringBootApplication
@EnableFeignClients
protected static class Application {
public static void main(String[] args) {
new SpringApplicationBuilder(UserApiTest.Application.class).run(args);
}
}
}

View File

@ -2,9 +2,7 @@ spring:
application:
name: petstore-test
feign.hystrix.enabled: false
hystrix.command.default.execution.timeout.enabled: false
logging.level.io.swagger.api: DEBUG
logging.level.io.swagger.api:
PetApiClient: DEBUG
StoreApiClient: DEBUG
UserApiClient: DEBUG

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