[openapi-normalizer] add a rule to better handle openapi 3.1 spec (#16495)

* add samples

* update samples

* openapi 3.1 beta support

* update .gitignore

* fix composed schema, add oneof, allof tests in opeanpi 3.1 spec

* add allof tests, more fixes

* add null check

* update artifact id

* better null check
This commit is contained in:
William Cheng 2023-09-05 23:27:00 +08:00 committed by GitHub
parent 065b48177b
commit 4b7a808a9f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
109 changed files with 16897 additions and 215 deletions

1
.gitignore vendored
View File

@ -89,6 +89,7 @@ samples/client/petstore/cpp-restsdk/cmake_install.cmake
**/.gradle
samples/client/petstore/java/hello.txt
samples/client/petstore/java/okhttp-gson/hello.txt
samples/client/petstore/java/okhttp-gson-3.1/hello.txt
samples/client/petstore/java/jersey1/hello.txt
samples/client/petstore/java/jersey2-java8/hello.txt
samples/client/petstore/java/jersey2/hello.txt

View File

@ -0,0 +1,16 @@
generatorName: java
outputDir: samples/client/petstore/java/okhttp-gson-3.1
library: okhttp-gson
inputSpec: modules/openapi-generator/src/test/resources/3_1/java/petstore.yaml
templateDir: modules/openapi-generator/src/main/resources/Java
nameMappings:
_type: underscoreType
type_: typeWithUnderscore
parameterNameMappings:
_type: underscoreType
type_: typeWithUnderscore
additionalProperties:
artifactId: petstore-okhttp-gson-31
hideGenerationTimestamp: "true"
useOneOfDiscriminatorLookup: "true"
disallowAdditionalPropertiesIfNotPresent: false

View File

@ -17,6 +17,7 @@
package org.openapitools.codegen;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.Ticker;
@ -1035,23 +1036,23 @@ public class DefaultCodegen implements CodegenConfig {
if (ModelUtils.isComposedSchema(s)) {
if (e.getKey().contains("/")) {
// if this is property schema, we also need to generate the oneOf interface model
addOneOfNameExtension((ComposedSchema) s, nOneOf);
addOneOfInterfaceModel((ComposedSchema) s, nOneOf);
addOneOfNameExtension(s, nOneOf);
addOneOfInterfaceModel(s, nOneOf);
} else {
// else this is a component schema, so we will just use that as the oneOf interface model
addOneOfNameExtension((ComposedSchema) s, n);
addOneOfNameExtension(s, n);
}
} else if (ModelUtils.isArraySchema(s)) {
Schema items = ((ArraySchema) s).getItems();
if (ModelUtils.isComposedSchema(items)) {
addOneOfNameExtension((ComposedSchema) items, nOneOf);
addOneOfInterfaceModel((ComposedSchema) items, nOneOf);
addOneOfNameExtension(items, nOneOf);
addOneOfInterfaceModel(items, nOneOf);
}
} else if (ModelUtils.isMapSchema(s)) {
Schema addProps = ModelUtils.getAdditionalProperties(s);
if (addProps != null && ModelUtils.isComposedSchema(addProps)) {
addOneOfNameExtension((ComposedSchema) addProps, nOneOf);
addOneOfInterfaceModel((ComposedSchema) addProps, nOneOf);
addOneOfNameExtension(addProps, nOneOf);
addOneOfInterfaceModel(addProps, nOneOf);
}
}
}
@ -2273,10 +2274,9 @@ public class DefaultCodegen implements CodegenConfig {
**/
@SuppressWarnings("static-method")
public String getSchemaType(Schema schema) {
if (schema instanceof ComposedSchema) { // composed schema
ComposedSchema cs = (ComposedSchema) schema;
if (ModelUtils.isComposedSchema(schema)) { // composed schema
// Get the interfaces, i.e. the set of elements under 'allOf', 'anyOf' or 'oneOf'.
List<Schema> schemas = ModelUtils.getInterfaces(cs);
List<Schema> schemas = ModelUtils.getInterfaces(schema);
List<String> names = new ArrayList<>();
// Build a list of the schema types under each interface.
@ -2286,12 +2286,12 @@ public class DefaultCodegen implements CodegenConfig {
names.add(getSingleSchemaType(s));
}
if (cs.getAllOf() != null) {
return toAllOfName(names, cs);
} else if (cs.getAnyOf() != null) { // anyOf
return toAnyOfName(names, cs);
} else if (cs.getOneOf() != null) { // oneOf
return toOneOfName(names, cs);
if (schema.getAllOf() != null) {
return toAllOfName(names, schema);
} else if (schema.getAnyOf() != null) { // anyOf
return toAnyOfName(names, schema);
} else if (schema.getOneOf() != null) { // oneOf
return toOneOfName(names, schema);
}
}
@ -2327,7 +2327,7 @@ public class DefaultCodegen implements CodegenConfig {
* @return name of the allOf schema
*/
@SuppressWarnings("static-method")
public String toAllOfName(List<String> names, ComposedSchema composedSchema) {
public String toAllOfName(List<String> names, Schema composedSchema) {
Map<String, Object> exts = composedSchema.getExtensions();
if (exts != null && exts.containsKey("x-all-of-name")) {
return (String) exts.get("x-all-of-name");
@ -2351,7 +2351,7 @@ public class DefaultCodegen implements CodegenConfig {
* @return name of the anyOf schema
*/
@SuppressWarnings("static-method")
public String toAnyOfName(List<String> names, ComposedSchema composedSchema) {
public String toAnyOfName(List<String> names, Schema composedSchema) {
return "anyOf<" + String.join(",", names) + ">";
}
@ -2369,7 +2369,7 @@ public class DefaultCodegen implements CodegenConfig {
* @return name of the oneOf schema
*/
@SuppressWarnings("static-method")
public String toOneOfName(List<String> names, ComposedSchema composedSchema) {
public String toOneOfName(List<String> names, Schema composedSchema) {
Map<String, Object> exts = composedSchema.getExtensions();
if (exts != null && exts.containsKey("x-one-of-name")) {
return (String) exts.get("x-one-of-name");
@ -2674,7 +2674,7 @@ public class DefaultCodegen implements CodegenConfig {
Map<NamedSchema, CodegenProperty> schemaCodegenPropertyCache = new HashMap<>();
protected void updateModelForComposedSchema(CodegenModel m, Schema schema, Map<String, Schema> allDefinitions) {
final ComposedSchema composed = (ComposedSchema) schema;
final Schema composed = schema;
Map<String, Schema> properties = new LinkedHashMap<>();
List<String> required = new ArrayList<>();
Map<String, Schema> allProperties = new LinkedHashMap<>();
@ -2700,17 +2700,17 @@ public class DefaultCodegen implements CodegenConfig {
if (composed.getAllOf() != null) {
int modelImplCnt = 0; // only one inline object allowed in a ComposedModel
int modelDiscriminators = 0; // only one discriminator allowed in a ComposedModel
for (Schema innerSchema : composed.getAllOf()) { // TODO need to work with anyOf, oneOf as well
if (m.discriminator == null && innerSchema.getDiscriminator() != null) {
for (Object innerSchema : composed.getAllOf()) { // TODO need to work with anyOf, oneOf as well
if (m.discriminator == null && ((Schema) innerSchema).getDiscriminator() != null) {
LOGGER.debug("discriminator is set to null (not correctly set earlier): {}", m.name);
m.setDiscriminator(createDiscriminator(m.name, innerSchema));
m.setDiscriminator(createDiscriminator(m.name, (Schema) innerSchema));
modelDiscriminators++;
}
if (innerSchema.getXml() != null) {
m.xmlPrefix = innerSchema.getXml().getPrefix();
m.xmlNamespace = innerSchema.getXml().getNamespace();
m.xmlName = innerSchema.getXml().getName();
if (((Schema) innerSchema).getXml() != null) {
m.xmlPrefix = ((Schema) innerSchema).getXml().getPrefix();
m.xmlNamespace = ((Schema) innerSchema).getXml().getNamespace();
m.xmlName = ((Schema) innerSchema).getXml().getName();
}
if (modelDiscriminators > 1) {
LOGGER.error("Allof composed schema is inheriting >1 discriminator. Only use one discriminator: {}", composed);
@ -2888,7 +2888,7 @@ public class DefaultCodegen implements CodegenConfig {
}
protected void updateModelForObject(CodegenModel m, Schema schema) {
if (schema.getProperties() != null || schema.getRequired() != null && !(schema instanceof ComposedSchema)) {
if (schema.getProperties() != null || schema.getRequired() != null && !(ModelUtils.isComposedSchema(schema))) {
// passing null to allProperties and allRequired as there's no parent
addVars(m, unaliasPropertySchema(schema.getProperties()), schema.getRequired(), null, null);
}
@ -2917,7 +2917,7 @@ public class DefaultCodegen implements CodegenConfig {
addAdditionPropertiesToCodeGenModel(m, schema);
m.isMap = true;
}
if (schema.getProperties() != null || schema.getRequired() != null && !(schema instanceof ComposedSchema)) {
if (schema.getProperties() != null || schema.getRequired() != null && !(ModelUtils.isComposedSchema(schema))) {
// passing null to allProperties and allRequired as there's no parent
addVars(m, unaliasPropertySchema(schema.getProperties()), schema.getRequired(), null, null);
}
@ -3122,7 +3122,7 @@ public class DefaultCodegen implements CodegenConfig {
m.setRef(schema.get$ref());
}
if (schema instanceof ComposedSchema) {
if (ModelUtils.isComposedSchema(schema)) {
updateModelForComposedSchema(m, schema, allDefinitions);
}
@ -3256,11 +3256,11 @@ public class DefaultCodegen implements CodegenConfig {
return cp;
}
if (ModelUtils.isComposedSchema(refSchema)) {
ComposedSchema composedSchema = (ComposedSchema) refSchema;
Schema composedSchema = refSchema;
if (composedSchema.getAllOf() != null) {
// If our discriminator is in one of the allOf schemas break when we find it
for (Schema allOf : composedSchema.getAllOf()) {
CodegenProperty cp = discriminatorFound(composedSchemaName, allOf, discPropName, visitedSchemas);
for (Object allOf : composedSchema.getAllOf()) {
CodegenProperty cp = discriminatorFound(composedSchemaName, (Schema) allOf, discPropName, visitedSchemas);
if (cp != null) {
return cp;
}
@ -3269,9 +3269,9 @@ public class DefaultCodegen implements CodegenConfig {
if (composedSchema.getOneOf() != null && composedSchema.getOneOf().size() != 0) {
// All oneOf definitions must contain the discriminator
CodegenProperty cp = new CodegenProperty();
for (Schema oneOf : composedSchema.getOneOf()) {
String modelName = ModelUtils.getSimpleRef(oneOf.get$ref());
CodegenProperty thisCp = discriminatorFound(composedSchemaName, oneOf, discPropName, visitedSchemas);
for (Object oneOf : composedSchema.getOneOf()) {
String modelName = ModelUtils.getSimpleRef(((Schema) oneOf).get$ref());
CodegenProperty thisCp = discriminatorFound(composedSchemaName, (Schema) oneOf, discPropName, visitedSchemas);
if (thisCp == null) {
LOGGER.warn(
"'{}' defines discriminator '{}', but the referenced OneOf schema '{}' is missing {}",
@ -3292,9 +3292,9 @@ public class DefaultCodegen implements CodegenConfig {
if (composedSchema.getAnyOf() != null && composedSchema.getAnyOf().size() != 0) {
// All anyOf definitions must contain the discriminator because a min of one must be selected
CodegenProperty cp = new CodegenProperty();
for (Schema anyOf : composedSchema.getAnyOf()) {
String modelName = ModelUtils.getSimpleRef(anyOf.get$ref());
CodegenProperty thisCp = discriminatorFound(composedSchemaName, anyOf, discPropName, visitedSchemas);
for (Object anyOf : composedSchema.getAnyOf()) {
String modelName = ModelUtils.getSimpleRef(((Schema) anyOf).get$ref());
CodegenProperty thisCp = discriminatorFound(composedSchemaName, (Schema) anyOf, discPropName, visitedSchemas);
if (thisCp == null) {
LOGGER.warn(
"'{}' defines discriminator '{}', but the referenced AnyOf schema '{}' is missing {}",
@ -3343,11 +3343,11 @@ public class DefaultCodegen implements CodegenConfig {
Discriminator disc = new Discriminator();
if (ModelUtils.isComposedSchema(refSchema)) {
ComposedSchema composedSchema = (ComposedSchema) refSchema;
Schema composedSchema = refSchema;
if (composedSchema.getAllOf() != null) {
// If our discriminator is in one of the allOf schemas break when we find it
for (Schema allOf : composedSchema.getAllOf()) {
foundDisc = recursiveGetDiscriminator(allOf, visitedSchemas);
for (Object allOf : composedSchema.getAllOf()) {
foundDisc = recursiveGetDiscriminator((Schema) allOf, visitedSchemas);
if (foundDisc != null) {
disc.setPropertyName(foundDisc.getPropertyName());
disc.setMapping(foundDisc.getMapping());
@ -3360,13 +3360,13 @@ public class DefaultCodegen implements CodegenConfig {
Integer hasDiscriminatorCnt = 0;
Integer hasNullTypeCnt = 0;
Set<String> discriminatorsPropNames = new HashSet<>();
for (Schema oneOf : composedSchema.getOneOf()) {
if (ModelUtils.isNullType(oneOf)) {
for (Object oneOf : composedSchema.getOneOf()) {
if (ModelUtils.isNullType((Schema) oneOf)) {
// The null type does not have a discriminator. Skip.
hasNullTypeCnt++;
continue;
}
foundDisc = recursiveGetDiscriminator(oneOf, visitedSchemas);
foundDisc = recursiveGetDiscriminator((Schema) oneOf, visitedSchemas);
if (foundDisc != null) {
discriminatorsPropNames.add(foundDisc.getPropertyName());
hasDiscriminatorCnt++;
@ -3389,13 +3389,13 @@ public class DefaultCodegen implements CodegenConfig {
Integer hasDiscriminatorCnt = 0;
Integer hasNullTypeCnt = 0;
Set<String> discriminatorsPropNames = new HashSet<>();
for (Schema anyOf : composedSchema.getAnyOf()) {
if (ModelUtils.isNullType(anyOf)) {
for (Object anyOf : composedSchema.getAnyOf()) {
if (ModelUtils.isNullType((Schema) anyOf)) {
// The null type does not have a discriminator. Skip.
hasNullTypeCnt++;
continue;
}
foundDisc = recursiveGetDiscriminator(anyOf, visitedSchemas);
foundDisc = recursiveGetDiscriminator((Schema) anyOf, visitedSchemas);
if (foundDisc != null) {
discriminatorsPropNames.add(foundDisc.getPropertyName());
hasDiscriminatorCnt++;
@ -3430,7 +3430,7 @@ public class DefaultCodegen implements CodegenConfig {
* @param c The ComposedSchema that contains the discriminator and oneOf/anyOf schemas
* @return the list of oneOf and anyOf MappedModel that need to be added to the discriminator map
*/
protected List<MappedModel> getOneOfAnyOfDescendants(String composedSchemaName, String discPropName, ComposedSchema c) {
protected List<MappedModel> getOneOfAnyOfDescendants(String composedSchemaName, String discPropName, Schema c) {
ArrayList<List<Schema>> listOLists = new ArrayList<>();
listOLists.add(c.getOneOf());
listOLists.add(c.getAnyOf());
@ -3510,8 +3510,7 @@ public class DefaultCodegen implements CodegenConfig {
}
Schema child = schemas.get(childName);
if (ModelUtils.isComposedSchema(child)) {
ComposedSchema composedChild = (ComposedSchema) child;
List<Schema> parents = composedChild.getAllOf();
List<Schema> parents = child.getAllOf();
if (parents != null) {
for (Schema parent : parents) {
String ref = parent.get$ref();
@ -3624,7 +3623,7 @@ public class DefaultCodegen implements CodegenConfig {
}
// if there are composed oneOf/anyOf schemas, add them to this discriminator
if (ModelUtils.isComposedSchema(schema) && !this.getLegacyDiscriminatorBehavior()) {
List<MappedModel> otherDescendants = getOneOfAnyOfDescendants(schemaName, discriminatorPropertyName, (ComposedSchema) schema);
List<MappedModel> otherDescendants = getOneOfAnyOfDescendants(schemaName, discriminatorPropertyName, schema);
for (MappedModel otherDescendant : otherDescendants) {
if (!uniqueDescendants.contains(otherDescendant)) {
uniqueDescendants.add(otherDescendant);
@ -3658,15 +3657,18 @@ public class DefaultCodegen implements CodegenConfig {
* @param visitedSchemas circuit-breaker - the schemas with which the method was called before for recursive structures
*/
protected void addProperties(Map<String, Schema> properties, List<String> required, Schema schema, Set<Schema> visitedSchemas) {
if (schema == null) {
return;
}
if (!visitedSchemas.add(schema)) {
return;
}
if (schema instanceof ComposedSchema) {
ComposedSchema composedSchema = (ComposedSchema) schema;
if (ModelUtils.isComposedSchema(schema)) {
if (composedSchema.getAllOf() != null) {
for (Schema component : composedSchema.getAllOf()) {
addProperties(properties, required, component, visitedSchemas);
if (schema.getAllOf() != null) {
for (Object component : schema.getAllOf()) {
addProperties(properties, required, (Schema) component, visitedSchemas);
}
}
@ -3674,15 +3676,15 @@ public class DefaultCodegen implements CodegenConfig {
required.addAll(schema.getRequired());
}
if (composedSchema.getOneOf() != null) {
for (Schema component : composedSchema.getOneOf()) {
addProperties(properties, required, component, visitedSchemas);
if (schema.getOneOf() != null) {
for (Object component : schema.getOneOf()) {
addProperties(properties, required, (Schema) component, visitedSchemas);
}
}
if (composedSchema.getAnyOf() != null) {
for (Schema component : composedSchema.getAnyOf()) {
addProperties(properties, required, component, visitedSchemas);
if (schema.getAnyOf() != null) {
for (Object component : schema.getAnyOf()) {
addProperties(properties, required, (Schema) component, visitedSchemas);
}
}
@ -3766,10 +3768,11 @@ public class DefaultCodegen implements CodegenConfig {
if (Boolean.FALSE.equals(p.getNullable())) {
LOGGER.warn("Schema '{}' is any type, which includes the 'null' value. 'nullable' cannot be set to 'false'", p.getName());
}
ComposedSchema composedSchema = p instanceof ComposedSchema
? (ComposedSchema) p
: null;
property.isNullable = property.isNullable || composedSchema == null || composedSchema.getAllOf() == null || composedSchema.getAllOf().size() == 0;
property.isNullable = property.isNullable ||
!(ModelUtils.isComposedSchema(p)) ||
p.getAllOf() == null ||
p.getAllOf().size() == 0;
if (languageSpecificPrimitives.contains(property.dataType)) {
property.isPrimitiveType = true;
}
@ -5746,7 +5749,7 @@ public class DefaultCodegen implements CodegenConfig {
* @param model codegen model
* @param modelName model name
*/
protected void addImport(ComposedSchema composed, Schema childSchema, CodegenModel model, String modelName ) {
protected void addImport(Schema composed, Schema childSchema, CodegenModel model, String modelName ) {
if (composed == null || childSchema == null) {
return;
}
@ -7920,12 +7923,12 @@ public class DefaultCodegen implements CodegenConfig {
/**
* Add "x-one-of-name" extension to a given oneOf schema (assuming it has at least 1 oneOf elements)
*
* @param s schema to add the extension to
* @param name name of the parent oneOf schema
* @param schema schema to add the extension to
* @param name name of the parent oneOf schema
*/
public void addOneOfNameExtension(ComposedSchema s, String name) {
if (s.getOneOf() != null && s.getOneOf().size() > 0) {
s.addExtension("x-one-of-name", name);
public void addOneOfNameExtension(Schema schema, String name) {
if (schema.getOneOf() != null && schema.getOneOf().size() > 0) {
schema.addExtension("x-one-of-name", name);
}
}
@ -7935,7 +7938,7 @@ public class DefaultCodegen implements CodegenConfig {
* @param cs ComposedSchema object to create as interface model
* @param type name to use for the generated interface model
*/
public void addOneOfInterfaceModel(ComposedSchema cs, String type) {
public void addOneOfInterfaceModel(Schema cs, String type) {
if (cs.getOneOf() == null) {
return;
}
@ -7944,9 +7947,9 @@ public class DefaultCodegen implements CodegenConfig {
cm.setDiscriminator(createDiscriminator("", cs));
for (Schema o : Optional.ofNullable(cs.getOneOf()).orElse(Collections.emptyList())) {
if (o.get$ref() == null) {
if (cm.discriminator != null && o.get$ref() == null) {
for (Object o : Optional.ofNullable(cs.getOneOf()).orElse(Collections.emptyList())) {
if (((Schema) o).get$ref() == null) {
if (cm.discriminator != null && ((Schema) o).get$ref() == null) {
// OpenAPI spec states that inline objects should not be considered when discriminator is used
// https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#discriminatorObject
LOGGER.warn("Ignoring inline object in oneOf definition of {}, since discriminator is used", type);
@ -7955,7 +7958,7 @@ public class DefaultCodegen implements CodegenConfig {
}
continue;
}
cm.oneOf.add(toModelName(ModelUtils.getSimpleRef(o.get$ref())));
cm.oneOf.add(toModelName(ModelUtils.getSimpleRef(((Schema) o).get$ref())));
}
cm.name = type;
cm.classname = type;
@ -8126,7 +8129,7 @@ public class DefaultCodegen implements CodegenConfig {
}
private CodegenComposedSchemas getComposedSchemas(Schema schema) {
if (!(schema instanceof ComposedSchema) && schema.getNot() == null) {
if (!(ModelUtils.isComposedSchema(schema)) && schema.getNot() == null) {
return null;
}
Schema notSchema = schema.getNot();
@ -8137,11 +8140,10 @@ public class DefaultCodegen implements CodegenConfig {
List<CodegenProperty> allOf = new ArrayList<>();
List<CodegenProperty> oneOf = new ArrayList<>();
List<CodegenProperty> anyOf = new ArrayList<>();
if (schema instanceof ComposedSchema) {
ComposedSchema cs = (ComposedSchema) schema;
allOf = getComposedProperties(cs.getAllOf(), "all_of");
oneOf = getComposedProperties(cs.getOneOf(), "one_of");
anyOf = getComposedProperties(cs.getAnyOf(), "any_of");
if (ModelUtils.isComposedSchema(schema)) {
allOf = getComposedProperties(schema.getAllOf(), "all_of");
oneOf = getComposedProperties(schema.getOneOf(), "one_of");
anyOf = getComposedProperties(schema.getAnyOf(), "any_of");
}
return new CodegenComposedSchemas(
allOf,

View File

@ -58,6 +58,7 @@ import org.openapitools.codegen.utils.ImplementationVersion;
import org.openapitools.codegen.utils.ModelUtils;
import org.openapitools.codegen.utils.ProcessUtils;
import org.openapitools.codegen.utils.URLPathUtils;
import org.openapitools.codegen.utils.SemVer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -262,6 +263,10 @@ public class DefaultGenerator implements Generator {
// normalize the spec
try {
if (config.getUseOpenAPINormalizer()) {
SemVer version = new SemVer(openAPI.getOpenapi());
if (version.atLeast("3.1.0")) {
config.openapiNormalizer().put("NORMALIZE_31SPEC", "true");
}
OpenAPINormalizer openapiNormalizer = new OpenAPINormalizer(openAPI, config.openapiNormalizer());
openapiNormalizer.normalize();
}

View File

@ -216,32 +216,30 @@ public class InlineModelResolver {
return true;
}
}
if (schema instanceof ComposedSchema) {
if (ModelUtils.isComposedSchema(schema)) {
// allOf, anyOf, oneOf
ComposedSchema m = (ComposedSchema) schema;
boolean isSingleAllOf = m.getAllOf() != null && m.getAllOf().size() == 1;
boolean isReadOnly = m.getReadOnly() != null && m.getReadOnly();
boolean isNullable = m.getNullable() != null && m.getNullable();
boolean isSingleAllOf = schema.getAllOf() != null && schema.getAllOf().size() == 1;
boolean isReadOnly = schema.getReadOnly() != null && schema.getReadOnly();
boolean isNullable = schema.getNullable() != null && schema.getNullable();
if (isSingleAllOf && (isReadOnly || isNullable)) {
// Check if this composed schema only contains an allOf and a readOnly or nullable.
ComposedSchema c = new ComposedSchema();
c.setAllOf(m.getAllOf());
c.setReadOnly(m.getReadOnly());
c.setNullable(m.getNullable());
if (m.equals(c)) {
return isModelNeeded(m.getAllOf().get(0), visitedSchemas);
c.setAllOf(schema.getAllOf());
c.setReadOnly(schema.getReadOnly());
c.setNullable(schema.getNullable());
if (schema.equals(c)) {
return isModelNeeded((Schema) schema.getAllOf().get(0), visitedSchemas);
}
} else if (isSingleAllOf && StringUtils.isNotEmpty(m.getAllOf().get(0).get$ref())) {
} else if (isSingleAllOf && StringUtils.isNotEmpty(((Schema) schema.getAllOf().get(0)).get$ref())) {
// single allOf and it's a ref
return isModelNeeded(m.getAllOf().get(0), visitedSchemas);
return isModelNeeded((Schema) schema.getAllOf().get(0), visitedSchemas);
}
if (m.getAllOf() != null && !m.getAllOf().isEmpty()) {
if (schema.getAllOf() != null && !schema.getAllOf().isEmpty()) {
// check to ensure at least one of the allOf item is model
for (Schema inner : m.getAllOf()) {
if (isModelNeeded(ModelUtils.getReferencedSchema(openAPI, inner), visitedSchemas)) {
for (Object inner : schema.getAllOf()) {
if (isModelNeeded(ModelUtils.getReferencedSchema(openAPI, (Schema) inner), visitedSchemas)) {
return true;
}
}
@ -249,10 +247,10 @@ public class InlineModelResolver {
return false;
}
if (m.getAnyOf() != null && !m.getAnyOf().isEmpty()) {
if (schema.getAnyOf() != null && !schema.getAnyOf().isEmpty()) {
return true;
}
if (m.getOneOf() != null && !m.getOneOf().isEmpty()) {
if (schema.getOneOf() != null && !schema.getOneOf().isEmpty()) {
return true;
}
}
@ -273,7 +271,7 @@ public class InlineModelResolver {
// any to catch OpenAPI violations
if (isModelNeeded(schema) || "object".equals(schema.getType()) ||
schema.getProperties() != null || schema.getAdditionalProperties() != null ||
schema instanceof ComposedSchema) {
ModelUtils.isComposedSchema(schema)) {
LOGGER.error("Illegal schema found with $ref combined with other properties," +
" no properties should be defined alongside a $ref:\n " + schema.toString());
}
@ -295,13 +293,13 @@ public class InlineModelResolver {
// If this schema should be split into its own model, do so
Schema refSchema = this.makeSchemaInComponents(schemaName, prop);
props.put(propName, refSchema);
} else if (prop instanceof ComposedSchema) {
ComposedSchema m = (ComposedSchema) prop;
if (m.getAllOf() != null && m.getAllOf().size() == 1 &&
!(m.getAllOf().get(0).getType() == null || "object".equals(m.getAllOf().get(0).getType()))) {
} else if (ModelUtils.isComposedSchema(prop)) {
if (prop.getAllOf() != null && prop.getAllOf().size() == 1 &&
!(((Schema) prop.getAllOf().get(0)).getType() == null ||
"object".equals(((Schema) prop.getAllOf().get(0)).getType()))) {
// allOf with only 1 type (non-model)
LOGGER.info("allOf schema used by the property `{}` replaced by its only item (a type)", propName);
props.put(propName, m.getAllOf().get(0));
props.put(propName, (Schema) prop.getAllOf().get(0));
}
}
}
@ -357,71 +355,69 @@ public class InlineModelResolver {
}
}
// Check allOf, anyOf, oneOf for inline models
if (schema instanceof ComposedSchema) {
ComposedSchema m = (ComposedSchema) schema;
if (m.getAllOf() != null) {
if (ModelUtils.isComposedSchema(schema)) {
if (schema.getAllOf() != null) {
List<Schema> newAllOf = new ArrayList<Schema>();
boolean atLeastOneModel = false;
for (Schema inner : m.getAllOf()) {
String schemaName = resolveModelName(inner.getTitle(), modelPrefix + "_allOf");
for (Object inner : schema.getAllOf()) {
String schemaName = resolveModelName(((Schema) inner).getTitle(), modelPrefix + "_allOf");
// Recurse to create $refs for inner models
gatherInlineModels(inner, schemaName);
if (isModelNeeded(inner)) {
gatherInlineModels((Schema) inner, schemaName);
if (isModelNeeded((Schema) inner)) {
if (Boolean.TRUE.equals(this.refactorAllOfInlineSchemas)) {
Schema refSchema = this.makeSchemaInComponents(schemaName, inner);
Schema refSchema = this.makeSchemaInComponents(schemaName, (Schema) inner);
newAllOf.add(refSchema); // replace with ref
atLeastOneModel = true;
} else { // do not refactor allOf inline schemas
newAllOf.add(inner);
newAllOf.add((Schema) inner);
atLeastOneModel = true;
}
} else {
newAllOf.add(inner);
newAllOf.add((Schema) inner);
}
}
if (atLeastOneModel) {
m.setAllOf(newAllOf);
schema.setAllOf(newAllOf);
} else {
// allOf is just one or more types only so do not generate the inline allOf model
if (m.getAllOf().size() == 1) {
if (schema.getAllOf().size() == 1) {
// handle earlier in this function when looping through properties
} else if (m.getAllOf().size() > 1) {
} else if (schema.getAllOf().size() > 1) {
LOGGER.warn("allOf schema `{}` containing multiple types (not model) is not supported at the moment.", schema.getName());
} else {
LOGGER.error("allOf schema `{}` contains no items.", schema.getName());
}
}
}
if (m.getAnyOf() != null) {
if (schema.getAnyOf() != null) {
List<Schema> newAnyOf = new ArrayList<Schema>();
for (Schema inner : m.getAnyOf()) {
String schemaName = resolveModelName(inner.getTitle(), modelPrefix + "_anyOf");
for (Object inner : schema.getAnyOf()) {
String schemaName = resolveModelName(((Schema) inner).getTitle(), modelPrefix + "_anyOf");
// Recurse to create $refs for inner models
gatherInlineModels(inner, schemaName);
if (isModelNeeded(inner)) {
Schema refSchema = this.makeSchemaInComponents(schemaName, inner);
gatherInlineModels((Schema) inner, schemaName);
if (isModelNeeded((Schema) inner)) {
Schema refSchema = this.makeSchemaInComponents(schemaName, (Schema) inner);
newAnyOf.add(refSchema); // replace with ref
} else {
newAnyOf.add(inner);
newAnyOf.add((Schema) inner);
}
}
m.setAnyOf(newAnyOf);
schema.setAnyOf(newAnyOf);
}
if (m.getOneOf() != null) {
if (schema.getOneOf() != null) {
List<Schema> newOneOf = new ArrayList<Schema>();
for (Schema inner : m.getOneOf()) {
String schemaName = resolveModelName(inner.getTitle(), modelPrefix + "_oneOf");
for (Object inner : schema.getOneOf()) {
String schemaName = resolveModelName(((Schema) inner).getTitle(), modelPrefix + "_oneOf");
// Recurse to create $refs for inner models
gatherInlineModels(inner, schemaName);
if (isModelNeeded(inner)) {
Schema refSchema = this.makeSchemaInComponents(schemaName, inner);
gatherInlineModels((Schema) inner, schemaName);
if (isModelNeeded((Schema) inner)) {
Schema refSchema = this.makeSchemaInComponents(schemaName, (Schema) inner);
newOneOf.add(refSchema); // replace with ref
} else {
newOneOf.add(inner);
newOneOf.add((Schema) inner);
}
}
m.setOneOf(newOneOf);
schema.setOneOf(newOneOf);
}
}
// Check not schema
@ -638,11 +634,10 @@ public class InlineModelResolver {
} else if (ModelUtils.isOneOf(model)) { // contains oneOf only
gatherInlineModels(model, modelName);
} else if (ModelUtils.isComposedSchema(model)) {
ComposedSchema m = (ComposedSchema) model;
// inline child schemas
flattenComposedChildren(modelName + "_allOf", m.getAllOf(), !Boolean.TRUE.equals(this.refactorAllOfInlineSchemas));
flattenComposedChildren(modelName + "_anyOf", m.getAnyOf(), false);
flattenComposedChildren(modelName + "_oneOf", m.getOneOf(), false);
flattenComposedChildren(modelName + "_allOf", model.getAllOf(), !Boolean.TRUE.equals(this.refactorAllOfInlineSchemas));
flattenComposedChildren(modelName + "_anyOf", model.getAnyOf(), false);
flattenComposedChildren(modelName + "_oneOf", model.getOneOf(), false);
} else {
gatherInlineModels(model, modelName);
}

View File

@ -19,6 +19,7 @@ package org.openapitools.codegen;
import io.swagger.v3.oas.models.*;
import io.swagger.v3.oas.models.callbacks.Callback;
import io.swagger.v3.oas.models.headers.Header;
import io.swagger.v3.oas.models.media.*;
import io.swagger.v3.oas.models.parameters.Parameter;
import io.swagger.v3.oas.models.parameters.RequestBody;
@ -87,6 +88,9 @@ public class OpenAPINormalizer {
// the allOf contains a new schema containing the properties in the top level
final String REFACTOR_ALLOF_WITH_PROPERTIES_ONLY = "REFACTOR_ALLOF_WITH_PROPERTIES_ONLY";
// when set to true, normalize OpenAPI 3.1 spec to make it work with the generator
final String NORMALIZE_31SPEC = "NORMALIZE_31SPEC";
// ============= end of rules =============
/**
@ -115,6 +119,7 @@ public class OpenAPINormalizer {
ruleNames.add(SET_TAGS_FOR_ALL_OPERATIONS);
ruleNames.add(ADD_UNSIGNED_TO_INTEGER_WITH_INVALID_MAX_VALUE);
ruleNames.add(REFACTOR_ALLOF_WITH_PROPERTIES_ONLY);
ruleNames.add(NORMALIZE_31SPEC);
// rules that are default to true
rules.put(SIMPLIFY_ONEOF_ANYOF, true);
@ -247,11 +252,13 @@ public class OpenAPINormalizer {
} else if (mediaType.getSchema() == null) {
continue;
} else {
normalizeSchema(mediaType.getSchema(), new HashSet<>());
Schema newSchema = normalizeSchema(mediaType.getSchema(), new HashSet<>());
mediaType.setSchema(newSchema);
}
}
}
/**
* Normalizes schemas in RequestBody
*
@ -291,7 +298,8 @@ public class OpenAPINormalizer {
if (parameter.getSchema() == null) {
continue;
} else {
normalizeSchema(parameter.getSchema(), new HashSet<>());
Schema newSchema = normalizeSchema(parameter.getSchema(), new HashSet<>());
parameter.setSchema(newSchema);
}
}
}
@ -312,10 +320,29 @@ public class OpenAPINormalizer {
continue;
} else {
normalizeContent(responsesEntry.getValue().getContent());
normalizeHeaders(responsesEntry.getValue().getHeaders());
}
}
}
/**
* Normalizes schemas in headers
*
* @param headers a map of headers
*/
private void normalizeHeaders(Map<String, Header> headers) {
if (headers == null || headers.isEmpty()) {
return;
}
for (String headerKey : headers.keySet()) {
Header h = headers.get(headerKey);
Schema updatedHeader = normalizeSchema(h.getSchema(), new HashSet<>());
h.setSchema(updatedHeader);
}
}
/**
* Normalizes schemas in components
*/
@ -408,7 +435,7 @@ public class OpenAPINormalizer {
} else if (schema instanceof IntegerSchema) {
normalizeIntegerSchema(schema, visitedSchemas);
} else if (schema instanceof Schema) {
normalizeSchemaWithOnlyProperties(schema, visitedSchemas);
return normalizeSimpleSchema(schema, visitedSchemas);
} else {
throw new RuntimeException("Unknown schema type found in normalizer: " + schema);
}
@ -416,6 +443,10 @@ public class OpenAPINormalizer {
return schema;
}
private Schema normalizeSimpleSchema(Schema schema, Set<Schema> visitedSchemas) {
return processNormalize31Spec(schema, visitedSchemas);
}
private void normalizeBooleanSchema(Schema schema, Set<Schema> visitedSchemas) {
processSimplifyBooleanEnum(schema);
}
@ -424,10 +455,6 @@ public class OpenAPINormalizer {
processAddUnsignedToIntegerWithInvalidMaxValue(schema);
}
private void normalizeSchemaWithOnlyProperties(Schema schema, Set<Schema> visitedSchemas) {
// normalize non-composed schema (e.g. schema with only properties)
}
private void normalizeProperties(Map<String, Schema> properties, Set<Schema> visitedSchemas) {
if (properties == null) {
return;
@ -670,9 +697,9 @@ public class OpenAPINormalizer {
/**
* Check if the schema is of type 'null'
*
* <p>
* Return true if the schema's type is 'null' or not specified
*
*
* @param schema Schema
*/
private boolean isNullTypeSchema(Schema schema) {
@ -803,7 +830,7 @@ public class OpenAPINormalizer {
}
}
/*
/**
* When set to true, refactor schema with allOf and properties in the same level to a schema with allOf only and
* the allOf contains a new schema containing the properties in the top level.
*
@ -844,5 +871,70 @@ public class OpenAPINormalizer {
return schema;
}
/**
* When set to true, normalize schema so that it works well with the generator.
*
* @param schema Schema
* @param visitedSchemas a set of visited schemas
* @return Schema
*/
private Schema processNormalize31Spec(Schema schema, Set<Schema> visitedSchemas) {
if (!getRule(NORMALIZE_31SPEC)) {
return schema;
}
// process null
if (schema.getTypes().contains("null")) {
schema.setNullable(true);
schema.getTypes().remove("null");
}
// only one item (type) left
if (schema.getTypes().size() == 1) {
String type = String.valueOf(schema.getTypes().iterator().next());
if ("array".equals(type)) {
ArraySchema as = new ArraySchema();
as.setXml(schema.getXml());
// `items` is also a json schema
if (StringUtils.isNotEmpty(schema.getItems().get$ref())) {
Schema ref = new Schema();
ref.set$ref(schema.getItems().get$ref());
as.setItems(ref);
} else { // inline schema (e.g. model, string, etc)
Schema updatedItems = normalizeSchema(schema.getItems(), visitedSchemas);
as.setItems(updatedItems);
}
return as;
} else { // other primitive type such as string
// set type (3.0 spec) directly
schema.setType(type);
}
} else { // more than 1 item
// convert to anyOf and keep all other attributes (e.g. nullable, description)
// the same. No need to handle null as it should have been removed at this point.
for (Object type : schema.getTypes()) {
switch (String.valueOf(type)) {
case "string":
schema.addAnyOfItem(new StringSchema());
break;
case "integer":
schema.addAnyOfItem(new IntegerSchema());
break;
case "number":
schema.addAnyOfItem(new NumberSchema());
break;
case "boolean":
schema.addAnyOfItem(new BooleanSchema());
break;
default:
LOGGER.error("Type {} not yet supported in openapi-normalizer to process OpenAPI 3.1 spec with multiple types.");
LOGGER.error("Please report the issue via https://github.com/OpenAPITools/openapi-generator/issues/new/.");
}
}
}
return schema;
}
// ===================== end of rules =====================
}

View File

@ -1062,7 +1062,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
} else { // has default value
return toArrayDefaultValue(cp, schema);
}
} else if (ModelUtils.isMapSchema(schema) && !(schema instanceof ComposedSchema)) {
} else if (ModelUtils.isMapSchema(schema) && !(ModelUtils.isComposedSchema(schema))) {
if (schema.getProperties() != null && schema.getProperties().size() > 0) {
// object is complex object with free-form additional properties
if (schema.getDefault() != null) {
@ -1645,11 +1645,11 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
.map(Schema::getProperties))
.forEach(schemas -> schemas.replaceAll(
(name, s) -> Stream.of(s)
.filter(schema -> schema instanceof ComposedSchema)
.map(schema -> (ComposedSchema) schema)
.filter(schema -> Objects.nonNull(schema.getAnyOf()))
.flatMap(schema -> schema.getAnyOf().stream())
.filter(schema -> Objects.nonNull(schema.getEnum()))
.filter(schema -> ModelUtils.isComposedSchema((Schema) schema))
//.map(schema -> (ComposedSchema) schema)
.filter(schema -> Objects.nonNull(((Schema) schema).getAnyOf()))
.flatMap(schema -> ((Schema) schema).getAnyOf().stream())
.filter(schema -> Objects.nonNull(((Schema) schema).getEnum()))
.findFirst()
.orElse((Schema) s)));
}

View File

@ -1143,7 +1143,7 @@ public abstract class AbstractKotlinCodegen extends DefaultCodegen implements Co
* ModelUtils.isMapSchema
* In other generators, isMap is true for all type object schemas
*/
if (schema.getProperties() != null || schema.getRequired() != null && !(schema instanceof ComposedSchema)) {
if (schema.getProperties() != null || schema.getRequired() != null && !(ModelUtils.isComposedSchema(schema))) {
// passing null to allProperties and allRequired as there's no parent
addVars(m, unaliasPropertySchema(schema.getProperties()), schema.getRequired(), null, null);
}

View File

@ -1135,21 +1135,21 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp
}
@Override
public String toAnyOfName(List<String> names, ComposedSchema composedSchema) {
public String toAnyOfName(List<String> names, Schema composedSchema) {
List<String> types = getTypesFromSchemas(composedSchema.getAnyOf());
return String.join(" | ", types);
}
@Override
public String toOneOfName(List<String> names, ComposedSchema composedSchema) {
public String toOneOfName(List<String> names, Schema composedSchema) {
List<String> types = getTypesFromSchemas(composedSchema.getOneOf());
return String.join(" | ", types);
}
@Override
public String toAllOfName(List<String> names, ComposedSchema composedSchema) {
public String toAllOfName(List<String> names, Schema composedSchema) {
List<String> types = getTypesFromSchemas(composedSchema.getAllOf());
return String.join(" & ", types);

View File

@ -1631,7 +1631,7 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen {
* ModelUtils.isMapSchema
* In other generators, isMap is true for all type object schemas
*/
if (schema.getProperties() != null || schema.getRequired() != null && !(schema instanceof ComposedSchema)) {
if (schema.getProperties() != null || schema.getRequired() != null && !(ModelUtils.isComposedSchema(schema))) {
// passing null to allProperties and allRequired as there's no parent
addVars(m, unaliasPropertySchema(schema.getProperties()), schema.getRequired(), null, null);
}

View File

@ -1142,7 +1142,7 @@ public class CSharpReducedClientCodegen extends AbstractCSharpCodegen {
* ModelUtils.isMapSchema
* In other generators, isMap is true for all type object schemas
*/
if (schema.getProperties() != null || schema.getRequired() != null && !(schema instanceof ComposedSchema)) {
if (schema.getProperties() != null || schema.getRequired() != null && !(ModelUtils.isComposedSchema(schema))) {
// passing null to allProperties and allRequired as there's no parent
addVars(m, unaliasPropertySchema(schema.getProperties()), schema.getRequired(), null, null);
}

View File

@ -1233,7 +1233,7 @@ public class JavascriptApolloClientCodegen extends DefaultCodegen implements Cod
public GeneratorLanguage generatorLanguage() { return GeneratorLanguage.JAVASCRIPT; }
@Override
protected void addImport(ComposedSchema composed, Schema childSchema, CodegenModel model, String modelName ) {
protected void addImport(Schema composed, Schema childSchema, CodegenModel model, String modelName ) {
// import everything (including child schema of a composed schema)
addImport(model, modelName);
}

View File

@ -1242,7 +1242,7 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
}
@Override
protected void addImport(ComposedSchema composed, Schema childSchema, CodegenModel model, String modelName) {
protected void addImport(Schema composed, Schema childSchema, CodegenModel model, String modelName) {
// import everything (including child schema of a composed schema)
addImport(model, modelName);
}

View File

@ -266,19 +266,19 @@ public class N4jsClientCodegen extends DefaultCodegen implements CodegenConfig {
}
@Override
public String toAnyOfName(List<String> names, ComposedSchema composedSchema) {
public String toAnyOfName(List<String> names, Schema composedSchema) {
List<String> types = getTypesFromSchemas(composedSchema.getAnyOf());
return String.join(" | ", types);
}
@Override
public String toOneOfName(List<String> names, ComposedSchema composedSchema) {
public String toOneOfName(List<String> names, Schema composedSchema) {
List<String> types = getTypesFromSchemas(composedSchema.getOneOf());
return String.join(" | ", types);
}
@Override
public String toAllOfName(List<String> names, ComposedSchema composedSchema) {
public String toAllOfName(List<String> names, Schema composedSchema) {
List<String> types = getTypesFromSchemas(composedSchema.getAllOf());
return String.join(" & ", types);
}

View File

@ -1245,7 +1245,7 @@ public class RustServerCodegen extends AbstractRustCodegen implements CodegenCon
}
@Override
public String toOneOfName(List<String> names, ComposedSchema composedSchema) {
public String toOneOfName(List<String> names, Schema composedSchema) {
List<Schema> schemas = ModelUtils.getInterfaces(composedSchema);
List<String> types = new ArrayList<>();
@ -1256,7 +1256,7 @@ public class RustServerCodegen extends AbstractRustCodegen implements CodegenCon
}
@Override
public String toAnyOfName(List<String> names, ComposedSchema composedSchema) {
public String toAnyOfName(List<String> names, Schema composedSchema) {
List<Schema> schemas = ModelUtils.getInterfaces(composedSchema);
List<String> types = new ArrayList<>();

View File

@ -313,7 +313,7 @@ public class TypeScriptAxiosClientCodegen extends AbstractTypeScriptClientCodege
}
@Override
protected void addImport(ComposedSchema composed, Schema childSchema, CodegenModel model, String modelName) {
protected void addImport(Schema composed, Schema childSchema, CodegenModel model, String modelName) {
// import everything (including child schema of a composed schema)
addImport(model, modelName);
}

View File

@ -423,7 +423,7 @@ public class TypeScriptRxjsClientCodegen extends AbstractTypeScriptClientCodegen
}
@Override
protected void addImport(ComposedSchema composed, Schema childSchema, CodegenModel model, String modelName) {
protected void addImport(Schema composed, Schema childSchema, CodegenModel model, String modelName) {
// import everything (including child schema of a composed schema)
addImport(model, modelName);
}

View File

@ -331,20 +331,20 @@ public class ModelUtils {
}
}
}
if (schema instanceof ComposedSchema) {
List<Schema> oneOf = ((ComposedSchema) schema).getOneOf();
if (isComposedSchema(schema)) {
List<Schema> oneOf = schema.getOneOf();
if (oneOf != null) {
for (Schema s : oneOf) {
visitSchema(openAPI, s, mimeType, visitedSchemas, visitor);
}
}
List<Schema> allOf = ((ComposedSchema) schema).getAllOf();
List<Schema> allOf = schema.getAllOf();
if (allOf != null) {
for (Schema s : allOf) {
visitSchema(openAPI, s, mimeType, visitedSchemas, visitor);
}
}
List<Schema> anyOf = ((ComposedSchema) schema).getAnyOf();
List<Schema> anyOf = schema.getAnyOf();
if (anyOf != null) {
for (Schema s : anyOf) {
visitSchema(openAPI, s, mimeType, visitedSchemas, visitor);
@ -453,7 +453,32 @@ public class ModelUtils {
* @return true if the specified schema is a Composed schema.
*/
public static boolean isComposedSchema(Schema schema) {
return schema instanceof ComposedSchema;
if (schema == null) {
return false;
}
// in 3.0, ComposeSchema is used for anyOf/oneOf/allOf
// in 3.1, it's not the case so we need more checks below
if (schema instanceof ComposedSchema) {
return true;
}
// has oneOf
if (schema.getOneOf() != null) {
return true;
}
// has anyOf
if (schema.getAnyOf() != null) {
return true;
}
// has allOf
if (schema.getAllOf() != null) {
return true;
}
return false;
}
/**
@ -678,7 +703,8 @@ public class ModelUtils {
// has properties
((null != schema.getProperties() && !schema.getProperties().isEmpty())
// composed schema is a model, consider very simple ObjectSchema a model
|| (schema instanceof ComposedSchema || schema instanceof ObjectSchema));
|| isComposedSchema(schema)
|| schema instanceof ObjectSchema);
}
/**
@ -752,9 +778,8 @@ public class ModelUtils {
}
// not free-form if allOf, anyOf, oneOf is not empty
if (schema instanceof ComposedSchema) {
ComposedSchema cs = (ComposedSchema) schema;
List<Schema> interfaces = ModelUtils.getInterfaces(cs);
if (isComposedSchema(schema)) {
List<Schema> interfaces = ModelUtils.getInterfaces(schema);
if (interfaces != null && !interfaces.isEmpty()) {
return false;
}
@ -1053,8 +1078,8 @@ public class ModelUtils {
return true;
}
}
if (schema instanceof ComposedSchema) {
List<Schema> oneOf = ((ComposedSchema) schema).getOneOf();
if (isComposedSchema(schema)) {
List<Schema> oneOf = schema.getOneOf();
if (oneOf != null) {
for (Schema s : oneOf) {
if (hasSelfReference(openAPI, s, visitedSchemaNames)) {
@ -1062,7 +1087,7 @@ public class ModelUtils {
}
}
}
List<Schema> allOf = ((ComposedSchema) schema).getAllOf();
List<Schema> allOf = schema.getAllOf();
if (allOf != null) {
for (Schema s : allOf) {
if (hasSelfReference(openAPI, s, visitedSchemaNames)) {
@ -1070,7 +1095,7 @@ public class ModelUtils {
}
}
}
List<Schema> anyOf = ((ComposedSchema) schema).getAnyOf();
List<Schema> anyOf = schema.getAnyOf();
if (anyOf != null) {
for (Schema s : anyOf) {
if (hasSelfReference(openAPI, s, visitedSchemaNames)) {
@ -1270,8 +1295,8 @@ public class ModelUtils {
Map<String, List<Entry<String, Schema>>> groupedByParent = allSchemas.entrySet().stream()
.filter(entry -> isComposedSchema(entry.getValue()))
.filter(entry -> getParentName((ComposedSchema) entry.getValue(), allSchemas) != null)
.collect(Collectors.groupingBy(entry -> getParentName((ComposedSchema) entry.getValue(), allSchemas)));
.filter(entry -> getParentName((Schema) entry.getValue(), allSchemas) != null)
.collect(Collectors.groupingBy(entry -> getParentName((Schema) entry.getValue(), allSchemas)));
return groupedByParent.entrySet().stream()
.collect(Collectors.toMap(entry -> entry.getKey(), entry -> entry.getValue().stream().map(e -> e.getKey()).collect(Collectors.toList())));
@ -1283,7 +1308,7 @@ public class ModelUtils {
* @param composed schema (alias or direct reference)
* @return a list of schema defined in allOf, anyOf or oneOf
*/
public static List<Schema> getInterfaces(ComposedSchema composed) {
public static List<Schema> getInterfaces(Schema composed) {
if (composed.getAllOf() != null && !composed.getAllOf().isEmpty()) {
return composed.getAllOf();
} else if (composed.getAnyOf() != null && !composed.getAnyOf().isEmpty()) {
@ -1324,7 +1349,7 @@ public class ModelUtils {
* @param allSchemas all schemas
* @return the name of the parent model
*/
public static String getParentName(ComposedSchema composedSchema, Map<String, Schema> allSchemas) {
public static String getParentName(Schema composedSchema, Map<String, Schema> allSchemas) {
List<Schema> interfaces = getInterfaces(composedSchema);
int nullSchemaChildrenCount = 0;
boolean hasAmbiguousParents = false;
@ -1376,7 +1401,7 @@ public class ModelUtils {
* @param includeAncestors if true, include the indirect ancestors in the return value. If false, return the direct parents.
* @return the name of the parent model
*/
public static List<String> getAllParentsName(ComposedSchema composedSchema, Map<String, Schema> allSchemas, boolean includeAncestors) {
public static List<String> getAllParentsName(Schema composedSchema, Map<String, Schema> allSchemas, boolean includeAncestors) {
List<Schema> interfaces = getInterfaces(composedSchema);
List<String> names = new ArrayList<String>();
@ -1392,8 +1417,8 @@ public class ModelUtils {
} else if (hasOrInheritsDiscriminator(s, allSchemas, new ArrayList<Schema>())) {
// discriminator.propertyName is used or x-parent is used
names.add(parentName);
if (includeAncestors && s instanceof ComposedSchema) {
names.addAll(getAllParentsName((ComposedSchema) s, allSchemas, true));
if (includeAncestors && isComposedSchema(s)) {
names.addAll(getAllParentsName(s, allSchemas, true));
}
} else {
// not a parent since discriminator.propertyName is not set
@ -1433,9 +1458,8 @@ public class ModelUtils {
} else {
LOGGER.error("Failed to obtain schema from {}", parentName);
}
} else if (schema instanceof ComposedSchema) {
final ComposedSchema composed = (ComposedSchema) schema;
final List<Schema> interfaces = getInterfaces(composed);
} else if (isComposedSchema(schema)) {
final List<Schema> interfaces = getInterfaces(schema);
for (Schema i : interfaces) {
if (hasOrInheritsDiscriminator(i, allSchemas, visitedSchemas)) {
return true;
@ -1502,8 +1526,8 @@ public class ModelUtils {
return Boolean.parseBoolean(schema.getExtensions().get("x-nullable").toString());
}
// In OAS 3.1, the recommended way to define a nullable property or object is to use oneOf.
if (schema instanceof ComposedSchema) {
return isNullableComposedSchema(((ComposedSchema) schema));
if (isComposedSchema(schema)) {
return isNullableComposedSchema(schema);
}
return false;
}
@ -1524,7 +1548,7 @@ public class ModelUtils {
* @param schema the OAS composed schema.
* @return true if the composed schema is nullable.
*/
public static boolean isNullableComposedSchema(ComposedSchema schema) {
public static boolean isNullableComposedSchema(Schema schema) {
List<Schema> oneOf = schema.getOneOf();
if (oneOf != null && oneOf.size() <= 2) {
for (Schema s : oneOf) {

View File

@ -69,13 +69,12 @@ class OpenApiSchemaValidations extends GenericValidator<SchemaWrapper> {
Schema schema = schemaWrapper.getSchema();
ValidationRule.Result result = ValidationRule.Pass.empty();
if (schema instanceof ComposedSchema) {
final ComposedSchema composed = (ComposedSchema) schema;
if (ModelUtils.isComposedSchema(schema)) {
// check for loosely defined oneOf extension requirements.
// This is a recommendation because the 3.0.x spec is not clear enough on usage of oneOf.
// see https://json-schema.org/draft/2019-09/json-schema-core.html#rfc.section.9.2.1.3 and the OAS section on 'Composition and Inheritance'.
if (composed.getOneOf() != null && composed.getOneOf().size() > 0) {
if (composed.getProperties() != null && composed.getProperties().size() >= 1 && composed.getProperties().get("discriminator") == null) {
if (schema.getOneOf() != null && schema.getOneOf().size() > 0) {
if (schema.getProperties() != null && schema.getProperties().size() >= 1 && schema.getProperties().get("discriminator") == null) {
// not necessarily "invalid" here, but we trigger the recommendation which requires the method to return false.
result = ValidationRule.Fail.empty();
}
@ -91,7 +90,7 @@ class OpenApiSchemaValidations extends GenericValidator<SchemaWrapper> {
* Note: the validator invokes checkNullType() for every top-level schema in the OAS document. The method
* is not called for nested schemas that are defined inline.
*
* @param schema An input schema, regardless of the type of schema.
* @param schemaWrapper An input schema, regardless of the type of schema.
* @return {@link ValidationRule.Pass} if the check succeeds, otherwise {@link ValidationRule.Fail}
*/
private static ValidationRule.Result checkNullType(SchemaWrapper schemaWrapper) {

View File

@ -807,7 +807,7 @@ public class InlineModelResolverTest {
OpenAPI openAPI = TestUtils.parseSpec("src/test/resources/3_0/inline_model_resolver.yaml");
new InlineModelResolver().flatten(openAPI);
assertTrue(openAPI.getComponents().getSchemas().get("ComposedObjectModelInline") instanceof ComposedSchema);
assertTrue(ModelUtils.isComposedSchema(openAPI.getComponents().getSchemas().get("ComposedObjectModelInline")));
ComposedSchema schema = (ComposedSchema) openAPI.getComponents().getSchemas().get("ComposedObjectModelInline");
@ -830,19 +830,19 @@ public class InlineModelResolverTest {
assertTrue(openAPI.getComponents().getSchemas().get("CustomerType") instanceof StringSchema);
assertTrue(openAPI.getComponents().getSchemas().get("Entity") instanceof ObjectSchema);
assertTrue(openAPI.getComponents().getSchemas().get("Party") instanceof ComposedSchema);
assertTrue(openAPI.getComponents().getSchemas().get("Contact") instanceof ComposedSchema);
assertTrue(openAPI.getComponents().getSchemas().get("Customer") instanceof ComposedSchema);
assertTrue(openAPI.getComponents().getSchemas().get("Person") instanceof ComposedSchema);
assertTrue(openAPI.getComponents().getSchemas().get("Organization") instanceof ComposedSchema);
assertTrue(ModelUtils.isComposedSchema(openAPI.getComponents().getSchemas().get("Party")));
assertTrue(ModelUtils.isComposedSchema(openAPI.getComponents().getSchemas().get("Contact")));
assertTrue(ModelUtils.isComposedSchema(openAPI.getComponents().getSchemas().get("Customer")));
assertTrue(ModelUtils.isComposedSchema(openAPI.getComponents().getSchemas().get("Person")));
assertTrue(ModelUtils.isComposedSchema(openAPI.getComponents().getSchemas().get("Organization")));
assertTrue(openAPI.getComponents().getSchemas().get("ApiError") instanceof ObjectSchema);
assertFalse(openAPI.getComponents().getSchemas().get("Party_allOf") instanceof ComposedSchema);
assertFalse(openAPI.getComponents().getSchemas().get("Contact_allOf") instanceof ComposedSchema);
assertFalse(openAPI.getComponents().getSchemas().get("Customer_allOf") instanceof ComposedSchema);
assertFalse(openAPI.getComponents().getSchemas().get("Person_allOf") instanceof ComposedSchema);
assertFalse(openAPI.getComponents().getSchemas().get("Organization_allOf") instanceof ComposedSchema);
assertFalse(ModelUtils.isComposedSchema(openAPI.getComponents().getSchemas().get("Party_allOf")));
assertFalse(ModelUtils.isComposedSchema(openAPI.getComponents().getSchemas().get("Contact_allOf")));
assertFalse(ModelUtils.isComposedSchema(openAPI.getComponents().getSchemas().get("Customer_allOf")));
assertFalse(ModelUtils.isComposedSchema(openAPI.getComponents().getSchemas().get("Person_allOf")));
assertFalse(ModelUtils.isComposedSchema(openAPI.getComponents().getSchemas().get("Organization_allOf")));
// Party
ComposedSchema party = (ComposedSchema) openAPI.getComponents().getSchemas().get("Party");

View File

@ -0,0 +1,775 @@
openapi: 3.1.0
servers:
- url: 'http://petstore.swagger.io/v2'
info:
description: >-
This is a sample server Petstore server. For this sample, you can use the api key
`special-key` to test the authorization filters.
version: 1.0.0
title: OpenAPI Petstore
license:
name: Apache-2.0
url: 'https://www.apache.org/licenses/LICENSE-2.0.html'
tags:
- name: pet
description: Everything about your Pets
- name: store
description: Access to Petstore orders
- name: user
description: Operations about user
paths:
/pet:
post:
tags:
- pet
summary: Add a new pet to the store
description: ''
operationId: addPet
responses:
'200':
description: successful operation
content:
application/xml:
schema:
$ref: '#/components/schemas/Pet'
application/json:
schema:
$ref: '#/components/schemas/Pet'
'405':
description: Invalid input
security:
- petstore_auth:
- 'write:pets'
- 'read:pets'
requestBody:
$ref: '#/components/requestBodies/Pet'
put:
tags:
- pet
summary: Update an existing pet
description: ''
externalDocs:
description: API documentation for the updatePet operation
url: http://petstore.swagger.io/v2/doc/updatePet
operationId: updatePet
responses:
'200':
description: successful operation
content:
application/xml:
schema:
$ref: '#/components/schemas/Pet'
application/json:
schema:
$ref: '#/components/schemas/Pet'
'400':
description: Invalid ID supplied
'404':
description: Pet not found
'405':
description: Validation exception
security:
- petstore_auth:
- 'write:pets'
- 'read:pets'
requestBody:
$ref: '#/components/requestBodies/Pet'
/pet/findByStatus:
get:
tags:
- pet
summary: Finds Pets by status
description: Multiple status values can be provided with comma separated strings
operationId: findPetsByStatus
parameters:
- name: status
in: query
description: Status values that need to be considered for filter
required: true
style: form
explode: false
deprecated: true
schema:
type: array
items:
type: string
enum:
- available
- pending
- sold
default: available
responses:
'200':
description: successful operation
content:
application/xml:
schema:
type: array
items:
$ref: '#/components/schemas/Pet'
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/Pet'
'400':
description: Invalid status value
security:
- petstore_auth:
- 'read:pets'
/pet/findByTags:
get:
tags:
- pet
summary: Finds Pets by tags
description: >-
Multiple tags can be provided with comma separated strings. Use tag1,
tag2, tag3 for testing.
operationId: findPetsByTags
parameters:
- name: tags
in: query
description: Tags to filter by
required: true
style: form
explode: false
schema:
type: array
items:
type: string
responses:
'200':
description: successful operation
content:
application/xml:
schema:
type: array
items:
$ref: '#/components/schemas/Pet'
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/Pet'
'400':
description: Invalid tag value
security:
- petstore_auth:
- 'read:pets'
deprecated: true
'/pet/{petId}':
get:
tags:
- pet
summary: Find pet by ID
description: Returns a single pet
operationId: getPetById
parameters:
- name: petId
in: path
description: ID of pet to return
required: true
schema:
type: integer
format: int64
responses:
'200':
description: successful operation
content:
application/xml:
schema:
$ref: '#/components/schemas/Pet'
application/json:
schema:
$ref: '#/components/schemas/Pet'
'400':
description: Invalid ID supplied
'404':
description: Pet not found
security:
- api_key: []
post:
tags:
- pet
summary: Updates a pet in the store with form data
description: ''
operationId: updatePetWithForm
parameters:
- name: petId
in: path
description: ID of pet that needs to be updated
required: true
schema:
type: integer
format: int64
responses:
'405':
description: Invalid input
security:
- petstore_auth:
- 'write:pets'
- 'read:pets'
requestBody:
content:
application/x-www-form-urlencoded:
schema:
type: object
properties:
name:
description: Updated name of the pet
type: string
status:
description: Updated status of the pet
type: string
delete:
tags:
- pet
summary: Deletes a pet
description: ''
operationId: deletePet
parameters:
- name: api_key
in: header
required: false
schema:
type: string
- name: petId
in: path
description: Pet id to delete
required: true
schema:
type: integer
format: int64
responses:
'400':
description: Invalid pet value
security:
- petstore_auth:
- 'write:pets'
- 'read:pets'
'/pet/{petId}/uploadImage':
post:
tags:
- pet
summary: uploads an image
description: ''
operationId: uploadFile
parameters:
- name: petId
in: path
description: ID of pet to update
required: true
schema:
type: integer
format: int64
responses:
'200':
description: successful operation
content:
application/json:
schema:
$ref: '#/components/schemas/ApiResponse'
security:
- petstore_auth:
- 'write:pets'
- 'read:pets'
requestBody:
content:
multipart/form-data:
schema:
type: object
properties:
additionalMetadata:
description: Additional data to pass to server
type: string
file:
description: file to upload
type: string
format: binary
/store/inventory:
get:
tags:
- store
summary: Returns pet inventories by status
description: Returns a map of status codes to quantities
operationId: getInventory
responses:
'200':
description: successful operation
content:
application/json:
schema:
type: object
additionalProperties:
type: integer
format: int32
security:
- api_key: []
/store/order:
post:
tags:
- store
summary: Place an order for a pet
description: ''
operationId: placeOrder
responses:
'200':
description: successful operation
content:
application/xml:
schema:
$ref: '#/components/schemas/Order'
application/json:
schema:
$ref: '#/components/schemas/Order'
'400':
description: Invalid Order
requestBody:
content:
application/json:
schema:
$ref: '#/components/schemas/Order'
description: order placed for purchasing the pet
required: true
'/store/order/{orderId}':
get:
tags:
- store
summary: Find purchase order by ID
description: >-
For valid response try integer IDs with value <= 5 or > 10. Other values
will generate exceptions
operationId: getOrderById
parameters:
- name: orderId
in: path
description: ID of pet that needs to be fetched
required: true
schema:
type: integer
format: int64
minimum: 1
maximum: 5
responses:
'200':
description: successful operation
content:
application/xml:
schema:
$ref: '#/components/schemas/Order'
application/json:
schema:
$ref: '#/components/schemas/Order'
'400':
description: Invalid ID supplied
'404':
description: Order not found
delete:
tags:
- store
summary: Delete purchase order by ID
description: >-
For valid response try integer IDs with value < 1000. Anything above
1000 or nonintegers will generate API errors
operationId: deleteOrder
parameters:
- name: orderId
in: path
description: ID of the order that needs to be deleted
required: true
schema:
type: string
responses:
'400':
description: Invalid ID supplied
'404':
description: Order not found
/user:
post:
tags:
- user
summary: Create user
description: This can only be done by the logged in user.
operationId: createUser
responses:
default:
description: successful operation
security:
- api_key: []
requestBody:
content:
application/json:
schema:
$ref: '#/components/schemas/User'
description: Created user object
required: true
/user/createWithArray:
post:
tags:
- user
summary: Creates list of users with given input array
description: ''
operationId: createUsersWithArrayInput
responses:
default:
description: successful operation
security:
- api_key: []
requestBody:
$ref: '#/components/requestBodies/UserArray'
/user/createWithList:
post:
tags:
- user
summary: Creates list of users with given input array
description: ''
operationId: createUsersWithListInput
responses:
default:
description: successful operation
security:
- api_key: []
requestBody:
$ref: '#/components/requestBodies/UserArray'
/user/login:
get:
tags:
- user
summary: Logs user into the system
description: ''
operationId: loginUser
parameters:
- name: username
in: query
description: The user name for login
required: true
schema:
type: string
pattern: '^[a-zA-Z0-9]+[a-zA-Z0-9\.\-_]*[a-zA-Z0-9]+$'
- name: password
in: query
description: The password for login in clear text
required: true
schema:
type: string
responses:
'200':
description: successful operation
headers:
Set-Cookie:
description: >-
Cookie authentication key for use with the `api_key`
apiKey authentication.
schema:
type: string
example: AUTH_KEY=abcde12345; Path=/; HttpOnly
X-Rate-Limit:
description: calls per hour allowed by the user
schema:
type: integer
format: int32
X-Expires-After:
description: date in UTC when token expires
schema:
type: string
format: date-time
content:
application/xml:
schema:
type: string
application/json:
schema:
type: string
'400':
description: Invalid username/password supplied
/user/logout:
get:
tags:
- user
summary: Logs out current logged in user session
description: ''
operationId: logoutUser
responses:
default:
description: successful operation
security:
- api_key: []
'/user/{username}':
get:
tags:
- user
summary: Get user by user name
description: ''
operationId: getUserByName
parameters:
- name: username
in: path
description: The name that needs to be fetched. Use user1 for testing.
required: true
schema:
type: string
responses:
'200':
description: successful operation
content:
application/xml:
schema:
$ref: '#/components/schemas/User'
application/json:
schema:
$ref: '#/components/schemas/User'
'400':
description: Invalid username supplied
'404':
description: User not found
put:
tags:
- user
summary: Updated user
description: This can only be done by the logged in user.
operationId: updateUser
parameters:
- name: username
in: path
description: name that need to be deleted
required: true
schema:
type: string
responses:
'400':
description: Invalid user supplied
'404':
description: User not found
security:
- api_key: []
requestBody:
content:
application/json:
schema:
$ref: '#/components/schemas/User'
description: Updated user object
required: true
delete:
tags:
- user
summary: Delete user
description: This can only be done by the logged in user.
operationId: deleteUser
parameters:
- name: username
in: path
description: The name that needs to be deleted
required: true
schema:
type: string
responses:
'400':
description: Invalid username supplied
'404':
description: User not found
security:
- api_key: []
externalDocs:
description: Find out more about Swagger
url: 'http://swagger.io'
components:
requestBodies:
UserArray:
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/User'
description: List of user object
required: true
Pet:
content:
application/json:
schema:
$ref: '#/components/schemas/Pet'
application/xml:
schema:
$ref: '#/components/schemas/Pet'
description: Pet object that needs to be added to the store
required: true
securitySchemes:
petstore_auth:
type: oauth2
flows:
implicit:
authorizationUrl: 'http://petstore.swagger.io/api/oauth/dialog'
scopes:
'write:pets': modify pets in your account
'read:pets': read your pets
api_key:
type: apiKey
name: api_key
in: header
schemas:
Order:
title: Pet Order
description: An order for a pets from the pet store
type: object
properties:
id:
type: integer
format: int64
petId:
type: integer
format: int64
quantity:
type: integer
format: int32
shipDate:
type: string
format: date-time
status:
type: string
description: Order Status
enum:
- placed
- approved
- delivered
complete:
type: boolean
default: false
xml:
name: Order
Category:
title: Pet category
description: A category for a pet
type: object
properties:
id:
type: integer
format: int64
name:
type: string
pattern: '^[a-zA-Z0-9]+[a-zA-Z0-9\.\-_]*[a-zA-Z0-9]+$'
xml:
name: Category
User:
title: a User
description: A User who is purchasing from the pet store
type: object
properties:
id:
type: integer
format: int64
username:
type: string
firstName:
type: string
lastName:
type: string
email:
type: string
password:
type: string
phone:
type: string
userStatus:
type: integer
format: int32
description: User Status
xml:
name: User
Tag:
title: Pet Tag
description: A tag for a pet
type: object
properties:
id:
type: integer
format: int64
name:
type: string
xml:
name: Tag
Pet:
title: a Pet
description: A pet for sale in the pet store
type: object
required:
- name
- photoUrls
properties:
id:
type: integer
format: int64
category:
$ref: '#/components/schemas/Category'
name:
type: string
example: doggie
photoUrls:
type: array
xml:
name: photoUrl
wrapped: true
items:
type: string
tags:
type: array
xml:
name: tag
wrapped: true
items:
$ref: '#/components/schemas/Tag'
status:
type: string
description: pet status in the store
deprecated: true
enum:
- available
- pending
- sold
xml:
name: Pet
ApiResponse:
title: An uploaded response
description: Describes the result of uploading an image resource
type: object
properties:
code:
type: integer
format: int32
type:
type: string
message:
type: string
StringOrInt:
description: string or int
type: [string, integer]
OneOfStringOrInt:
description: string or int (onefOf)
oneOf:
- type: string
- type: integer
Dog:
allOf:
- $ref: '#/components/schemas/Animal'
- type: object
properties:
breed:
type: string
Cat:
allOf:
- $ref: '#/components/schemas/Animal'
- type: object
properties:
declawed:
type: boolean
Animal:
type: object
discriminator:
propertyName: className
required:
- className
properties:
className:
type: string
color:
type: string
default: red

View File

@ -48,6 +48,9 @@ paths:
- pet
summary: Update an existing pet
description: ''
externalDocs:
description: API documentation for the updatePet operation
url: http://petstore.swagger.io/v2/doc/updatePet
operationId: updatePet
responses:
'200':

View File

@ -1291,6 +1291,7 @@
<module>samples/client/petstore/java/jersey3</module>
<module>samples/client/others/java/okhttp-gson-streaming</module>
<module>samples/client/petstore/java/okhttp-gson</module>
<module>samples/client/petstore/java/okhttp-gson-3.1</module>
<module>samples/client/petstore/java-micronaut-client</module>
<module>samples/client/petstore/java/apache-httpclient</module>
</modules>

View File

@ -0,0 +1,30 @@
# This workflow will build a Java project with Maven, and cache/restore any dependencies to improve the workflow execution time
# For more information see: https://help.github.com/actions/language-and-framework-guides/building-and-testing-java-with-maven
#
# This file is auto-generated by OpenAPI Generator (https://openapi-generator.tech)
name: Java CI with Maven
on:
push:
branches: [ main, master ]
pull_request:
branches: [ main, master ]
jobs:
build:
name: Build OpenAPI Petstore
runs-on: ubuntu-latest
strategy:
matrix:
java: [ '8' ]
steps:
- uses: actions/checkout@v2
- name: Set up JDK
uses: actions/setup-java@v2
with:
java-version: ${{ matrix.java }}
distribution: 'temurin'
cache: maven
- name: Build with Maven
run: mvn -B package --no-transfer-progress --file pom.xml

View File

@ -0,0 +1,21 @@
*.class
# Mobile Tools for Java (J2ME)
.mtj.tmp/
# Package Files #
*.jar
*.war
*.ear
# exclude jar for gradle wrapper
!gradle/wrapper/*.jar
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*
# build files
**/target
target
.gradle
build

View File

@ -0,0 +1,23 @@
# OpenAPI Generator Ignore
# Generated by openapi-generator https://github.com/openapitools/openapi-generator
# Use this file to prevent files from being overwritten by the generator.
# The patterns follow closely to .gitignore or .dockerignore.
# As an example, the C# client generator defines ApiClient.cs.
# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line:
#ApiClient.cs
# You can match any string of characters against a directory, file or extension with a single asterisk (*):
#foo/*/qux
# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux
# You can recursively match patterns against a directory, file or extension with a double asterisk (**):
#foo/**/qux
# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux
# You can also negate patterns with an exclamation (!).
# For example, you can ignore all files in a docs folder with the file extension .md:
#docs/*.md
# Then explicitly reverse the ignore rule for a single file:
#!docs/README.md

View File

@ -0,0 +1,66 @@
.github/workflows/maven.yml
.gitignore
.travis.yml
README.md
api/openapi.yaml
build.gradle
build.sbt
docs/Animal.md
docs/Cat.md
docs/Category.md
docs/Dog.md
docs/ModelApiResponse.md
docs/OneOfStringOrInt.md
docs/Order.md
docs/Pet.md
docs/PetApi.md
docs/StoreApi.md
docs/StringOrInt.md
docs/Tag.md
docs/User.md
docs/UserApi.md
git_push.sh
gradle.properties
gradle/wrapper/gradle-wrapper.jar
gradle/wrapper/gradle-wrapper.properties
gradlew
gradlew.bat
pom.xml
settings.gradle
src/main/AndroidManifest.xml
src/main/java/org/openapitools/client/ApiCallback.java
src/main/java/org/openapitools/client/ApiClient.java
src/main/java/org/openapitools/client/ApiException.java
src/main/java/org/openapitools/client/ApiResponse.java
src/main/java/org/openapitools/client/Configuration.java
src/main/java/org/openapitools/client/GzipRequestInterceptor.java
src/main/java/org/openapitools/client/JSON.java
src/main/java/org/openapitools/client/Pair.java
src/main/java/org/openapitools/client/ProgressRequestBody.java
src/main/java/org/openapitools/client/ProgressResponseBody.java
src/main/java/org/openapitools/client/ServerConfiguration.java
src/main/java/org/openapitools/client/ServerVariable.java
src/main/java/org/openapitools/client/StringUtil.java
src/main/java/org/openapitools/client/api/PetApi.java
src/main/java/org/openapitools/client/api/StoreApi.java
src/main/java/org/openapitools/client/api/UserApi.java
src/main/java/org/openapitools/client/auth/ApiKeyAuth.java
src/main/java/org/openapitools/client/auth/Authentication.java
src/main/java/org/openapitools/client/auth/HttpBasicAuth.java
src/main/java/org/openapitools/client/auth/HttpBearerAuth.java
src/main/java/org/openapitools/client/auth/OAuth.java
src/main/java/org/openapitools/client/auth/OAuthFlow.java
src/main/java/org/openapitools/client/auth/OAuthOkHttpClient.java
src/main/java/org/openapitools/client/auth/RetryingOAuth.java
src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java
src/main/java/org/openapitools/client/model/Animal.java
src/main/java/org/openapitools/client/model/Cat.java
src/main/java/org/openapitools/client/model/Category.java
src/main/java/org/openapitools/client/model/Dog.java
src/main/java/org/openapitools/client/model/ModelApiResponse.java
src/main/java/org/openapitools/client/model/OneOfStringOrInt.java
src/main/java/org/openapitools/client/model/Order.java
src/main/java/org/openapitools/client/model/Pet.java
src/main/java/org/openapitools/client/model/StringOrInt.java
src/main/java/org/openapitools/client/model/Tag.java
src/main/java/org/openapitools/client/model/User.java

View File

@ -0,0 +1 @@
7.0.1-SNAPSHOT

View File

@ -0,0 +1,22 @@
#
# Generated by OpenAPI Generator: https://openapi-generator.tech
#
# Ref: https://docs.travis-ci.com/user/languages/java/
#
language: java
jdk:
- openjdk12
- openjdk11
- openjdk10
- openjdk9
- openjdk8
before_install:
# ensure gradlew has proper permission
- chmod a+x ./gradlew
script:
# test using maven
#- mvn test
# test using gradle
- gradle test
# test using sbt
# - sbt test

View File

@ -0,0 +1,188 @@
# petstore-okhttp-gson-31
OpenAPI Petstore
- API version: 1.0.0
This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*Automatically generated by the [OpenAPI Generator](https://openapi-generator.tech)*
## Requirements
Building the API client library requires:
1. Java 1.8+
2. Maven (3.8.3+)/Gradle (7.2+)
## Installation
To install the API client library to your local Maven repository, simply execute:
```shell
mvn clean install
```
To deploy it to a remote Maven repository instead, configure the settings of the repository and execute:
```shell
mvn clean deploy
```
Refer to the [OSSRH Guide](http://central.sonatype.org/pages/ossrh-guide.html) for more information.
### Maven users
Add this dependency to your project's POM:
```xml
<dependency>
<groupId>org.openapitools</groupId>
<artifactId>petstore-okhttp-gson-31</artifactId>
<version>1.0.0</version>
<scope>compile</scope>
</dependency>
```
### Gradle users
Add this dependency to your project's build file:
```groovy
repositories {
mavenCentral() // Needed if the 'petstore-okhttp-gson-31' jar has been published to maven central.
mavenLocal() // Needed if the 'petstore-okhttp-gson-31' jar has been published to the local maven repo.
}
dependencies {
implementation "org.openapitools:petstore-okhttp-gson-31:1.0.0"
}
```
### Others
At first generate the JAR by executing:
```shell
mvn clean package
```
Then manually install the following JARs:
* `target/petstore-okhttp-gson-31-1.0.0.jar`
* `target/lib/*.jar`
## Getting Started
Please follow the [installation](#installation) instruction and execute the following Java code:
```java
// Import classes:
import org.openapitools.client.ApiClient;
import org.openapitools.client.ApiException;
import org.openapitools.client.Configuration;
import org.openapitools.client.auth.*;
import org.openapitools.client.models.*;
import org.openapitools.client.api.PetApi;
public class Example {
public static void main(String[] args) {
ApiClient defaultClient = Configuration.getDefaultApiClient();
defaultClient.setBasePath("http://petstore.swagger.io/v2");
// Configure OAuth2 access token for authorization: petstore_auth
OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth");
petstore_auth.setAccessToken("YOUR ACCESS TOKEN");
PetApi apiInstance = new PetApi(defaultClient);
Pet pet = new Pet(); // Pet | Pet object that needs to be added to the store
try {
Pet result = apiInstance.addPet(pet);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling PetApi#addPet");
System.err.println("Status code: " + e.getCode());
System.err.println("Reason: " + e.getResponseBody());
System.err.println("Response headers: " + e.getResponseHeaders());
e.printStackTrace();
}
}
}
```
## Documentation for API Endpoints
All URIs are relative to *http://petstore.swagger.io/v2*
Class | Method | HTTP request | Description
------------ | ------------- | ------------- | -------------
*PetApi* | [**addPet**](docs/PetApi.md#addPet) | **POST** /pet | Add a new pet to the store
*PetApi* | [**deletePet**](docs/PetApi.md#deletePet) | **DELETE** /pet/{petId} | Deletes a pet
*PetApi* | [**findPetsByStatus**](docs/PetApi.md#findPetsByStatus) | **GET** /pet/findByStatus | Finds Pets by status
*PetApi* | [**findPetsByTags**](docs/PetApi.md#findPetsByTags) | **GET** /pet/findByTags | Finds Pets by tags
*PetApi* | [**getPetById**](docs/PetApi.md#getPetById) | **GET** /pet/{petId} | Find pet by ID
*PetApi* | [**updatePet**](docs/PetApi.md#updatePet) | **PUT** /pet | Update an existing pet
*PetApi* | [**updatePetWithForm**](docs/PetApi.md#updatePetWithForm) | **POST** /pet/{petId} | Updates a pet in the store with form data
*PetApi* | [**uploadFile**](docs/PetApi.md#uploadFile) | **POST** /pet/{petId}/uploadImage | uploads an image
*StoreApi* | [**deleteOrder**](docs/StoreApi.md#deleteOrder) | **DELETE** /store/order/{orderId} | Delete purchase order by ID
*StoreApi* | [**getInventory**](docs/StoreApi.md#getInventory) | **GET** /store/inventory | Returns pet inventories by status
*StoreApi* | [**getOrderById**](docs/StoreApi.md#getOrderById) | **GET** /store/order/{orderId} | Find purchase order by ID
*StoreApi* | [**placeOrder**](docs/StoreApi.md#placeOrder) | **POST** /store/order | Place an order for a pet
*UserApi* | [**createUser**](docs/UserApi.md#createUser) | **POST** /user | Create user
*UserApi* | [**createUsersWithArrayInput**](docs/UserApi.md#createUsersWithArrayInput) | **POST** /user/createWithArray | Creates list of users with given input array
*UserApi* | [**createUsersWithListInput**](docs/UserApi.md#createUsersWithListInput) | **POST** /user/createWithList | Creates list of users with given input array
*UserApi* | [**deleteUser**](docs/UserApi.md#deleteUser) | **DELETE** /user/{username} | Delete user
*UserApi* | [**getUserByName**](docs/UserApi.md#getUserByName) | **GET** /user/{username} | Get user by user name
*UserApi* | [**loginUser**](docs/UserApi.md#loginUser) | **GET** /user/login | Logs user into the system
*UserApi* | [**logoutUser**](docs/UserApi.md#logoutUser) | **GET** /user/logout | Logs out current logged in user session
*UserApi* | [**updateUser**](docs/UserApi.md#updateUser) | **PUT** /user/{username} | Updated user
## Documentation for Models
- [Animal](docs/Animal.md)
- [Cat](docs/Cat.md)
- [Category](docs/Category.md)
- [Dog](docs/Dog.md)
- [ModelApiResponse](docs/ModelApiResponse.md)
- [OneOfStringOrInt](docs/OneOfStringOrInt.md)
- [Order](docs/Order.md)
- [Pet](docs/Pet.md)
- [StringOrInt](docs/StringOrInt.md)
- [Tag](docs/Tag.md)
- [User](docs/User.md)
<a id="documentation-for-authorization"></a>
## Documentation for Authorization
Authentication schemes defined for the API:
<a id="petstore_auth"></a>
### petstore_auth
- **Type**: OAuth
- **Flow**: implicit
- **Authorization URL**: http://petstore.swagger.io/api/oauth/dialog
- **Scopes**:
- write:pets: modify pets in your account
- read:pets: read your pets
<a id="api_key"></a>
### api_key
- **Type**: API key
- **API key parameter name**: api_key
- **Location**: HTTP header
## Recommendation
It's recommended to create an instance of `ApiClient` per thread in a multithreaded environment to avoid any potential issues.
## Author

View File

@ -0,0 +1,866 @@
openapi: 3.1.0
info:
description: "This is a sample server Petstore server. For this sample, you can\
\ use the api key `special-key` to test the authorization filters."
license:
name: Apache-2.0
url: https://www.apache.org/licenses/LICENSE-2.0.html
title: OpenAPI Petstore
version: 1.0.0
externalDocs:
description: Find out more about Swagger
url: http://swagger.io
servers:
- url: http://petstore.swagger.io/v2
tags:
- description: Everything about your Pets
name: pet
- description: Access to Petstore orders
name: store
- description: Operations about user
name: user
paths:
/pet:
post:
description: ""
operationId: addPet
requestBody:
$ref: '#/components/requestBodies/Pet'
responses:
"200":
content:
application/xml:
schema:
$ref: '#/components/schemas/Pet'
application/json:
schema:
$ref: '#/components/schemas/Pet'
description: successful operation
"405":
description: Invalid input
security:
- petstore_auth:
- write:pets
- read:pets
summary: Add a new pet to the store
tags:
- pet
x-content-type: application/json
x-accepts: application/json
put:
description: ""
externalDocs:
description: API documentation for the updatePet operation
url: http://petstore.swagger.io/v2/doc/updatePet
operationId: updatePet
requestBody:
$ref: '#/components/requestBodies/Pet'
responses:
"200":
content:
application/xml:
schema:
$ref: '#/components/schemas/Pet'
application/json:
schema:
$ref: '#/components/schemas/Pet'
description: successful operation
"400":
description: Invalid ID supplied
"404":
description: Pet not found
"405":
description: Validation exception
security:
- petstore_auth:
- write:pets
- read:pets
summary: Update an existing pet
tags:
- pet
x-content-type: application/json
x-accepts: application/json
/pet/findByStatus:
get:
description: Multiple status values can be provided with comma separated strings
operationId: findPetsByStatus
parameters:
- deprecated: true
description: Status values that need to be considered for filter
explode: false
in: query
name: status
required: true
schema:
items:
default: available
enum:
- available
- pending
- sold
type: string
type: array
style: form
responses:
"200":
content:
application/xml:
schema:
items:
$ref: '#/components/schemas/Pet'
type: array
application/json:
schema:
items:
$ref: '#/components/schemas/Pet'
type: array
description: successful operation
"400":
description: Invalid status value
security:
- petstore_auth:
- read:pets
summary: Finds Pets by status
tags:
- pet
x-accepts: application/json
/pet/findByTags:
get:
deprecated: true
description: "Multiple tags can be provided with comma separated strings. Use\
\ tag1, tag2, tag3 for testing."
operationId: findPetsByTags
parameters:
- description: Tags to filter by
explode: false
in: query
name: tags
required: true
schema:
items:
type: string
type: array
style: form
responses:
"200":
content:
application/xml:
schema:
items:
$ref: '#/components/schemas/Pet'
type: array
application/json:
schema:
items:
$ref: '#/components/schemas/Pet'
type: array
description: successful operation
"400":
description: Invalid tag value
security:
- petstore_auth:
- read:pets
summary: Finds Pets by tags
tags:
- pet
x-accepts: application/json
/pet/{petId}:
delete:
description: ""
operationId: deletePet
parameters:
- explode: false
in: header
name: api_key
required: false
schema:
type: string
style: simple
- description: Pet id to delete
explode: false
in: path
name: petId
required: true
schema:
format: int64
type: integer
style: simple
responses:
"400":
description: Invalid pet value
security:
- petstore_auth:
- write:pets
- read:pets
summary: Deletes a pet
tags:
- pet
x-accepts: application/json
get:
description: Returns a single pet
operationId: getPetById
parameters:
- description: ID of pet to return
explode: false
in: path
name: petId
required: true
schema:
format: int64
type: integer
style: simple
responses:
"200":
content:
application/xml:
schema:
$ref: '#/components/schemas/Pet'
application/json:
schema:
$ref: '#/components/schemas/Pet'
description: successful operation
"400":
description: Invalid ID supplied
"404":
description: Pet not found
security:
- api_key: []
summary: Find pet by ID
tags:
- pet
x-accepts: application/json
post:
description: ""
operationId: updatePetWithForm
parameters:
- description: ID of pet that needs to be updated
explode: false
in: path
name: petId
required: true
schema:
format: int64
type: integer
style: simple
requestBody:
content:
application/x-www-form-urlencoded:
schema:
$ref: '#/components/schemas/updatePetWithForm_request'
responses:
"405":
description: Invalid input
security:
- petstore_auth:
- write:pets
- read:pets
summary: Updates a pet in the store with form data
tags:
- pet
x-content-type: application/x-www-form-urlencoded
x-accepts: application/json
/pet/{petId}/uploadImage:
post:
description: ""
operationId: uploadFile
parameters:
- description: ID of pet to update
explode: false
in: path
name: petId
required: true
schema:
format: int64
type: integer
style: simple
requestBody:
content:
multipart/form-data:
schema:
$ref: '#/components/schemas/uploadFile_request'
responses:
"200":
content:
application/json:
schema:
$ref: '#/components/schemas/ApiResponse'
description: successful operation
security:
- petstore_auth:
- write:pets
- read:pets
summary: uploads an image
tags:
- pet
x-content-type: multipart/form-data
x-accepts: application/json
/store/inventory:
get:
description: Returns a map of status codes to quantities
operationId: getInventory
responses:
"200":
content:
application/json:
schema:
additionalProperties:
format: int32
type: integer
description: successful operation
security:
- api_key: []
summary: Returns pet inventories by status
tags:
- store
x-accepts: application/json
/store/order:
post:
description: ""
operationId: placeOrder
requestBody:
content:
application/json:
schema:
$ref: '#/components/schemas/Order'
description: order placed for purchasing the pet
required: true
responses:
"200":
content:
application/xml:
schema:
$ref: '#/components/schemas/Order'
application/json:
schema:
$ref: '#/components/schemas/Order'
description: successful operation
"400":
description: Invalid Order
summary: Place an order for a pet
tags:
- store
x-content-type: application/json
x-accepts: application/json
/store/order/{orderId}:
delete:
description: For valid response try integer IDs with value < 1000. Anything
above 1000 or nonintegers will generate API errors
operationId: deleteOrder
parameters:
- description: ID of the order that needs to be deleted
explode: false
in: path
name: orderId
required: true
schema:
type: string
style: simple
responses:
"400":
description: Invalid ID supplied
"404":
description: Order not found
summary: Delete purchase order by ID
tags:
- store
x-accepts: application/json
get:
description: For valid response try integer IDs with value <= 5 or > 10. Other
values will generate exceptions
operationId: getOrderById
parameters:
- description: ID of pet that needs to be fetched
explode: false
in: path
name: orderId
required: true
schema:
format: int64
maximum: 5
minimum: 1
type: integer
style: simple
responses:
"200":
content:
application/xml:
schema:
$ref: '#/components/schemas/Order'
application/json:
schema:
$ref: '#/components/schemas/Order'
description: successful operation
"400":
description: Invalid ID supplied
"404":
description: Order not found
summary: Find purchase order by ID
tags:
- store
x-accepts: application/json
/user:
post:
description: This can only be done by the logged in user.
operationId: createUser
requestBody:
content:
application/json:
schema:
$ref: '#/components/schemas/User'
description: Created user object
required: true
responses:
default:
description: successful operation
security:
- api_key: []
summary: Create user
tags:
- user
x-content-type: application/json
x-accepts: application/json
/user/createWithArray:
post:
description: ""
operationId: createUsersWithArrayInput
requestBody:
$ref: '#/components/requestBodies/UserArray'
responses:
default:
description: successful operation
security:
- api_key: []
summary: Creates list of users with given input array
tags:
- user
x-content-type: application/json
x-accepts: application/json
/user/createWithList:
post:
description: ""
operationId: createUsersWithListInput
requestBody:
$ref: '#/components/requestBodies/UserArray'
responses:
default:
description: successful operation
security:
- api_key: []
summary: Creates list of users with given input array
tags:
- user
x-content-type: application/json
x-accepts: application/json
/user/login:
get:
description: ""
operationId: loginUser
parameters:
- description: The user name for login
explode: true
in: query
name: username
required: true
schema:
pattern: "^[a-zA-Z0-9]+[a-zA-Z0-9\\.\\-_]*[a-zA-Z0-9]+$"
type: string
style: form
- description: The password for login in clear text
explode: true
in: query
name: password
required: true
schema:
type: string
style: form
responses:
"200":
content:
application/xml:
schema:
type: string
application/json:
schema:
type: string
description: successful operation
headers:
Set-Cookie:
description: Cookie authentication key for use with the `api_key` apiKey
authentication.
explode: false
schema:
example: AUTH_KEY=abcde12345; Path=/; HttpOnly
type: string
style: simple
X-Rate-Limit:
description: calls per hour allowed by the user
explode: false
schema:
format: int32
type: integer
style: simple
X-Expires-After:
description: date in UTC when token expires
explode: false
schema:
format: date-time
type: string
style: simple
"400":
description: Invalid username/password supplied
summary: Logs user into the system
tags:
- user
x-accepts: application/json
/user/logout:
get:
description: ""
operationId: logoutUser
responses:
default:
description: successful operation
security:
- api_key: []
summary: Logs out current logged in user session
tags:
- user
x-accepts: application/json
/user/{username}:
delete:
description: This can only be done by the logged in user.
operationId: deleteUser
parameters:
- description: The name that needs to be deleted
explode: false
in: path
name: username
required: true
schema:
type: string
style: simple
responses:
"400":
description: Invalid username supplied
"404":
description: User not found
security:
- api_key: []
summary: Delete user
tags:
- user
x-accepts: application/json
get:
description: ""
operationId: getUserByName
parameters:
- description: The name that needs to be fetched. Use user1 for testing.
explode: false
in: path
name: username
required: true
schema:
type: string
style: simple
responses:
"200":
content:
application/xml:
schema:
$ref: '#/components/schemas/User'
application/json:
schema:
$ref: '#/components/schemas/User'
description: successful operation
"400":
description: Invalid username supplied
"404":
description: User not found
summary: Get user by user name
tags:
- user
x-accepts: application/json
put:
description: This can only be done by the logged in user.
operationId: updateUser
parameters:
- description: name that need to be deleted
explode: false
in: path
name: username
required: true
schema:
type: string
style: simple
requestBody:
content:
application/json:
schema:
$ref: '#/components/schemas/User'
description: Updated user object
required: true
responses:
"400":
description: Invalid user supplied
"404":
description: User not found
security:
- api_key: []
summary: Updated user
tags:
- user
x-content-type: application/json
x-accepts: application/json
components:
requestBodies:
UserArray:
content:
application/json:
schema:
items:
$ref: '#/components/schemas/User'
type: array
description: List of user object
required: true
Pet:
content:
application/json:
schema:
$ref: '#/components/schemas/Pet'
application/xml:
schema:
$ref: '#/components/schemas/Pet'
description: Pet object that needs to be added to the store
required: true
schemas:
Order:
description: An order for a pets from the pet store
example:
petId: 6
quantity: 1
id: 0
shipDate: 2000-01-23T04:56:07.000+00:00
complete: false
status: placed
properties:
id:
format: int64
type: integer
petId:
format: int64
type: integer
quantity:
format: int32
type: integer
shipDate:
format: date-time
type: string
status:
description: Order Status
enum:
- placed
- approved
- delivered
type: string
complete:
default: false
type: boolean
title: Pet Order
xml:
name: Order
Category:
description: A category for a pet
example:
name: name
id: 6
properties:
id:
format: int64
type: integer
name:
pattern: "^[a-zA-Z0-9]+[a-zA-Z0-9\\.\\-_]*[a-zA-Z0-9]+$"
type: string
title: Pet category
xml:
name: Category
User:
description: A User who is purchasing from the pet store
example:
firstName: firstName
lastName: lastName
password: password
userStatus: 6
phone: phone
id: 0
email: email
username: username
properties:
id:
format: int64
type: integer
username:
type: string
firstName:
type: string
lastName:
type: string
email:
type: string
password:
type: string
phone:
type: string
userStatus:
description: User Status
format: int32
type: integer
title: a User
xml:
name: User
Tag:
description: A tag for a pet
example:
name: name
id: 1
properties:
id:
format: int64
type: integer
name:
type: string
title: Pet Tag
xml:
name: Tag
Pet:
description: A pet for sale in the pet store
example:
photoUrls:
- photoUrls
- photoUrls
name: doggie
id: 0
category:
name: name
id: 6
tags:
- name: name
id: 1
- name: name
id: 1
status: available
properties:
id:
format: int64
type: integer
category:
$ref: '#/components/schemas/Category'
name:
example: doggie
type: string
photoUrls:
items:
type: string
type: array
xml:
name: photoUrl
wrapped: true
tags:
items:
$ref: '#/components/schemas/Tag'
type: array
xml:
name: tag
wrapped: true
status:
deprecated: true
description: pet status in the store
enum:
- available
- pending
- sold
type: string
required:
- name
- photoUrls
title: a Pet
xml:
name: Pet
ApiResponse:
description: Describes the result of uploading an image resource
example:
code: 0
type: type
message: message
properties:
code:
format: int32
type: integer
type:
type: string
message:
type: string
title: An uploaded response
StringOrInt:
anyOf:
- type: string
- format: int32
type: integer
description: string or int
OneOfStringOrInt:
description: string or int (onefOf)
oneOf:
- type: string
- type: integer
Dog:
allOf:
- $ref: '#/components/schemas/Animal'
- properties:
breed:
type: string
Cat:
allOf:
- $ref: '#/components/schemas/Animal'
- properties:
declawed:
type: boolean
Animal:
discriminator:
propertyName: className
properties:
className:
type: string
color:
default: red
type: string
required:
- className
updatePetWithForm_request:
properties:
name:
description: Updated name of the pet
type: string
status:
description: Updated status of the pet
type: string
uploadFile_request:
properties:
additionalMetadata:
description: Additional data to pass to server
type: string
file:
description: file to upload
format: binary
type: string
securitySchemes:
petstore_auth:
flows:
implicit:
authorizationUrl: http://petstore.swagger.io/api/oauth/dialog
scopes:
write:pets: modify pets in your account
read:pets: read your pets
type: oauth2
api_key:
in: header
name: api_key
type: apiKey

View File

@ -0,0 +1,169 @@
apply plugin: 'idea'
apply plugin: 'eclipse'
apply plugin: 'java'
apply plugin: 'com.diffplug.spotless'
group = 'org.openapitools'
version = '1.0.0'
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.3.+'
classpath 'com.github.dcendents:android-maven-gradle-plugin:2.1'
classpath 'com.diffplug.spotless:spotless-plugin-gradle:6.11.0'
}
}
repositories {
mavenCentral()
}
sourceSets {
main.java.srcDirs = ['src/main/java']
}
if(hasProperty('target') && target == 'android') {
apply plugin: 'com.android.library'
apply plugin: 'com.github.dcendents.android-maven'
android {
compileSdkVersion 25
buildToolsVersion '25.0.2'
defaultConfig {
minSdkVersion 14
targetSdkVersion 25
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
// Rename the aar correctly
libraryVariants.all { variant ->
variant.outputs.each { output ->
def outputFile = output.outputFile
if (outputFile != null && outputFile.name.endsWith('.aar')) {
def fileName = "${project.name}-${variant.baseName}-${version}.aar"
output.outputFile = new File(outputFile.parent, fileName)
}
}
}
dependencies {
provided "jakarta.annotation:jakarta.annotation-api:$jakarta_annotation_version"
}
}
afterEvaluate {
android.libraryVariants.all { variant ->
def task = project.tasks.create "jar${variant.name.capitalize()}", Jar
task.description = "Create jar artifact for ${variant.name}"
task.dependsOn variant.javaCompile
task.from variant.javaCompile.destinationDir
task.destinationDir = project.file("${project.buildDir}/outputs/jar")
task.archiveName = "${project.name}-${variant.baseName}-${version}.jar"
artifacts.add('archives', task)
}
}
task sourcesJar(type: Jar) {
from android.sourceSets.main.java.srcDirs
classifier = 'sources'
}
artifacts {
archives sourcesJar
}
} else {
apply plugin: 'java'
apply plugin: 'maven-publish'
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
publishing {
publications {
maven(MavenPublication) {
artifactId = 'petstore-okhttp-gson-31'
from components.java
}
}
}
task execute(type:JavaExec) {
main = System.getProperty('mainClass')
classpath = sourceSets.main.runtimeClasspath
}
}
ext {
jakarta_annotation_version = "1.3.5"
}
dependencies {
implementation 'io.swagger:swagger-annotations:1.6.8'
implementation "com.google.code.findbugs:jsr305:3.0.2"
implementation 'com.squareup.okhttp3:okhttp:4.10.0'
implementation 'com.squareup.okhttp3:logging-interceptor:4.10.0'
implementation 'com.google.code.gson:gson:2.9.1'
implementation 'io.gsonfire:gson-fire:1.8.5'
implementation 'javax.ws.rs:jsr311-api:1.1.1'
implementation 'javax.ws.rs:javax.ws.rs-api:2.1.1'
implementation 'org.openapitools:jackson-databind-nullable:0.2.6'
implementation group: 'org.apache.oltu.oauth2', name: 'org.apache.oltu.oauth2.client', version: '1.0.2'
implementation group: 'org.apache.commons', name: 'commons-lang3', version: '3.12.0'
implementation "jakarta.annotation:jakarta.annotation-api:$jakarta_annotation_version"
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.9.1'
testImplementation 'org.mockito:mockito-core:3.12.4'
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.9.1'
}
javadoc {
options.tags = [ "http.response.details:a:Http Response Details" ]
}
// Use spotless plugin to automatically format code, remove unused import, etc
// To apply changes directly to the file, run `gradlew spotlessApply`
// Ref: https://github.com/diffplug/spotless/tree/main/plugin-gradle
spotless {
// comment out below to run spotless as part of the `check` task
enforceCheck false
format 'misc', {
// define the files (e.g. '*.gradle', '*.md') to apply `misc` to
target '.gitignore'
// define the steps to apply to those files
trimTrailingWhitespace()
indentWithSpaces() // Takes an integer argument if you don't like 4
endWithNewline()
}
java {
// don't need to set target, it is inferred from java
// apply a specific flavor of google-java-format
googleJavaFormat('1.8').aosp().reflowLongStrings()
removeUnusedImports()
importOrder()
}
}
test {
// Enable JUnit 5 (Gradle 4.6+).
useJUnitPlatform()
// Always run tests, even when nothing changed.
dependsOn 'cleanTest'
// Show test results.
testLogging {
events "passed", "skipped", "failed"
}
}

View File

@ -0,0 +1,29 @@
lazy val root = (project in file(".")).
settings(
organization := "org.openapitools",
name := "petstore-okhttp-gson-31",
version := "1.0.0",
scalaVersion := "2.11.4",
scalacOptions ++= Seq("-feature"),
javacOptions in compile ++= Seq("-Xlint:deprecation"),
publishArtifact in (Compile, packageDoc) := false,
resolvers += Resolver.mavenLocal,
libraryDependencies ++= Seq(
"io.swagger" % "swagger-annotations" % "1.6.5",
"com.squareup.okhttp3" % "okhttp" % "4.10.0",
"com.squareup.okhttp3" % "logging-interceptor" % "4.10.0",
"com.google.code.gson" % "gson" % "2.9.1",
"org.apache.commons" % "commons-lang3" % "3.12.0",
"javax.ws.rs" % "jsr311-api" % "1.1.1",
"javax.ws.rs" % "javax.ws.rs-api" % "2.1.1",
"org.openapitools" % "jackson-databind-nullable" % "0.2.6",
"org.apache.oltu.oauth2" % "org.apache.oltu.oauth2.client" % "1.0.2",
"io.gsonfire" % "gson-fire" % "1.8.5" % "compile",
"jakarta.annotation" % "jakarta.annotation-api" % "1.3.5" % "compile",
"com.google.code.findbugs" % "jsr305" % "3.0.2" % "compile",
"jakarta.annotation" % "jakarta.annotation-api" % "1.3.5" % "compile",
"org.junit.jupiter" % "junit-jupiter-api" % "5.9.1" % "test",
"com.novocode" % "junit-interface" % "0.10" % "test",
"org.mockito" % "mockito-core" % "3.12.4" % "test"
)
)

View File

@ -0,0 +1,14 @@
# Animal
## Properties
| Name | Type | Description | Notes |
|------------ | ------------- | ------------- | -------------|
|**className** | **String** | | |
|**color** | **String** | | [optional] |

View File

@ -0,0 +1,13 @@
# AnyOfStringOrInt
string or int (anyOf)
## Properties
| Name | Type | Description | Notes |
|------------ | ------------- | ------------- | -------------|

View File

@ -0,0 +1,13 @@
# Cat
## Properties
| Name | Type | Description | Notes |
|------------ | ------------- | ------------- | -------------|
|**declawed** | **Boolean** | | [optional] |

View File

@ -0,0 +1,15 @@
# Category
A category for a pet
## Properties
| Name | Type | Description | Notes |
|------------ | ------------- | ------------- | -------------|
|**id** | **Long** | | [optional] |
|**name** | **String** | | [optional] |

View File

@ -0,0 +1,13 @@
# Dog
## Properties
| Name | Type | Description | Notes |
|------------ | ------------- | ------------- | -------------|
|**breed** | **String** | | [optional] |

View File

@ -0,0 +1,16 @@
# ModelApiResponse
Describes the result of uploading an image resource
## Properties
| Name | Type | Description | Notes |
|------------ | ------------- | ------------- | -------------|
|**code** | **Integer** | | [optional] |
|**type** | **String** | | [optional] |
|**message** | **String** | | [optional] |

View File

@ -0,0 +1,13 @@
# OneOfStringOrInt
string or int (onefOf)
## Properties
| Name | Type | Description | Notes |
|------------ | ------------- | ------------- | -------------|

View File

@ -0,0 +1,29 @@
# Order
An order for a pets from the pet store
## Properties
| Name | Type | Description | Notes |
|------------ | ------------- | ------------- | -------------|
|**id** | **Long** | | [optional] |
|**petId** | **Long** | | [optional] |
|**quantity** | **Integer** | | [optional] |
|**shipDate** | **OffsetDateTime** | | [optional] |
|**status** | [**StatusEnum**](#StatusEnum) | Order Status | [optional] |
|**complete** | **Boolean** | | [optional] |
## Enum: StatusEnum
| Name | Value |
|---- | -----|
| PLACED | &quot;placed&quot; |
| APPROVED | &quot;approved&quot; |
| DELIVERED | &quot;delivered&quot; |

View File

@ -0,0 +1,29 @@
# Pet
A pet for sale in the pet store
## Properties
| Name | Type | Description | Notes |
|------------ | ------------- | ------------- | -------------|
|**id** | **Long** | | [optional] |
|**category** | [**Category**](Category.md) | | [optional] |
|**name** | **String** | | |
|**photoUrls** | **List&lt;String&gt;** | | |
|**tags** | [**List&lt;Tag&gt;**](Tag.md) | | [optional] |
|**status** | [**StatusEnum**](#StatusEnum) | pet status in the store | [optional] |
## Enum: StatusEnum
| Name | Value |
|---- | -----|
| AVAILABLE | &quot;available&quot; |
| PENDING | &quot;pending&quot; |
| SOLD | &quot;sold&quot; |

View File

@ -0,0 +1,570 @@
# PetApi
All URIs are relative to *http://petstore.swagger.io/v2*
| Method | HTTP request | Description |
|------------- | ------------- | -------------|
| [**addPet**](PetApi.md#addPet) | **POST** /pet | Add a new pet to the store |
| [**deletePet**](PetApi.md#deletePet) | **DELETE** /pet/{petId} | Deletes a pet |
| [**findPetsByStatus**](PetApi.md#findPetsByStatus) | **GET** /pet/findByStatus | Finds Pets by status |
| [**findPetsByTags**](PetApi.md#findPetsByTags) | **GET** /pet/findByTags | Finds Pets by tags |
| [**getPetById**](PetApi.md#getPetById) | **GET** /pet/{petId} | Find pet by ID |
| [**updatePet**](PetApi.md#updatePet) | **PUT** /pet | Update an existing pet |
| [**updatePetWithForm**](PetApi.md#updatePetWithForm) | **POST** /pet/{petId} | Updates a pet in the store with form data |
| [**uploadFile**](PetApi.md#uploadFile) | **POST** /pet/{petId}/uploadImage | uploads an image |
<a id="addPet"></a>
# **addPet**
> Pet addPet(pet)
Add a new pet to the store
### Example
```java
// Import classes:
import org.openapitools.client.ApiClient;
import org.openapitools.client.ApiException;
import org.openapitools.client.Configuration;
import org.openapitools.client.auth.*;
import org.openapitools.client.models.*;
import org.openapitools.client.api.PetApi;
public class Example {
public static void main(String[] args) {
ApiClient defaultClient = Configuration.getDefaultApiClient();
defaultClient.setBasePath("http://petstore.swagger.io/v2");
// Configure OAuth2 access token for authorization: petstore_auth
OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth");
petstore_auth.setAccessToken("YOUR ACCESS TOKEN");
PetApi apiInstance = new PetApi(defaultClient);
Pet pet = new Pet(); // Pet | Pet object that needs to be added to the store
try {
Pet result = apiInstance.addPet(pet);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling PetApi#addPet");
System.err.println("Status code: " + e.getCode());
System.err.println("Reason: " + e.getResponseBody());
System.err.println("Response headers: " + e.getResponseHeaders());
e.printStackTrace();
}
}
}
```
### Parameters
| Name | Type | Description | Notes |
|------------- | ------------- | ------------- | -------------|
| **pet** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | |
### Return type
[**Pet**](Pet.md)
### Authorization
[petstore_auth](../README.md#petstore_auth)
### HTTP request headers
- **Content-Type**: application/json, application/xml
- **Accept**: application/xml, application/json
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **200** | successful operation | - |
| **405** | Invalid input | - |
<a id="deletePet"></a>
# **deletePet**
> deletePet(petId, apiKey)
Deletes a pet
### Example
```java
// Import classes:
import org.openapitools.client.ApiClient;
import org.openapitools.client.ApiException;
import org.openapitools.client.Configuration;
import org.openapitools.client.auth.*;
import org.openapitools.client.models.*;
import org.openapitools.client.api.PetApi;
public class Example {
public static void main(String[] args) {
ApiClient defaultClient = Configuration.getDefaultApiClient();
defaultClient.setBasePath("http://petstore.swagger.io/v2");
// Configure OAuth2 access token for authorization: petstore_auth
OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth");
petstore_auth.setAccessToken("YOUR ACCESS TOKEN");
PetApi apiInstance = new PetApi(defaultClient);
Long petId = 56L; // Long | Pet id to delete
String apiKey = "apiKey_example"; // String |
try {
apiInstance.deletePet(petId, apiKey);
} catch (ApiException e) {
System.err.println("Exception when calling PetApi#deletePet");
System.err.println("Status code: " + e.getCode());
System.err.println("Reason: " + e.getResponseBody());
System.err.println("Response headers: " + e.getResponseHeaders());
e.printStackTrace();
}
}
}
```
### Parameters
| Name | Type | Description | Notes |
|------------- | ------------- | ------------- | -------------|
| **petId** | **Long**| Pet id to delete | |
| **apiKey** | **String**| | [optional] |
### Return type
null (empty response body)
### Authorization
[petstore_auth](../README.md#petstore_auth)
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: Not defined
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **400** | Invalid pet value | - |
<a id="findPetsByStatus"></a>
# **findPetsByStatus**
> List&lt;Pet&gt; findPetsByStatus(status)
Finds Pets by status
Multiple status values can be provided with comma separated strings
### Example
```java
// Import classes:
import org.openapitools.client.ApiClient;
import org.openapitools.client.ApiException;
import org.openapitools.client.Configuration;
import org.openapitools.client.auth.*;
import org.openapitools.client.models.*;
import org.openapitools.client.api.PetApi;
public class Example {
public static void main(String[] args) {
ApiClient defaultClient = Configuration.getDefaultApiClient();
defaultClient.setBasePath("http://petstore.swagger.io/v2");
// Configure OAuth2 access token for authorization: petstore_auth
OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth");
petstore_auth.setAccessToken("YOUR ACCESS TOKEN");
PetApi apiInstance = new PetApi(defaultClient);
List<String> status = Arrays.asList("available"); // List<String> | Status values that need to be considered for filter
try {
List<Pet> result = apiInstance.findPetsByStatus(status);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling PetApi#findPetsByStatus");
System.err.println("Status code: " + e.getCode());
System.err.println("Reason: " + e.getResponseBody());
System.err.println("Response headers: " + e.getResponseHeaders());
e.printStackTrace();
}
}
}
```
### Parameters
| Name | Type | Description | Notes |
|------------- | ------------- | ------------- | -------------|
| **status** | [**List&lt;String&gt;**](String.md)| Status values that need to be considered for filter | [enum: available, pending, sold] |
### Return type
[**List&lt;Pet&gt;**](Pet.md)
### Authorization
[petstore_auth](../README.md#petstore_auth)
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/xml, application/json
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **200** | successful operation | - |
| **400** | Invalid status value | - |
<a id="findPetsByTags"></a>
# **findPetsByTags**
> List&lt;Pet&gt; findPetsByTags(tags)
Finds Pets by tags
Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.
### Example
```java
// Import classes:
import org.openapitools.client.ApiClient;
import org.openapitools.client.ApiException;
import org.openapitools.client.Configuration;
import org.openapitools.client.auth.*;
import org.openapitools.client.models.*;
import org.openapitools.client.api.PetApi;
public class Example {
public static void main(String[] args) {
ApiClient defaultClient = Configuration.getDefaultApiClient();
defaultClient.setBasePath("http://petstore.swagger.io/v2");
// Configure OAuth2 access token for authorization: petstore_auth
OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth");
petstore_auth.setAccessToken("YOUR ACCESS TOKEN");
PetApi apiInstance = new PetApi(defaultClient);
List<String> tags = Arrays.asList(); // List<String> | Tags to filter by
try {
List<Pet> result = apiInstance.findPetsByTags(tags);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling PetApi#findPetsByTags");
System.err.println("Status code: " + e.getCode());
System.err.println("Reason: " + e.getResponseBody());
System.err.println("Response headers: " + e.getResponseHeaders());
e.printStackTrace();
}
}
}
```
### Parameters
| Name | Type | Description | Notes |
|------------- | ------------- | ------------- | -------------|
| **tags** | [**List&lt;String&gt;**](String.md)| Tags to filter by | |
### Return type
[**List&lt;Pet&gt;**](Pet.md)
### Authorization
[petstore_auth](../README.md#petstore_auth)
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/xml, application/json
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **200** | successful operation | - |
| **400** | Invalid tag value | - |
<a id="getPetById"></a>
# **getPetById**
> Pet getPetById(petId)
Find pet by ID
Returns a single pet
### Example
```java
// Import classes:
import org.openapitools.client.ApiClient;
import org.openapitools.client.ApiException;
import org.openapitools.client.Configuration;
import org.openapitools.client.auth.*;
import org.openapitools.client.models.*;
import org.openapitools.client.api.PetApi;
public class Example {
public static void main(String[] args) {
ApiClient defaultClient = Configuration.getDefaultApiClient();
defaultClient.setBasePath("http://petstore.swagger.io/v2");
// Configure API key authorization: api_key
ApiKeyAuth api_key = (ApiKeyAuth) defaultClient.getAuthentication("api_key");
api_key.setApiKey("YOUR API KEY");
// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
//api_key.setApiKeyPrefix("Token");
PetApi apiInstance = new PetApi(defaultClient);
Long petId = 56L; // Long | ID of pet to return
try {
Pet result = apiInstance.getPetById(petId);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling PetApi#getPetById");
System.err.println("Status code: " + e.getCode());
System.err.println("Reason: " + e.getResponseBody());
System.err.println("Response headers: " + e.getResponseHeaders());
e.printStackTrace();
}
}
}
```
### Parameters
| Name | Type | Description | Notes |
|------------- | ------------- | ------------- | -------------|
| **petId** | **Long**| ID of pet to return | |
### Return type
[**Pet**](Pet.md)
### Authorization
[api_key](../README.md#api_key)
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/xml, application/json
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **200** | successful operation | - |
| **400** | Invalid ID supplied | - |
| **404** | Pet not found | - |
<a id="updatePet"></a>
# **updatePet**
> Pet updatePet(pet)
Update an existing pet
### Example
```java
// Import classes:
import org.openapitools.client.ApiClient;
import org.openapitools.client.ApiException;
import org.openapitools.client.Configuration;
import org.openapitools.client.auth.*;
import org.openapitools.client.models.*;
import org.openapitools.client.api.PetApi;
public class Example {
public static void main(String[] args) {
ApiClient defaultClient = Configuration.getDefaultApiClient();
defaultClient.setBasePath("http://petstore.swagger.io/v2");
// Configure OAuth2 access token for authorization: petstore_auth
OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth");
petstore_auth.setAccessToken("YOUR ACCESS TOKEN");
PetApi apiInstance = new PetApi(defaultClient);
Pet pet = new Pet(); // Pet | Pet object that needs to be added to the store
try {
Pet result = apiInstance.updatePet(pet);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling PetApi#updatePet");
System.err.println("Status code: " + e.getCode());
System.err.println("Reason: " + e.getResponseBody());
System.err.println("Response headers: " + e.getResponseHeaders());
e.printStackTrace();
}
}
}
```
### Parameters
| Name | Type | Description | Notes |
|------------- | ------------- | ------------- | -------------|
| **pet** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | |
### Return type
[**Pet**](Pet.md)
### Authorization
[petstore_auth](../README.md#petstore_auth)
### HTTP request headers
- **Content-Type**: application/json, application/xml
- **Accept**: application/xml, application/json
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **200** | successful operation | - |
| **400** | Invalid ID supplied | - |
| **404** | Pet not found | - |
| **405** | Validation exception | - |
<a id="updatePetWithForm"></a>
# **updatePetWithForm**
> updatePetWithForm(petId, name, status)
Updates a pet in the store with form data
### Example
```java
// Import classes:
import org.openapitools.client.ApiClient;
import org.openapitools.client.ApiException;
import org.openapitools.client.Configuration;
import org.openapitools.client.auth.*;
import org.openapitools.client.models.*;
import org.openapitools.client.api.PetApi;
public class Example {
public static void main(String[] args) {
ApiClient defaultClient = Configuration.getDefaultApiClient();
defaultClient.setBasePath("http://petstore.swagger.io/v2");
// Configure OAuth2 access token for authorization: petstore_auth
OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth");
petstore_auth.setAccessToken("YOUR ACCESS TOKEN");
PetApi apiInstance = new PetApi(defaultClient);
Long petId = 56L; // Long | ID of pet that needs to be updated
String name = "name_example"; // String | Updated name of the pet
String status = "status_example"; // String | Updated status of the pet
try {
apiInstance.updatePetWithForm(petId, name, status);
} catch (ApiException e) {
System.err.println("Exception when calling PetApi#updatePetWithForm");
System.err.println("Status code: " + e.getCode());
System.err.println("Reason: " + e.getResponseBody());
System.err.println("Response headers: " + e.getResponseHeaders());
e.printStackTrace();
}
}
}
```
### Parameters
| Name | Type | Description | Notes |
|------------- | ------------- | ------------- | -------------|
| **petId** | **Long**| ID of pet that needs to be updated | |
| **name** | **String**| Updated name of the pet | [optional] |
| **status** | **String**| Updated status of the pet | [optional] |
### Return type
null (empty response body)
### Authorization
[petstore_auth](../README.md#petstore_auth)
### HTTP request headers
- **Content-Type**: application/x-www-form-urlencoded
- **Accept**: Not defined
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **405** | Invalid input | - |
<a id="uploadFile"></a>
# **uploadFile**
> ModelApiResponse uploadFile(petId, additionalMetadata, _file)
uploads an image
### Example
```java
// Import classes:
import org.openapitools.client.ApiClient;
import org.openapitools.client.ApiException;
import org.openapitools.client.Configuration;
import org.openapitools.client.auth.*;
import org.openapitools.client.models.*;
import org.openapitools.client.api.PetApi;
public class Example {
public static void main(String[] args) {
ApiClient defaultClient = Configuration.getDefaultApiClient();
defaultClient.setBasePath("http://petstore.swagger.io/v2");
// Configure OAuth2 access token for authorization: petstore_auth
OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth");
petstore_auth.setAccessToken("YOUR ACCESS TOKEN");
PetApi apiInstance = new PetApi(defaultClient);
Long petId = 56L; // Long | ID of pet to update
String additionalMetadata = "additionalMetadata_example"; // String | Additional data to pass to server
File _file = new File("/path/to/file"); // File | file to upload
try {
ModelApiResponse result = apiInstance.uploadFile(petId, additionalMetadata, _file);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling PetApi#uploadFile");
System.err.println("Status code: " + e.getCode());
System.err.println("Reason: " + e.getResponseBody());
System.err.println("Response headers: " + e.getResponseHeaders());
e.printStackTrace();
}
}
}
```
### Parameters
| Name | Type | Description | Notes |
|------------- | ------------- | ------------- | -------------|
| **petId** | **Long**| ID of pet to update | |
| **additionalMetadata** | **String**| Additional data to pass to server | [optional] |
| **_file** | **File**| file to upload | [optional] |
### Return type
[**ModelApiResponse**](ModelApiResponse.md)
### Authorization
[petstore_auth](../README.md#petstore_auth)
### HTTP request headers
- **Content-Type**: multipart/form-data
- **Accept**: application/json
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **200** | successful operation | - |

View File

@ -0,0 +1,266 @@
# StoreApi
All URIs are relative to *http://petstore.swagger.io/v2*
| Method | HTTP request | Description |
|------------- | ------------- | -------------|
| [**deleteOrder**](StoreApi.md#deleteOrder) | **DELETE** /store/order/{orderId} | Delete purchase order by ID |
| [**getInventory**](StoreApi.md#getInventory) | **GET** /store/inventory | Returns pet inventories by status |
| [**getOrderById**](StoreApi.md#getOrderById) | **GET** /store/order/{orderId} | Find purchase order by ID |
| [**placeOrder**](StoreApi.md#placeOrder) | **POST** /store/order | Place an order for a pet |
<a id="deleteOrder"></a>
# **deleteOrder**
> deleteOrder(orderId)
Delete purchase order by ID
For valid response try integer IDs with value &lt; 1000. Anything above 1000 or nonintegers will generate API errors
### Example
```java
// Import classes:
import org.openapitools.client.ApiClient;
import org.openapitools.client.ApiException;
import org.openapitools.client.Configuration;
import org.openapitools.client.models.*;
import org.openapitools.client.api.StoreApi;
public class Example {
public static void main(String[] args) {
ApiClient defaultClient = Configuration.getDefaultApiClient();
defaultClient.setBasePath("http://petstore.swagger.io/v2");
StoreApi apiInstance = new StoreApi(defaultClient);
String orderId = "orderId_example"; // String | ID of the order that needs to be deleted
try {
apiInstance.deleteOrder(orderId);
} catch (ApiException e) {
System.err.println("Exception when calling StoreApi#deleteOrder");
System.err.println("Status code: " + e.getCode());
System.err.println("Reason: " + e.getResponseBody());
System.err.println("Response headers: " + e.getResponseHeaders());
e.printStackTrace();
}
}
}
```
### Parameters
| Name | Type | Description | Notes |
|------------- | ------------- | ------------- | -------------|
| **orderId** | **String**| ID of the order that needs to be deleted | |
### Return type
null (empty response body)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: Not defined
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **400** | Invalid ID supplied | - |
| **404** | Order not found | - |
<a id="getInventory"></a>
# **getInventory**
> Map&lt;String, Integer&gt; getInventory()
Returns pet inventories by status
Returns a map of status codes to quantities
### Example
```java
// Import classes:
import org.openapitools.client.ApiClient;
import org.openapitools.client.ApiException;
import org.openapitools.client.Configuration;
import org.openapitools.client.auth.*;
import org.openapitools.client.models.*;
import org.openapitools.client.api.StoreApi;
public class Example {
public static void main(String[] args) {
ApiClient defaultClient = Configuration.getDefaultApiClient();
defaultClient.setBasePath("http://petstore.swagger.io/v2");
// Configure API key authorization: api_key
ApiKeyAuth api_key = (ApiKeyAuth) defaultClient.getAuthentication("api_key");
api_key.setApiKey("YOUR API KEY");
// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
//api_key.setApiKeyPrefix("Token");
StoreApi apiInstance = new StoreApi(defaultClient);
try {
Map<String, Integer> result = apiInstance.getInventory();
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling StoreApi#getInventory");
System.err.println("Status code: " + e.getCode());
System.err.println("Reason: " + e.getResponseBody());
System.err.println("Response headers: " + e.getResponseHeaders());
e.printStackTrace();
}
}
}
```
### Parameters
This endpoint does not need any parameter.
### Return type
**Map&lt;String, Integer&gt;**
### Authorization
[api_key](../README.md#api_key)
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/json
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **200** | successful operation | - |
<a id="getOrderById"></a>
# **getOrderById**
> Order getOrderById(orderId)
Find purchase order by ID
For valid response try integer IDs with value &lt;&#x3D; 5 or &gt; 10. Other values will generate exceptions
### Example
```java
// Import classes:
import org.openapitools.client.ApiClient;
import org.openapitools.client.ApiException;
import org.openapitools.client.Configuration;
import org.openapitools.client.models.*;
import org.openapitools.client.api.StoreApi;
public class Example {
public static void main(String[] args) {
ApiClient defaultClient = Configuration.getDefaultApiClient();
defaultClient.setBasePath("http://petstore.swagger.io/v2");
StoreApi apiInstance = new StoreApi(defaultClient);
Long orderId = 56L; // Long | ID of pet that needs to be fetched
try {
Order result = apiInstance.getOrderById(orderId);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling StoreApi#getOrderById");
System.err.println("Status code: " + e.getCode());
System.err.println("Reason: " + e.getResponseBody());
System.err.println("Response headers: " + e.getResponseHeaders());
e.printStackTrace();
}
}
}
```
### Parameters
| Name | Type | Description | Notes |
|------------- | ------------- | ------------- | -------------|
| **orderId** | **Long**| ID of pet that needs to be fetched | |
### Return type
[**Order**](Order.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/xml, application/json
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **200** | successful operation | - |
| **400** | Invalid ID supplied | - |
| **404** | Order not found | - |
<a id="placeOrder"></a>
# **placeOrder**
> Order placeOrder(order)
Place an order for a pet
### Example
```java
// Import classes:
import org.openapitools.client.ApiClient;
import org.openapitools.client.ApiException;
import org.openapitools.client.Configuration;
import org.openapitools.client.models.*;
import org.openapitools.client.api.StoreApi;
public class Example {
public static void main(String[] args) {
ApiClient defaultClient = Configuration.getDefaultApiClient();
defaultClient.setBasePath("http://petstore.swagger.io/v2");
StoreApi apiInstance = new StoreApi(defaultClient);
Order order = new Order(); // Order | order placed for purchasing the pet
try {
Order result = apiInstance.placeOrder(order);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling StoreApi#placeOrder");
System.err.println("Status code: " + e.getCode());
System.err.println("Reason: " + e.getResponseBody());
System.err.println("Response headers: " + e.getResponseHeaders());
e.printStackTrace();
}
}
}
```
### Parameters
| Name | Type | Description | Notes |
|------------- | ------------- | ------------- | -------------|
| **order** | [**Order**](Order.md)| order placed for purchasing the pet | |
### Return type
[**Order**](Order.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json
- **Accept**: application/xml, application/json
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **200** | successful operation | - |
| **400** | Invalid Order | - |

View File

@ -0,0 +1,13 @@
# StringOrInt
string or int
## Properties
| Name | Type | Description | Notes |
|------------ | ------------- | ------------- | -------------|

View File

@ -0,0 +1,15 @@
# Tag
A tag for a pet
## Properties
| Name | Type | Description | Notes |
|------------ | ------------- | ------------- | -------------|
|**id** | **Long** | | [optional] |
|**name** | **String** | | [optional] |

View File

@ -0,0 +1,21 @@
# User
A User who is purchasing from the pet store
## Properties
| Name | Type | Description | Notes |
|------------ | ------------- | ------------- | -------------|
|**id** | **Long** | | [optional] |
|**username** | **String** | | [optional] |
|**firstName** | **String** | | [optional] |
|**lastName** | **String** | | [optional] |
|**email** | **String** | | [optional] |
|**password** | **String** | | [optional] |
|**phone** | **String** | | [optional] |
|**userStatus** | **Integer** | User Status | [optional] |

View File

@ -0,0 +1,553 @@
# UserApi
All URIs are relative to *http://petstore.swagger.io/v2*
| Method | HTTP request | Description |
|------------- | ------------- | -------------|
| [**createUser**](UserApi.md#createUser) | **POST** /user | Create user |
| [**createUsersWithArrayInput**](UserApi.md#createUsersWithArrayInput) | **POST** /user/createWithArray | Creates list of users with given input array |
| [**createUsersWithListInput**](UserApi.md#createUsersWithListInput) | **POST** /user/createWithList | Creates list of users with given input array |
| [**deleteUser**](UserApi.md#deleteUser) | **DELETE** /user/{username} | Delete user |
| [**getUserByName**](UserApi.md#getUserByName) | **GET** /user/{username} | Get user by user name |
| [**loginUser**](UserApi.md#loginUser) | **GET** /user/login | Logs user into the system |
| [**logoutUser**](UserApi.md#logoutUser) | **GET** /user/logout | Logs out current logged in user session |
| [**updateUser**](UserApi.md#updateUser) | **PUT** /user/{username} | Updated user |
<a id="createUser"></a>
# **createUser**
> createUser(user)
Create user
This can only be done by the logged in user.
### Example
```java
// Import classes:
import org.openapitools.client.ApiClient;
import org.openapitools.client.ApiException;
import org.openapitools.client.Configuration;
import org.openapitools.client.auth.*;
import org.openapitools.client.models.*;
import org.openapitools.client.api.UserApi;
public class Example {
public static void main(String[] args) {
ApiClient defaultClient = Configuration.getDefaultApiClient();
defaultClient.setBasePath("http://petstore.swagger.io/v2");
// Configure API key authorization: api_key
ApiKeyAuth api_key = (ApiKeyAuth) defaultClient.getAuthentication("api_key");
api_key.setApiKey("YOUR API KEY");
// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
//api_key.setApiKeyPrefix("Token");
UserApi apiInstance = new UserApi(defaultClient);
User user = new User(); // User | Created user object
try {
apiInstance.createUser(user);
} catch (ApiException e) {
System.err.println("Exception when calling UserApi#createUser");
System.err.println("Status code: " + e.getCode());
System.err.println("Reason: " + e.getResponseBody());
System.err.println("Response headers: " + e.getResponseHeaders());
e.printStackTrace();
}
}
}
```
### Parameters
| Name | Type | Description | Notes |
|------------- | ------------- | ------------- | -------------|
| **user** | [**User**](User.md)| Created user object | |
### Return type
null (empty response body)
### Authorization
[api_key](../README.md#api_key)
### HTTP request headers
- **Content-Type**: application/json
- **Accept**: Not defined
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **0** | successful operation | - |
<a id="createUsersWithArrayInput"></a>
# **createUsersWithArrayInput**
> createUsersWithArrayInput(user)
Creates list of users with given input array
### Example
```java
// Import classes:
import org.openapitools.client.ApiClient;
import org.openapitools.client.ApiException;
import org.openapitools.client.Configuration;
import org.openapitools.client.auth.*;
import org.openapitools.client.models.*;
import org.openapitools.client.api.UserApi;
public class Example {
public static void main(String[] args) {
ApiClient defaultClient = Configuration.getDefaultApiClient();
defaultClient.setBasePath("http://petstore.swagger.io/v2");
// Configure API key authorization: api_key
ApiKeyAuth api_key = (ApiKeyAuth) defaultClient.getAuthentication("api_key");
api_key.setApiKey("YOUR API KEY");
// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
//api_key.setApiKeyPrefix("Token");
UserApi apiInstance = new UserApi(defaultClient);
List<User> user = Arrays.asList(); // List<User> | List of user object
try {
apiInstance.createUsersWithArrayInput(user);
} catch (ApiException e) {
System.err.println("Exception when calling UserApi#createUsersWithArrayInput");
System.err.println("Status code: " + e.getCode());
System.err.println("Reason: " + e.getResponseBody());
System.err.println("Response headers: " + e.getResponseHeaders());
e.printStackTrace();
}
}
}
```
### Parameters
| Name | Type | Description | Notes |
|------------- | ------------- | ------------- | -------------|
| **user** | [**List&lt;User&gt;**](User.md)| List of user object | |
### Return type
null (empty response body)
### Authorization
[api_key](../README.md#api_key)
### HTTP request headers
- **Content-Type**: application/json
- **Accept**: Not defined
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **0** | successful operation | - |
<a id="createUsersWithListInput"></a>
# **createUsersWithListInput**
> createUsersWithListInput(user)
Creates list of users with given input array
### Example
```java
// Import classes:
import org.openapitools.client.ApiClient;
import org.openapitools.client.ApiException;
import org.openapitools.client.Configuration;
import org.openapitools.client.auth.*;
import org.openapitools.client.models.*;
import org.openapitools.client.api.UserApi;
public class Example {
public static void main(String[] args) {
ApiClient defaultClient = Configuration.getDefaultApiClient();
defaultClient.setBasePath("http://petstore.swagger.io/v2");
// Configure API key authorization: api_key
ApiKeyAuth api_key = (ApiKeyAuth) defaultClient.getAuthentication("api_key");
api_key.setApiKey("YOUR API KEY");
// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
//api_key.setApiKeyPrefix("Token");
UserApi apiInstance = new UserApi(defaultClient);
List<User> user = Arrays.asList(); // List<User> | List of user object
try {
apiInstance.createUsersWithListInput(user);
} catch (ApiException e) {
System.err.println("Exception when calling UserApi#createUsersWithListInput");
System.err.println("Status code: " + e.getCode());
System.err.println("Reason: " + e.getResponseBody());
System.err.println("Response headers: " + e.getResponseHeaders());
e.printStackTrace();
}
}
}
```
### Parameters
| Name | Type | Description | Notes |
|------------- | ------------- | ------------- | -------------|
| **user** | [**List&lt;User&gt;**](User.md)| List of user object | |
### Return type
null (empty response body)
### Authorization
[api_key](../README.md#api_key)
### HTTP request headers
- **Content-Type**: application/json
- **Accept**: Not defined
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **0** | successful operation | - |
<a id="deleteUser"></a>
# **deleteUser**
> deleteUser(username)
Delete user
This can only be done by the logged in user.
### Example
```java
// Import classes:
import org.openapitools.client.ApiClient;
import org.openapitools.client.ApiException;
import org.openapitools.client.Configuration;
import org.openapitools.client.auth.*;
import org.openapitools.client.models.*;
import org.openapitools.client.api.UserApi;
public class Example {
public static void main(String[] args) {
ApiClient defaultClient = Configuration.getDefaultApiClient();
defaultClient.setBasePath("http://petstore.swagger.io/v2");
// Configure API key authorization: api_key
ApiKeyAuth api_key = (ApiKeyAuth) defaultClient.getAuthentication("api_key");
api_key.setApiKey("YOUR API KEY");
// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
//api_key.setApiKeyPrefix("Token");
UserApi apiInstance = new UserApi(defaultClient);
String username = "username_example"; // String | The name that needs to be deleted
try {
apiInstance.deleteUser(username);
} catch (ApiException e) {
System.err.println("Exception when calling UserApi#deleteUser");
System.err.println("Status code: " + e.getCode());
System.err.println("Reason: " + e.getResponseBody());
System.err.println("Response headers: " + e.getResponseHeaders());
e.printStackTrace();
}
}
}
```
### Parameters
| Name | Type | Description | Notes |
|------------- | ------------- | ------------- | -------------|
| **username** | **String**| The name that needs to be deleted | |
### Return type
null (empty response body)
### Authorization
[api_key](../README.md#api_key)
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: Not defined
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **400** | Invalid username supplied | - |
| **404** | User not found | - |
<a id="getUserByName"></a>
# **getUserByName**
> User getUserByName(username)
Get user by user name
### Example
```java
// Import classes:
import org.openapitools.client.ApiClient;
import org.openapitools.client.ApiException;
import org.openapitools.client.Configuration;
import org.openapitools.client.models.*;
import org.openapitools.client.api.UserApi;
public class Example {
public static void main(String[] args) {
ApiClient defaultClient = Configuration.getDefaultApiClient();
defaultClient.setBasePath("http://petstore.swagger.io/v2");
UserApi apiInstance = new UserApi(defaultClient);
String username = "username_example"; // String | The name that needs to be fetched. Use user1 for testing.
try {
User result = apiInstance.getUserByName(username);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling UserApi#getUserByName");
System.err.println("Status code: " + e.getCode());
System.err.println("Reason: " + e.getResponseBody());
System.err.println("Response headers: " + e.getResponseHeaders());
e.printStackTrace();
}
}
}
```
### Parameters
| Name | Type | Description | Notes |
|------------- | ------------- | ------------- | -------------|
| **username** | **String**| The name that needs to be fetched. Use user1 for testing. | |
### Return type
[**User**](User.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/xml, application/json
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **200** | successful operation | - |
| **400** | Invalid username supplied | - |
| **404** | User not found | - |
<a id="loginUser"></a>
# **loginUser**
> String loginUser(username, password)
Logs user into the system
### Example
```java
// Import classes:
import org.openapitools.client.ApiClient;
import org.openapitools.client.ApiException;
import org.openapitools.client.Configuration;
import org.openapitools.client.models.*;
import org.openapitools.client.api.UserApi;
public class Example {
public static void main(String[] args) {
ApiClient defaultClient = Configuration.getDefaultApiClient();
defaultClient.setBasePath("http://petstore.swagger.io/v2");
UserApi apiInstance = new UserApi(defaultClient);
String username = "username_example"; // String | The user name for login
String password = "password_example"; // String | The password for login in clear text
try {
String result = apiInstance.loginUser(username, password);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling UserApi#loginUser");
System.err.println("Status code: " + e.getCode());
System.err.println("Reason: " + e.getResponseBody());
System.err.println("Response headers: " + e.getResponseHeaders());
e.printStackTrace();
}
}
}
```
### Parameters
| Name | Type | Description | Notes |
|------------- | ------------- | ------------- | -------------|
| **username** | **String**| The user name for login | |
| **password** | **String**| The password for login in clear text | |
### Return type
**String**
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/xml, application/json
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **200** | successful operation | * Set-Cookie - Cookie authentication key for use with the &#x60;api_key&#x60; apiKey authentication. <br> * X-Rate-Limit - calls per hour allowed by the user <br> * X-Expires-After - date in UTC when token expires <br> |
| **400** | Invalid username/password supplied | - |
<a id="logoutUser"></a>
# **logoutUser**
> logoutUser()
Logs out current logged in user session
### Example
```java
// Import classes:
import org.openapitools.client.ApiClient;
import org.openapitools.client.ApiException;
import org.openapitools.client.Configuration;
import org.openapitools.client.auth.*;
import org.openapitools.client.models.*;
import org.openapitools.client.api.UserApi;
public class Example {
public static void main(String[] args) {
ApiClient defaultClient = Configuration.getDefaultApiClient();
defaultClient.setBasePath("http://petstore.swagger.io/v2");
// Configure API key authorization: api_key
ApiKeyAuth api_key = (ApiKeyAuth) defaultClient.getAuthentication("api_key");
api_key.setApiKey("YOUR API KEY");
// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
//api_key.setApiKeyPrefix("Token");
UserApi apiInstance = new UserApi(defaultClient);
try {
apiInstance.logoutUser();
} catch (ApiException e) {
System.err.println("Exception when calling UserApi#logoutUser");
System.err.println("Status code: " + e.getCode());
System.err.println("Reason: " + e.getResponseBody());
System.err.println("Response headers: " + e.getResponseHeaders());
e.printStackTrace();
}
}
}
```
### Parameters
This endpoint does not need any parameter.
### Return type
null (empty response body)
### Authorization
[api_key](../README.md#api_key)
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: Not defined
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **0** | successful operation | - |
<a id="updateUser"></a>
# **updateUser**
> updateUser(username, user)
Updated user
This can only be done by the logged in user.
### Example
```java
// Import classes:
import org.openapitools.client.ApiClient;
import org.openapitools.client.ApiException;
import org.openapitools.client.Configuration;
import org.openapitools.client.auth.*;
import org.openapitools.client.models.*;
import org.openapitools.client.api.UserApi;
public class Example {
public static void main(String[] args) {
ApiClient defaultClient = Configuration.getDefaultApiClient();
defaultClient.setBasePath("http://petstore.swagger.io/v2");
// Configure API key authorization: api_key
ApiKeyAuth api_key = (ApiKeyAuth) defaultClient.getAuthentication("api_key");
api_key.setApiKey("YOUR API KEY");
// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
//api_key.setApiKeyPrefix("Token");
UserApi apiInstance = new UserApi(defaultClient);
String username = "username_example"; // String | name that need to be deleted
User user = new User(); // User | Updated user object
try {
apiInstance.updateUser(username, user);
} catch (ApiException e) {
System.err.println("Exception when calling UserApi#updateUser");
System.err.println("Status code: " + e.getCode());
System.err.println("Reason: " + e.getResponseBody());
System.err.println("Response headers: " + e.getResponseHeaders());
e.printStackTrace();
}
}
}
```
### Parameters
| Name | Type | Description | Notes |
|------------- | ------------- | ------------- | -------------|
| **username** | **String**| name that need to be deleted | |
| **user** | [**User**](User.md)| Updated user object | |
### Return type
null (empty response body)
### Authorization
[api_key](../README.md#api_key)
### HTTP request headers
- **Content-Type**: application/json
- **Accept**: Not defined
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **400** | Invalid user supplied | - |
| **404** | User not found | - |

View File

@ -0,0 +1,57 @@
#!/bin/sh
# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/
#
# Usage example: /bin/sh ./git_push.sh wing328 openapi-petstore-perl "minor update" "gitlab.com"
git_user_id=$1
git_repo_id=$2
release_note=$3
git_host=$4
if [ "$git_host" = "" ]; then
git_host="github.com"
echo "[INFO] No command line input provided. Set \$git_host to $git_host"
fi
if [ "$git_user_id" = "" ]; then
git_user_id="GIT_USER_ID"
echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id"
fi
if [ "$git_repo_id" = "" ]; then
git_repo_id="GIT_REPO_ID"
echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id"
fi
if [ "$release_note" = "" ]; then
release_note="Minor update"
echo "[INFO] No command line input provided. Set \$release_note to $release_note"
fi
# Initialize the local directory as a Git repository
git init
# Adds the files in the local repository and stages them for commit.
git add .
# Commits the tracked changes and prepares them to be pushed to a remote repository.
git commit -m "$release_note"
# Sets the new remote
git_remote=$(git remote)
if [ "$git_remote" = "" ]; then # git remote not defined
if [ "$GIT_TOKEN" = "" ]; then
echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment."
git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git
else
git remote add origin https://${git_user_id}:"${GIT_TOKEN}"@${git_host}/${git_user_id}/${git_repo_id}.git
fi
fi
git pull origin master
# Pushes (Forces) the changes in the local repository up to the remote repository
echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git"
git push origin master 2>&1 | grep -v 'To https'

View File

@ -0,0 +1,6 @@
# This file is automatically generated by OpenAPI Generator (https://github.com/openAPITools/openapi-generator).
# To include other gradle properties as part of the code generation process, please use the `gradleProperties` option.
#
# Gradle properties reference: https://docs.gradle.org/current/userguide/build_environment.html#sec:gradle_configuration_properties
# For example, uncomment below to build for Android
#target = android

View File

@ -0,0 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.2-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

View File

@ -0,0 +1,234 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# 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
#
# https://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.
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
APP_NAME="Gradle"
APP_BASE_NAME=${0##*/}
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='-Dfile.encoding=UTF-8 "-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in
# double quotes to make sure that they get re-expanded; and
# * put everything else in single quotes, so that it's not re-expanded.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"

View File

@ -0,0 +1,89 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=-Dfile.encoding=UTF-8 "-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

View File

@ -0,0 +1,357 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.openapitools</groupId>
<artifactId>petstore-okhttp-gson-31</artifactId>
<packaging>jar</packaging>
<name>petstore-okhttp-gson-31</name>
<version>1.0.0</version>
<url>https://github.com/openapitools/openapi-generator</url>
<description>OpenAPI Java</description>
<scm>
<connection>scm:git:git@github.com:openapitools/openapi-generator.git</connection>
<developerConnection>scm:git:git@github.com:openapitools/openapi-generator.git</developerConnection>
<url>https://github.com/openapitools/openapi-generator</url>
</scm>
<licenses>
<license>
<name>Unlicense</name>
<url>https://www.apache.org/licenses/LICENSE-2.0.html</url>
<distribution>repo</distribution>
</license>
</licenses>
<developers>
<developer>
<name>OpenAPI-Generator Contributors</name>
<email>team@openapitools.org</email>
<organization>OpenAPITools.org</organization>
<organizationUrl>http://openapitools.org</organizationUrl>
</developer>
</developers>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<fork>true</fork>
<meminitial>128m</meminitial>
<maxmem>512m</maxmem>
<compilerArgs>
<arg>-Xlint:all</arg>
<arg>-J-Xss4m</arg><!-- Compiling the generated JSON.java file may require larger stack size. -->
</compilerArgs>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-enforcer-plugin</artifactId>
<version>3.1.0</version>
<executions>
<execution>
<id>enforce-maven</id>
<goals>
<goal>enforce</goal>
</goals>
<configuration>
<rules>
<requireMavenVersion>
<version>2.2.0</version>
</requireMavenVersion>
</rules>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
<configuration>
<systemProperties>
<property>
<name>loggerPath</name>
<value>conf/log4j.properties</value>
</property>
</systemProperties>
<argLine>-Xms512m -Xmx1500m</argLine>
<parallel>methods</parallel>
<threadCount>10</threadCount>
</configuration>
<dependencies>
<!--Custom provider and engine for Junit 5 to surefire-->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit-version}</version>
</dependency>
</dependencies>
</plugin>
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
<version>3.3.0</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/lib</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
<!-- attach test jar -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.3.0</version>
<executions>
<execution>
<goals>
<goal>test-jar</goal>
</goals>
</execution>
</executions>
<configuration>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<version>3.3.0</version>
<executions>
<execution>
<id>add_sources</id>
<phase>generate-sources</phase>
<goals>
<goal>add-source</goal>
</goals>
<configuration>
<sources>
<source>src/main/java</source>
</sources>
</configuration>
</execution>
<execution>
<id>add_test_sources</id>
<phase>generate-test-sources</phase>
<goals>
<goal>add-test-source</goal>
</goals>
<configuration>
<sources>
<source>src/test/java</source>
</sources>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>3.4.1</version>
<executions>
<execution>
<id>attach-javadocs</id>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
<configuration>
<doclint>none</doclint>
<tags>
<tag>
<name>http.response.details</name>
<placement>a</placement>
<head>Http Response Details:</head>
</tag>
</tags>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>3.2.1</version>
<executions>
<execution>
<id>attach-sources</id>
<goals>
<goal>jar-no-fork</goal>
</goals>
</execution>
</executions>
</plugin>
<!-- Use spotless plugin to automatically format code, remove unused import, etc
To apply changes directly to the file, run `mvn spotless:apply`
Ref: https://github.com/diffplug/spotless/tree/main/plugin-maven
-->
<plugin>
<groupId>com.diffplug.spotless</groupId>
<artifactId>spotless-maven-plugin</artifactId>
<version>${spotless.version}</version>
<configuration>
<formats>
<!-- you can define as many formats as you want, each is independent -->
<format>
<!-- define the files to apply to -->
<includes>
<include>.gitignore</include>
</includes>
<!-- define the steps to apply to those files -->
<trimTrailingWhitespace/>
<endWithNewline/>
<indent>
<spaces>true</spaces> <!-- or <tabs>true</tabs> -->
<spacesPerTab>4</spacesPerTab> <!-- optional, default is 4 -->
</indent>
</format>
</formats>
<!-- define a language-specific format -->
<java>
<!-- no need to specify files, inferred automatically, but you can if you want -->
<!-- apply a specific flavor of google-java-format and reflow long strings -->
<googleJavaFormat>
<version>1.8</version>
<style>AOSP</style>
<reflowLongStrings>true</reflowLongStrings>
</googleJavaFormat>
<removeUnusedImports/>
<importOrder/>
</java>
</configuration>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>sign-artifacts</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-gpg-plugin</artifactId>
<version>3.0.1</version>
<executions>
<execution>
<id>sign-artifacts</id>
<phase>verify</phase>
<goals>
<goal>sign</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<dependencies>
<!-- @Nullable annotation -->
<dependency>
<groupId>com.google.code.findbugs</groupId>
<artifactId>jsr305</artifactId>
<version>3.0.2</version>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>${okhttp-version}</version>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>logging-interceptor</artifactId>
<version>${okhttp-version}</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>${gson-version}</version>
</dependency>
<dependency>
<groupId>io.gsonfire</groupId>
<artifactId>gson-fire</artifactId>
<version>${gson-fire-version}</version>
</dependency>
<dependency>
<groupId>org.apache.oltu.oauth2</groupId>
<artifactId>org.apache.oltu.oauth2.client</artifactId>
<version>1.0.2</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3-version}</version>
</dependency>
<dependency>
<groupId>jakarta.annotation</groupId>
<artifactId>jakarta.annotation-api</artifactId>
<version>${jakarta-annotation-version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.openapitools</groupId>
<artifactId>jackson-databind-nullable</artifactId>
<version>${jackson-databind-nullable-version}</version>
</dependency>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>jsr311-api</artifactId>
<version>${jsr311-api-version}</version>
</dependency>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId>
<version>${javax.ws.rs-api-version}</version>
</dependency>
<!-- test dependencies -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit-version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-runner</artifactId>
<version>${junit-platform-runner.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>${mockito-core-version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<java.version>1.8</java.version>
<maven.compiler.source>${java.version}</maven.compiler.source>
<maven.compiler.target>${java.version}</maven.compiler.target>
<gson-fire-version>1.8.5</gson-fire-version>
<okhttp-version>4.10.0</okhttp-version>
<gson-version>2.9.1</gson-version>
<commons-lang3-version>3.12.0</commons-lang3-version>
<jackson-databind-nullable-version>0.2.6</jackson-databind-nullable-version>
<jakarta-annotation-version>1.3.5</jakarta-annotation-version>
<junit-version>5.9.1</junit-version>
<junit-platform-runner.version>1.9.1</junit-platform-runner.version>
<mockito-core-version>3.12.4</mockito-core-version>
<javax.ws.rs-api-version>2.1.1</javax.ws.rs-api-version>
<jsr311-api-version>1.1.1</jsr311-api-version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<spotless.version>2.27.2</spotless.version>
</properties>
</project>

View File

@ -0,0 +1 @@
rootProject.name = "petstore-okhttp-gson-31"

View File

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

View File

@ -0,0 +1,62 @@
/*
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.client;
import java.io.IOException;
import java.util.Map;
import java.util.List;
/**
* Callback for asynchronous API call.
*
* @param <T> The return type
*/
public interface ApiCallback<T> {
/**
* This is called when the API call fails.
*
* @param e The exception causing the failure
* @param statusCode Status code of the response if available, otherwise it would be 0
* @param responseHeaders Headers of the response if available, otherwise it would be null
*/
void onFailure(ApiException e, int statusCode, Map<String, List<String>> responseHeaders);
/**
* This is called when the API call succeeded.
*
* @param result The result deserialized from response
* @param statusCode Status code of the response
* @param responseHeaders Headers of the response
*/
void onSuccess(T result, int statusCode, Map<String, List<String>> responseHeaders);
/**
* This is called when the API upload processing.
*
* @param bytesWritten bytes Written
* @param contentLength content length of request body
* @param done write end
*/
void onUploadProgress(long bytesWritten, long contentLength, boolean done);
/**
* This is called when the API download processing.
*
* @param bytesRead bytes Read
* @param contentLength content length of the response
* @param done Read end
*/
void onDownloadProgress(long bytesRead, long contentLength, boolean done);
}

View File

@ -0,0 +1,165 @@
/*
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.client;
import java.util.Map;
import java.util.List;
/**
* <p>ApiException class.</p>
*/
@SuppressWarnings("serial")
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen")
public class ApiException extends Exception {
private int code = 0;
private Map<String, List<String>> responseHeaders = null;
private String responseBody = null;
/**
* <p>Constructor for ApiException.</p>
*/
public ApiException() {}
/**
* <p>Constructor for ApiException.</p>
*
* @param throwable a {@link java.lang.Throwable} object
*/
public ApiException(Throwable throwable) {
super(throwable);
}
/**
* <p>Constructor for ApiException.</p>
*
* @param message the error message
*/
public ApiException(String message) {
super(message);
}
/**
* <p>Constructor for ApiException.</p>
*
* @param message the error message
* @param throwable a {@link java.lang.Throwable} object
* @param code HTTP status code
* @param responseHeaders a {@link java.util.Map} of HTTP response headers
* @param responseBody the response body
*/
public ApiException(String message, Throwable throwable, int code, Map<String, List<String>> responseHeaders, String responseBody) {
super(message, throwable);
this.code = code;
this.responseHeaders = responseHeaders;
this.responseBody = responseBody;
}
/**
* <p>Constructor for ApiException.</p>
*
* @param message the error message
* @param code HTTP status code
* @param responseHeaders a {@link java.util.Map} of HTTP response headers
* @param responseBody the response body
*/
public ApiException(String message, int code, Map<String, List<String>> responseHeaders, String responseBody) {
this(message, (Throwable) null, code, responseHeaders, responseBody);
}
/**
* <p>Constructor for ApiException.</p>
*
* @param message the error message
* @param throwable a {@link java.lang.Throwable} object
* @param code HTTP status code
* @param responseHeaders a {@link java.util.Map} of HTTP response headers
*/
public ApiException(String message, Throwable throwable, int code, Map<String, List<String>> responseHeaders) {
this(message, throwable, code, responseHeaders, null);
}
/**
* <p>Constructor for ApiException.</p>
*
* @param code HTTP status code
* @param responseHeaders a {@link java.util.Map} of HTTP response headers
* @param responseBody the response body
*/
public ApiException(int code, Map<String, List<String>> responseHeaders, String responseBody) {
this("Response Code: " + code + " Response Body: " + responseBody, (Throwable) null, code, responseHeaders, responseBody);
}
/**
* <p>Constructor for ApiException.</p>
*
* @param code HTTP status code
* @param message a {@link java.lang.String} object
*/
public ApiException(int code, String message) {
super(message);
this.code = code;
}
/**
* <p>Constructor for ApiException.</p>
*
* @param code HTTP status code
* @param message the error message
* @param responseHeaders a {@link java.util.Map} of HTTP response headers
* @param responseBody the response body
*/
public ApiException(int code, String message, Map<String, List<String>> responseHeaders, String responseBody) {
this(code, message);
this.responseHeaders = responseHeaders;
this.responseBody = responseBody;
}
/**
* Get the HTTP status code.
*
* @return HTTP status code
*/
public int getCode() {
return code;
}
/**
* Get the HTTP response headers.
*
* @return A map of list of string
*/
public Map<String, List<String>> getResponseHeaders() {
return responseHeaders;
}
/**
* Get the HTTP response body.
*
* @return Response body in the form of string
*/
public String getResponseBody() {
return responseBody;
}
/**
* Get the exception message including HTTP response data.
*
* @return The exception message
*/
public String getMessage() {
return String.format("Message: %s%nHTTP response code: %s%nHTTP response body: %s%nHTTP response headers: %s",
super.getMessage(), this.getCode(), this.getResponseBody(), this.getResponseHeaders());
}
}

View File

@ -0,0 +1,76 @@
/*
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.client;
import java.util.List;
import java.util.Map;
/**
* API response returned by API call.
*/
public class ApiResponse<T> {
final private int statusCode;
final private Map<String, List<String>> headers;
final private T data;
/**
* <p>Constructor for ApiResponse.</p>
*
* @param statusCode The status code of HTTP response
* @param headers The headers of HTTP response
*/
public ApiResponse(int statusCode, Map<String, List<String>> headers) {
this(statusCode, headers, null);
}
/**
* <p>Constructor for ApiResponse.</p>
*
* @param statusCode The status code of HTTP response
* @param headers The headers of HTTP response
* @param data The object deserialized from response bod
*/
public ApiResponse(int statusCode, Map<String, List<String>> headers, T data) {
this.statusCode = statusCode;
this.headers = headers;
this.data = data;
}
/**
* <p>Get the <code>status code</code>.</p>
*
* @return the status code
*/
public int getStatusCode() {
return statusCode;
}
/**
* <p>Get the <code>headers</code>.</p>
*
* @return a {@link java.util.Map} of headers
*/
public Map<String, List<String>> getHeaders() {
return headers;
}
/**
* <p>Get the <code>data</code>.</p>
*
* @return the data
*/
public T getData() {
return data;
}
}

View File

@ -0,0 +1,41 @@
/*
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.client;
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen")
public class Configuration {
public static final String VERSION = "1.0.0";
private static ApiClient defaultApiClient = new ApiClient();
/**
* Get the default API client, which would be used when creating API
* instances without providing an API client.
*
* @return Default API client
*/
public static ApiClient getDefaultApiClient() {
return defaultApiClient;
}
/**
* Set the default API client, which would be used when creating API
* instances without providing an API client.
*
* @param apiClient API client
*/
public static void setDefaultApiClient(ApiClient apiClient) {
defaultApiClient = apiClient;
}
}

View File

@ -0,0 +1,85 @@
/*
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.client;
import okhttp3.*;
import okio.Buffer;
import okio.BufferedSink;
import okio.GzipSink;
import okio.Okio;
import java.io.IOException;
/**
* Encodes request bodies using gzip.
*
* Taken from https://github.com/square/okhttp/issues/350
*/
class GzipRequestInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Request originalRequest = chain.request();
if (originalRequest.body() == null || originalRequest.header("Content-Encoding") != null) {
return chain.proceed(originalRequest);
}
Request compressedRequest = originalRequest.newBuilder()
.header("Content-Encoding", "gzip")
.method(originalRequest.method(), forceContentLength(gzip(originalRequest.body())))
.build();
return chain.proceed(compressedRequest);
}
private RequestBody forceContentLength(final RequestBody requestBody) throws IOException {
final Buffer buffer = new Buffer();
requestBody.writeTo(buffer);
return new RequestBody() {
@Override
public MediaType contentType() {
return requestBody.contentType();
}
@Override
public long contentLength() {
return buffer.size();
}
@Override
public void writeTo(BufferedSink sink) throws IOException {
sink.write(buffer.snapshot());
}
};
}
private RequestBody gzip(final RequestBody body) {
return new RequestBody() {
@Override
public MediaType contentType() {
return body.contentType();
}
@Override
public long contentLength() {
return -1; // We don't know the compressed length in advance!
}
@Override
public void writeTo(BufferedSink sink) throws IOException {
BufferedSink gzipSink = Okio.buffer(new GzipSink(sink));
body.writeTo(gzipSink);
gzipSink.close();
}
};
}
}

View File

@ -0,0 +1,439 @@
/*
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.client;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapter;
import com.google.gson.internal.bind.util.ISO8601Utils;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import com.google.gson.JsonElement;
import io.gsonfire.GsonFireBuilder;
import io.gsonfire.TypeSelector;
import okio.ByteString;
import java.io.IOException;
import java.io.StringReader;
import java.lang.reflect.Type;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.ParsePosition;
import java.time.LocalDate;
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.Locale;
import java.util.Map;
import java.util.HashMap;
/*
* A JSON utility class
*
* NOTE: in the future, this class may be converted to static, which may break
* backward-compatibility
*/
public class JSON {
private static Gson gson;
private static boolean isLenientOnJson = false;
private static DateTypeAdapter dateTypeAdapter = new DateTypeAdapter();
private static SqlDateTypeAdapter sqlDateTypeAdapter = new SqlDateTypeAdapter();
private static OffsetDateTimeTypeAdapter offsetDateTimeTypeAdapter = new OffsetDateTimeTypeAdapter();
private static LocalDateTypeAdapter localDateTypeAdapter = new LocalDateTypeAdapter();
private static ByteArrayAdapter byteArrayAdapter = new ByteArrayAdapter();
@SuppressWarnings("unchecked")
public static GsonBuilder createGson() {
GsonFireBuilder fireBuilder = new GsonFireBuilder()
.registerTypeSelector(org.openapitools.client.model.Animal.class, new TypeSelector<org.openapitools.client.model.Animal>() {
@Override
public Class<? extends org.openapitools.client.model.Animal> getClassForElement(JsonElement readElement) {
Map<String, Class> classByDiscriminatorValue = new HashMap<String, Class>();
classByDiscriminatorValue.put("Cat", org.openapitools.client.model.Cat.class);
classByDiscriminatorValue.put("Dog", org.openapitools.client.model.Dog.class);
classByDiscriminatorValue.put("Animal", org.openapitools.client.model.Animal.class);
return getClassByDiscriminator(classByDiscriminatorValue,
getDiscriminatorValue(readElement, "className"));
}
})
.registerTypeSelector(org.openapitools.client.model.Cat.class, new TypeSelector<org.openapitools.client.model.Cat>() {
@Override
public Class<? extends org.openapitools.client.model.Cat> getClassForElement(JsonElement readElement) {
Map<String, Class> classByDiscriminatorValue = new HashMap<String, Class>();
classByDiscriminatorValue.put("Cat", org.openapitools.client.model.Cat.class);
return getClassByDiscriminator(classByDiscriminatorValue,
getDiscriminatorValue(readElement, "className"));
}
})
.registerTypeSelector(org.openapitools.client.model.Dog.class, new TypeSelector<org.openapitools.client.model.Dog>() {
@Override
public Class<? extends org.openapitools.client.model.Dog> getClassForElement(JsonElement readElement) {
Map<String, Class> classByDiscriminatorValue = new HashMap<String, Class>();
classByDiscriminatorValue.put("Dog", org.openapitools.client.model.Dog.class);
return getClassByDiscriminator(classByDiscriminatorValue,
getDiscriminatorValue(readElement, "className"));
}
})
;
GsonBuilder builder = fireBuilder.createGsonBuilder();
return builder;
}
private static String getDiscriminatorValue(JsonElement readElement, String discriminatorField) {
JsonElement element = readElement.getAsJsonObject().get(discriminatorField);
if (null == element) {
throw new IllegalArgumentException("missing discriminator field: <" + discriminatorField + ">");
}
return element.getAsString();
}
/**
* Returns the Java class that implements the OpenAPI schema for the specified discriminator value.
*
* @param classByDiscriminatorValue The map of discriminator values to Java classes.
* @param discriminatorValue The value of the OpenAPI discriminator in the input data.
* @return The Java class that implements the OpenAPI schema
*/
private static Class getClassByDiscriminator(Map classByDiscriminatorValue, String discriminatorValue) {
Class clazz = (Class) classByDiscriminatorValue.get(discriminatorValue);
if (null == clazz) {
throw new IllegalArgumentException("cannot determine model class of name: <" + discriminatorValue + ">");
}
return clazz;
}
{
GsonBuilder gsonBuilder = createGson();
gsonBuilder.registerTypeAdapter(Date.class, dateTypeAdapter);
gsonBuilder.registerTypeAdapter(java.sql.Date.class, sqlDateTypeAdapter);
gsonBuilder.registerTypeAdapter(OffsetDateTime.class, offsetDateTimeTypeAdapter);
gsonBuilder.registerTypeAdapter(LocalDate.class, localDateTypeAdapter);
gsonBuilder.registerTypeAdapter(byte[].class, byteArrayAdapter);
gsonBuilder.registerTypeAdapterFactory(new org.openapitools.client.model.Cat.CustomTypeAdapterFactory());
gsonBuilder.registerTypeAdapterFactory(new org.openapitools.client.model.Category.CustomTypeAdapterFactory());
gsonBuilder.registerTypeAdapterFactory(new org.openapitools.client.model.Dog.CustomTypeAdapterFactory());
gsonBuilder.registerTypeAdapterFactory(new org.openapitools.client.model.ModelApiResponse.CustomTypeAdapterFactory());
gsonBuilder.registerTypeAdapterFactory(new org.openapitools.client.model.OneOfStringOrInt.CustomTypeAdapterFactory());
gsonBuilder.registerTypeAdapterFactory(new org.openapitools.client.model.Order.CustomTypeAdapterFactory());
gsonBuilder.registerTypeAdapterFactory(new org.openapitools.client.model.Pet.CustomTypeAdapterFactory());
gsonBuilder.registerTypeAdapterFactory(new org.openapitools.client.model.StringOrInt.CustomTypeAdapterFactory());
gsonBuilder.registerTypeAdapterFactory(new org.openapitools.client.model.Tag.CustomTypeAdapterFactory());
gsonBuilder.registerTypeAdapterFactory(new org.openapitools.client.model.User.CustomTypeAdapterFactory());
gson = gsonBuilder.create();
}
/**
* Get Gson.
*
* @return Gson
*/
public static Gson getGson() {
return gson;
}
/**
* Set Gson.
*
* @param gson Gson
*/
public static void setGson(Gson gson) {
JSON.gson = gson;
}
public static void setLenientOnJson(boolean lenientOnJson) {
isLenientOnJson = lenientOnJson;
}
/**
* Serialize the given Java object into JSON string.
*
* @param obj Object
* @return String representation of the JSON
*/
public static String serialize(Object obj) {
return gson.toJson(obj);
}
/**
* Deserialize the given JSON string to Java object.
*
* @param <T> Type
* @param body The JSON string
* @param returnType The type to deserialize into
* @return The deserialized Java object
*/
@SuppressWarnings("unchecked")
public static <T> T deserialize(String body, Type returnType) {
try {
if (isLenientOnJson) {
JsonReader jsonReader = new JsonReader(new StringReader(body));
// see https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/stream/JsonReader.html#setLenient(boolean)
jsonReader.setLenient(true);
return gson.fromJson(jsonReader, returnType);
} else {
return gson.fromJson(body, returnType);
}
} catch (JsonParseException e) {
// Fallback processing when failed to parse JSON form response body:
// return the response body string directly for the String return type;
if (returnType.equals(String.class)) {
return (T) body;
} else {
throw (e);
}
}
}
/**
* Gson TypeAdapter for Byte Array type
*/
public static class ByteArrayAdapter extends TypeAdapter<byte[]> {
@Override
public void write(JsonWriter out, byte[] value) throws IOException {
if (value == null) {
out.nullValue();
} else {
out.value(ByteString.of(value).base64());
}
}
@Override
public byte[] read(JsonReader in) throws IOException {
switch (in.peek()) {
case NULL:
in.nextNull();
return null;
default:
String bytesAsBase64 = in.nextString();
ByteString byteString = ByteString.decodeBase64(bytesAsBase64);
return byteString.toByteArray();
}
}
}
/**
* Gson TypeAdapter for JSR310 OffsetDateTime type
*/
public static class OffsetDateTimeTypeAdapter extends TypeAdapter<OffsetDateTime> {
private DateTimeFormatter formatter;
public OffsetDateTimeTypeAdapter() {
this(DateTimeFormatter.ISO_OFFSET_DATE_TIME);
}
public OffsetDateTimeTypeAdapter(DateTimeFormatter formatter) {
this.formatter = formatter;
}
public void setFormat(DateTimeFormatter dateFormat) {
this.formatter = dateFormat;
}
@Override
public void write(JsonWriter out, OffsetDateTime date) throws IOException {
if (date == null) {
out.nullValue();
} else {
out.value(formatter.format(date));
}
}
@Override
public OffsetDateTime read(JsonReader in) throws IOException {
switch (in.peek()) {
case NULL:
in.nextNull();
return null;
default:
String date = in.nextString();
if (date.endsWith("+0000")) {
date = date.substring(0, date.length()-5) + "Z";
}
return OffsetDateTime.parse(date, formatter);
}
}
}
/**
* Gson TypeAdapter for JSR310 LocalDate type
*/
public static class LocalDateTypeAdapter extends TypeAdapter<LocalDate> {
private DateTimeFormatter formatter;
public LocalDateTypeAdapter() {
this(DateTimeFormatter.ISO_LOCAL_DATE);
}
public LocalDateTypeAdapter(DateTimeFormatter formatter) {
this.formatter = formatter;
}
public void setFormat(DateTimeFormatter dateFormat) {
this.formatter = dateFormat;
}
@Override
public void write(JsonWriter out, LocalDate date) throws IOException {
if (date == null) {
out.nullValue();
} else {
out.value(formatter.format(date));
}
}
@Override
public LocalDate read(JsonReader in) throws IOException {
switch (in.peek()) {
case NULL:
in.nextNull();
return null;
default:
String date = in.nextString();
return LocalDate.parse(date, formatter);
}
}
}
public static void setOffsetDateTimeFormat(DateTimeFormatter dateFormat) {
offsetDateTimeTypeAdapter.setFormat(dateFormat);
}
public static void setLocalDateFormat(DateTimeFormatter dateFormat) {
localDateTypeAdapter.setFormat(dateFormat);
}
/**
* Gson TypeAdapter for java.sql.Date type
* If the dateFormat is null, a simple "yyyy-MM-dd" format will be used
* (more efficient than SimpleDateFormat).
*/
public static class SqlDateTypeAdapter extends TypeAdapter<java.sql.Date> {
private DateFormat dateFormat;
public SqlDateTypeAdapter() {}
public SqlDateTypeAdapter(DateFormat dateFormat) {
this.dateFormat = dateFormat;
}
public void setFormat(DateFormat dateFormat) {
this.dateFormat = dateFormat;
}
@Override
public void write(JsonWriter out, java.sql.Date date) throws IOException {
if (date == null) {
out.nullValue();
} else {
String value;
if (dateFormat != null) {
value = dateFormat.format(date);
} else {
value = date.toString();
}
out.value(value);
}
}
@Override
public java.sql.Date read(JsonReader in) throws IOException {
switch (in.peek()) {
case NULL:
in.nextNull();
return null;
default:
String date = in.nextString();
try {
if (dateFormat != null) {
return new java.sql.Date(dateFormat.parse(date).getTime());
}
return new java.sql.Date(ISO8601Utils.parse(date, new ParsePosition(0)).getTime());
} catch (ParseException e) {
throw new JsonParseException(e);
}
}
}
}
/**
* Gson TypeAdapter for java.util.Date type
* If the dateFormat is null, ISO8601Utils will be used.
*/
public static class DateTypeAdapter extends TypeAdapter<Date> {
private DateFormat dateFormat;
public DateTypeAdapter() {}
public DateTypeAdapter(DateFormat dateFormat) {
this.dateFormat = dateFormat;
}
public void setFormat(DateFormat dateFormat) {
this.dateFormat = dateFormat;
}
@Override
public void write(JsonWriter out, Date date) throws IOException {
if (date == null) {
out.nullValue();
} else {
String value;
if (dateFormat != null) {
value = dateFormat.format(date);
} else {
value = ISO8601Utils.format(date, true);
}
out.value(value);
}
}
@Override
public Date read(JsonReader in) throws IOException {
try {
switch (in.peek()) {
case NULL:
in.nextNull();
return null;
default:
String date = in.nextString();
try {
if (dateFormat != null) {
return dateFormat.parse(date);
}
return ISO8601Utils.parse(date, new ParsePosition(0));
} catch (ParseException e) {
throw new JsonParseException(e);
}
}
} catch (IllegalArgumentException e) {
throw new JsonParseException(e);
}
}
}
public static void setDateFormat(DateFormat dateFormat) {
dateTypeAdapter.setFormat(dateFormat);
}
public static void setSqlDateFormat(DateFormat dateFormat) {
sqlDateTypeAdapter.setFormat(dateFormat);
}
}

View File

@ -0,0 +1,57 @@
/*
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.client;
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen")
public class Pair {
private String name = "";
private String value = "";
public Pair (String name, String value) {
setName(name);
setValue(value);
}
private void setName(String name) {
if (!isValidString(name)) {
return;
}
this.name = name;
}
private void setValue(String value) {
if (!isValidString(value)) {
return;
}
this.value = value;
}
public String getName() {
return this.name;
}
public String getValue() {
return this.value;
}
private boolean isValidString(String arg) {
if (arg == null) {
return false;
}
return true;
}
}

View File

@ -0,0 +1,73 @@
/*
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.client;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import java.io.IOException;
import okio.Buffer;
import okio.BufferedSink;
import okio.ForwardingSink;
import okio.Okio;
import okio.Sink;
public class ProgressRequestBody extends RequestBody {
private final RequestBody requestBody;
private final ApiCallback callback;
public ProgressRequestBody(RequestBody requestBody, ApiCallback callback) {
this.requestBody = requestBody;
this.callback = callback;
}
@Override
public MediaType contentType() {
return requestBody.contentType();
}
@Override
public long contentLength() throws IOException {
return requestBody.contentLength();
}
@Override
public void writeTo(BufferedSink sink) throws IOException {
BufferedSink bufferedSink = Okio.buffer(sink(sink));
requestBody.writeTo(bufferedSink);
bufferedSink.flush();
}
private Sink sink(Sink sink) {
return new ForwardingSink(sink) {
long bytesWritten = 0L;
long contentLength = 0L;
@Override
public void write(Buffer source, long byteCount) throws IOException {
super.write(source, byteCount);
if (contentLength == 0) {
contentLength = contentLength();
}
bytesWritten += byteCount;
callback.onUploadProgress(bytesWritten, contentLength, bytesWritten == contentLength);
}
};
}
}

View File

@ -0,0 +1,70 @@
/*
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.client;
import okhttp3.MediaType;
import okhttp3.ResponseBody;
import java.io.IOException;
import okio.Buffer;
import okio.BufferedSource;
import okio.ForwardingSource;
import okio.Okio;
import okio.Source;
public class ProgressResponseBody extends ResponseBody {
private final ResponseBody responseBody;
private final ApiCallback callback;
private BufferedSource bufferedSource;
public ProgressResponseBody(ResponseBody responseBody, ApiCallback callback) {
this.responseBody = responseBody;
this.callback = callback;
}
@Override
public MediaType contentType() {
return responseBody.contentType();
}
@Override
public long contentLength() {
return responseBody.contentLength();
}
@Override
public BufferedSource source() {
if (bufferedSource == null) {
bufferedSource = Okio.buffer(source(responseBody.source()));
}
return bufferedSource;
}
private Source source(Source source) {
return new ForwardingSource(source) {
long totalBytesRead = 0L;
@Override
public long read(Buffer sink, long byteCount) throws IOException {
long bytesRead = super.read(sink, byteCount);
// read() returns the number of bytes read, or -1 if this source is exhausted.
totalBytesRead += bytesRead != -1 ? bytesRead : 0;
callback.onDownloadProgress(totalBytesRead, responseBody.contentLength(), bytesRead == -1);
return bytesRead;
}
};
}
}

View File

@ -0,0 +1,58 @@
package org.openapitools.client;
import java.util.Map;
/**
* Representing a Server configuration.
*/
public class ServerConfiguration {
public String URL;
public String description;
public Map<String, ServerVariable> variables;
/**
* @param URL A URL to the target host.
* @param description A description of the host designated by the URL.
* @param variables A map between a variable name and its value. The value is used for substitution in the server's URL template.
*/
public ServerConfiguration(String URL, String description, Map<String, ServerVariable> variables) {
this.URL = URL;
this.description = description;
this.variables = variables;
}
/**
* Format URL template using given variables.
*
* @param variables A map between a variable name and its value.
* @return Formatted URL.
*/
public String URL(Map<String, String> variables) {
String url = this.URL;
// go through variables and replace placeholders
for (Map.Entry<String, ServerVariable> variable: this.variables.entrySet()) {
String name = variable.getKey();
ServerVariable serverVariable = variable.getValue();
String value = serverVariable.defaultValue;
if (variables != null && variables.containsKey(name)) {
value = variables.get(name);
if (serverVariable.enumValues.size() > 0 && !serverVariable.enumValues.contains(value)) {
throw new IllegalArgumentException("The variable " + name + " in the server URL has invalid value " + value + ".");
}
}
url = url.replace("{" + name + "}", value);
}
return url;
}
/**
* Format URL template using default server variables.
*
* @return Formatted URL.
*/
public String URL() {
return URL(null);
}
}

View File

@ -0,0 +1,23 @@
package org.openapitools.client;
import java.util.HashSet;
/**
* Representing a Server Variable for server URL template substitution.
*/
public class ServerVariable {
public String description;
public String defaultValue;
public HashSet<String> enumValues = null;
/**
* @param description A description for the server variable.
* @param defaultValue The default value to use for substitution.
* @param enumValues An enumeration of string values to be used if the substitution options are from a limited set.
*/
public ServerVariable(String description, String defaultValue, HashSet<String> enumValues) {
this.description = description;
this.defaultValue = defaultValue;
this.enumValues = enumValues;
}
}

View File

@ -0,0 +1,83 @@
/*
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.client;
import java.util.Collection;
import java.util.Iterator;
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen")
public class StringUtil {
/**
* Check if the given array contains the given value (with case-insensitive comparison).
*
* @param array The array
* @param value The value to search
* @return true if the array contains the value
*/
public static boolean containsIgnoreCase(String[] array, String value) {
for (String str : array) {
if (value == null && str == null) {
return true;
}
if (value != null && value.equalsIgnoreCase(str)) {
return true;
}
}
return false;
}
/**
* Join an array of strings with the given separator.
* <p>
* Note: This might be replaced by utility method from commons-lang or guava someday
* if one of those libraries is added as dependency.
* </p>
*
* @param array The array of strings
* @param separator The separator
* @return the resulting string
*/
public static String join(String[] array, String separator) {
int len = array.length;
if (len == 0) {
return "";
}
StringBuilder out = new StringBuilder();
out.append(array[0]);
for (int i = 1; i < len; i++) {
out.append(separator).append(array[i]);
}
return out.toString();
}
/**
* Join a list of strings with the given separator.
*
* @param list The list of strings
* @param separator The separator
* @return the resulting string
*/
public static String join(Collection<String> list, String separator) {
Iterator<String> iterator = list.iterator();
StringBuilder out = new StringBuilder();
if (iterator.hasNext()) {
out.append(iterator.next());
}
while (iterator.hasNext()) {
out.append(separator).append(iterator.next());
}
return out.toString();
}
}

View File

@ -0,0 +1,570 @@
/*
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.client.api;
import org.openapitools.client.ApiCallback;
import org.openapitools.client.ApiClient;
import org.openapitools.client.ApiException;
import org.openapitools.client.ApiResponse;
import org.openapitools.client.Configuration;
import org.openapitools.client.Pair;
import org.openapitools.client.ProgressRequestBody;
import org.openapitools.client.ProgressResponseBody;
import com.google.gson.reflect.TypeToken;
import java.io.IOException;
import org.openapitools.client.model.Order;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class StoreApi {
private ApiClient localVarApiClient;
private int localHostIndex;
private String localCustomBaseUrl;
public StoreApi() {
this(Configuration.getDefaultApiClient());
}
public StoreApi(ApiClient apiClient) {
this.localVarApiClient = apiClient;
}
public ApiClient getApiClient() {
return localVarApiClient;
}
public void setApiClient(ApiClient apiClient) {
this.localVarApiClient = apiClient;
}
public int getHostIndex() {
return localHostIndex;
}
public void setHostIndex(int hostIndex) {
this.localHostIndex = hostIndex;
}
public String getCustomBaseUrl() {
return localCustomBaseUrl;
}
public void setCustomBaseUrl(String customBaseUrl) {
this.localCustomBaseUrl = customBaseUrl;
}
/**
* Build call for deleteOrder
* @param orderId ID of the order that needs to be deleted (required)
* @param _callback Callback for upload/download progress
* @return Call to execute
* @throws ApiException If fail to serialize the request body object
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 400 </td><td> Invalid ID supplied </td><td> - </td></tr>
<tr><td> 404 </td><td> Order not found </td><td> - </td></tr>
</table>
*/
public okhttp3.Call deleteOrderCall(String orderId, final ApiCallback _callback) throws ApiException {
String basePath = null;
// Operation Servers
String[] localBasePaths = new String[] { };
// Determine Base Path to Use
if (localCustomBaseUrl != null){
basePath = localCustomBaseUrl;
} else if ( localBasePaths.length > 0 ) {
basePath = localBasePaths[localHostIndex];
} else {
basePath = null;
}
Object localVarPostBody = null;
// create path and map variables
String localVarPath = "/store/order/{orderId}"
.replace("{" + "orderId" + "}", localVarApiClient.escapeString(orderId.toString()));
List<Pair> localVarQueryParams = new ArrayList<Pair>();
List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, String> localVarCookieParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = {
};
final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts);
if (localVarAccept != null) {
localVarHeaderParams.put("Accept", localVarAccept);
}
final String[] localVarContentTypes = {
};
final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes);
if (localVarContentType != null) {
localVarHeaderParams.put("Content-Type", localVarContentType);
}
String[] localVarAuthNames = new String[] { };
return localVarApiClient.buildCall(basePath, localVarPath, "DELETE", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback);
}
@SuppressWarnings("rawtypes")
private okhttp3.Call deleteOrderValidateBeforeCall(String orderId, final ApiCallback _callback) throws ApiException {
// verify the required parameter 'orderId' is set
if (orderId == null) {
throw new ApiException("Missing the required parameter 'orderId' when calling deleteOrder(Async)");
}
return deleteOrderCall(orderId, _callback);
}
/**
* Delete purchase order by ID
* For valid response try integer IDs with value &lt; 1000. Anything above 1000 or nonintegers will generate API errors
* @param orderId ID of the order that needs to be deleted (required)
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 400 </td><td> Invalid ID supplied </td><td> - </td></tr>
<tr><td> 404 </td><td> Order not found </td><td> - </td></tr>
</table>
*/
public void deleteOrder(String orderId) throws ApiException {
deleteOrderWithHttpInfo(orderId);
}
/**
* Delete purchase order by ID
* For valid response try integer IDs with value &lt; 1000. Anything above 1000 or nonintegers will generate API errors
* @param orderId ID of the order that needs to be deleted (required)
* @return ApiResponse&lt;Void&gt;
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 400 </td><td> Invalid ID supplied </td><td> - </td></tr>
<tr><td> 404 </td><td> Order not found </td><td> - </td></tr>
</table>
*/
public ApiResponse<Void> deleteOrderWithHttpInfo(String orderId) throws ApiException {
okhttp3.Call localVarCall = deleteOrderValidateBeforeCall(orderId, null);
return localVarApiClient.execute(localVarCall);
}
/**
* Delete purchase order by ID (asynchronously)
* For valid response try integer IDs with value &lt; 1000. Anything above 1000 or nonintegers will generate API errors
* @param orderId ID of the order that needs to be deleted (required)
* @param _callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 400 </td><td> Invalid ID supplied </td><td> - </td></tr>
<tr><td> 404 </td><td> Order not found </td><td> - </td></tr>
</table>
*/
public okhttp3.Call deleteOrderAsync(String orderId, final ApiCallback<Void> _callback) throws ApiException {
okhttp3.Call localVarCall = deleteOrderValidateBeforeCall(orderId, _callback);
localVarApiClient.executeAsync(localVarCall, _callback);
return localVarCall;
}
/**
* Build call for getInventory
* @param _callback Callback for upload/download progress
* @return Call to execute
* @throws ApiException If fail to serialize the request body object
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> successful operation </td><td> - </td></tr>
</table>
*/
public okhttp3.Call getInventoryCall(final ApiCallback _callback) throws ApiException {
String basePath = null;
// Operation Servers
String[] localBasePaths = new String[] { };
// Determine Base Path to Use
if (localCustomBaseUrl != null){
basePath = localCustomBaseUrl;
} else if ( localBasePaths.length > 0 ) {
basePath = localBasePaths[localHostIndex];
} else {
basePath = null;
}
Object localVarPostBody = null;
// create path and map variables
String localVarPath = "/store/inventory";
List<Pair> localVarQueryParams = new ArrayList<Pair>();
List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, String> localVarCookieParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = {
"application/json"
};
final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts);
if (localVarAccept != null) {
localVarHeaderParams.put("Accept", localVarAccept);
}
final String[] localVarContentTypes = {
};
final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes);
if (localVarContentType != null) {
localVarHeaderParams.put("Content-Type", localVarContentType);
}
String[] localVarAuthNames = new String[] { "api_key" };
return localVarApiClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback);
}
@SuppressWarnings("rawtypes")
private okhttp3.Call getInventoryValidateBeforeCall(final ApiCallback _callback) throws ApiException {
return getInventoryCall(_callback);
}
/**
* Returns pet inventories by status
* Returns a map of status codes to quantities
* @return Map&lt;String, Integer&gt;
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> successful operation </td><td> - </td></tr>
</table>
*/
public Map<String, Integer> getInventory() throws ApiException {
ApiResponse<Map<String, Integer>> localVarResp = getInventoryWithHttpInfo();
return localVarResp.getData();
}
/**
* Returns pet inventories by status
* Returns a map of status codes to quantities
* @return ApiResponse&lt;Map&lt;String, Integer&gt;&gt;
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> successful operation </td><td> - </td></tr>
</table>
*/
public ApiResponse<Map<String, Integer>> getInventoryWithHttpInfo() throws ApiException {
okhttp3.Call localVarCall = getInventoryValidateBeforeCall(null);
Type localVarReturnType = new TypeToken<Map<String, Integer>>(){}.getType();
return localVarApiClient.execute(localVarCall, localVarReturnType);
}
/**
* Returns pet inventories by status (asynchronously)
* Returns a map of status codes to quantities
* @param _callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> successful operation </td><td> - </td></tr>
</table>
*/
public okhttp3.Call getInventoryAsync(final ApiCallback<Map<String, Integer>> _callback) throws ApiException {
okhttp3.Call localVarCall = getInventoryValidateBeforeCall(_callback);
Type localVarReturnType = new TypeToken<Map<String, Integer>>(){}.getType();
localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback);
return localVarCall;
}
/**
* Build call for getOrderById
* @param orderId ID of pet that needs to be fetched (required)
* @param _callback Callback for upload/download progress
* @return Call to execute
* @throws ApiException If fail to serialize the request body object
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> successful operation </td><td> - </td></tr>
<tr><td> 400 </td><td> Invalid ID supplied </td><td> - </td></tr>
<tr><td> 404 </td><td> Order not found </td><td> - </td></tr>
</table>
*/
public okhttp3.Call getOrderByIdCall(Long orderId, final ApiCallback _callback) throws ApiException {
String basePath = null;
// Operation Servers
String[] localBasePaths = new String[] { };
// Determine Base Path to Use
if (localCustomBaseUrl != null){
basePath = localCustomBaseUrl;
} else if ( localBasePaths.length > 0 ) {
basePath = localBasePaths[localHostIndex];
} else {
basePath = null;
}
Object localVarPostBody = null;
// create path and map variables
String localVarPath = "/store/order/{orderId}"
.replace("{" + "orderId" + "}", localVarApiClient.escapeString(orderId.toString()));
List<Pair> localVarQueryParams = new ArrayList<Pair>();
List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, String> localVarCookieParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = {
"application/xml",
"application/json"
};
final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts);
if (localVarAccept != null) {
localVarHeaderParams.put("Accept", localVarAccept);
}
final String[] localVarContentTypes = {
};
final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes);
if (localVarContentType != null) {
localVarHeaderParams.put("Content-Type", localVarContentType);
}
String[] localVarAuthNames = new String[] { };
return localVarApiClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback);
}
@SuppressWarnings("rawtypes")
private okhttp3.Call getOrderByIdValidateBeforeCall(Long orderId, final ApiCallback _callback) throws ApiException {
// verify the required parameter 'orderId' is set
if (orderId == null) {
throw new ApiException("Missing the required parameter 'orderId' when calling getOrderById(Async)");
}
return getOrderByIdCall(orderId, _callback);
}
/**
* Find purchase order by ID
* For valid response try integer IDs with value &lt;&#x3D; 5 or &gt; 10. Other values will generate exceptions
* @param orderId ID of pet that needs to be fetched (required)
* @return Order
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> successful operation </td><td> - </td></tr>
<tr><td> 400 </td><td> Invalid ID supplied </td><td> - </td></tr>
<tr><td> 404 </td><td> Order not found </td><td> - </td></tr>
</table>
*/
public Order getOrderById(Long orderId) throws ApiException {
ApiResponse<Order> localVarResp = getOrderByIdWithHttpInfo(orderId);
return localVarResp.getData();
}
/**
* Find purchase order by ID
* For valid response try integer IDs with value &lt;&#x3D; 5 or &gt; 10. Other values will generate exceptions
* @param orderId ID of pet that needs to be fetched (required)
* @return ApiResponse&lt;Order&gt;
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> successful operation </td><td> - </td></tr>
<tr><td> 400 </td><td> Invalid ID supplied </td><td> - </td></tr>
<tr><td> 404 </td><td> Order not found </td><td> - </td></tr>
</table>
*/
public ApiResponse<Order> getOrderByIdWithHttpInfo(Long orderId) throws ApiException {
okhttp3.Call localVarCall = getOrderByIdValidateBeforeCall(orderId, null);
Type localVarReturnType = new TypeToken<Order>(){}.getType();
return localVarApiClient.execute(localVarCall, localVarReturnType);
}
/**
* Find purchase order by ID (asynchronously)
* For valid response try integer IDs with value &lt;&#x3D; 5 or &gt; 10. Other values will generate exceptions
* @param orderId ID of pet that needs to be fetched (required)
* @param _callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> successful operation </td><td> - </td></tr>
<tr><td> 400 </td><td> Invalid ID supplied </td><td> - </td></tr>
<tr><td> 404 </td><td> Order not found </td><td> - </td></tr>
</table>
*/
public okhttp3.Call getOrderByIdAsync(Long orderId, final ApiCallback<Order> _callback) throws ApiException {
okhttp3.Call localVarCall = getOrderByIdValidateBeforeCall(orderId, _callback);
Type localVarReturnType = new TypeToken<Order>(){}.getType();
localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback);
return localVarCall;
}
/**
* Build call for placeOrder
* @param order order placed for purchasing the pet (required)
* @param _callback Callback for upload/download progress
* @return Call to execute
* @throws ApiException If fail to serialize the request body object
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> successful operation </td><td> - </td></tr>
<tr><td> 400 </td><td> Invalid Order </td><td> - </td></tr>
</table>
*/
public okhttp3.Call placeOrderCall(Order order, final ApiCallback _callback) throws ApiException {
String basePath = null;
// Operation Servers
String[] localBasePaths = new String[] { };
// Determine Base Path to Use
if (localCustomBaseUrl != null){
basePath = localCustomBaseUrl;
} else if ( localBasePaths.length > 0 ) {
basePath = localBasePaths[localHostIndex];
} else {
basePath = null;
}
Object localVarPostBody = order;
// create path and map variables
String localVarPath = "/store/order";
List<Pair> localVarQueryParams = new ArrayList<Pair>();
List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, String> localVarCookieParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = {
"application/xml",
"application/json"
};
final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts);
if (localVarAccept != null) {
localVarHeaderParams.put("Accept", localVarAccept);
}
final String[] localVarContentTypes = {
"application/json"
};
final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes);
if (localVarContentType != null) {
localVarHeaderParams.put("Content-Type", localVarContentType);
}
String[] localVarAuthNames = new String[] { };
return localVarApiClient.buildCall(basePath, localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback);
}
@SuppressWarnings("rawtypes")
private okhttp3.Call placeOrderValidateBeforeCall(Order order, final ApiCallback _callback) throws ApiException {
// verify the required parameter 'order' is set
if (order == null) {
throw new ApiException("Missing the required parameter 'order' when calling placeOrder(Async)");
}
return placeOrderCall(order, _callback);
}
/**
* Place an order for a pet
*
* @param order order placed for purchasing the pet (required)
* @return Order
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> successful operation </td><td> - </td></tr>
<tr><td> 400 </td><td> Invalid Order </td><td> - </td></tr>
</table>
*/
public Order placeOrder(Order order) throws ApiException {
ApiResponse<Order> localVarResp = placeOrderWithHttpInfo(order);
return localVarResp.getData();
}
/**
* Place an order for a pet
*
* @param order order placed for purchasing the pet (required)
* @return ApiResponse&lt;Order&gt;
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> successful operation </td><td> - </td></tr>
<tr><td> 400 </td><td> Invalid Order </td><td> - </td></tr>
</table>
*/
public ApiResponse<Order> placeOrderWithHttpInfo(Order order) throws ApiException {
okhttp3.Call localVarCall = placeOrderValidateBeforeCall(order, null);
Type localVarReturnType = new TypeToken<Order>(){}.getType();
return localVarApiClient.execute(localVarCall, localVarReturnType);
}
/**
* Place an order for a pet (asynchronously)
*
* @param order order placed for purchasing the pet (required)
* @param _callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> successful operation </td><td> - </td></tr>
<tr><td> 400 </td><td> Invalid Order </td><td> - </td></tr>
</table>
*/
public okhttp3.Call placeOrderAsync(Order order, final ApiCallback<Order> _callback) throws ApiException {
okhttp3.Call localVarCall = placeOrderValidateBeforeCall(order, _callback);
Type localVarReturnType = new TypeToken<Order>(){}.getType();
localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback);
return localVarCall;
}
}

View File

@ -0,0 +1,80 @@
/*
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.client.auth;
import org.openapitools.client.ApiException;
import org.openapitools.client.Pair;
import java.net.URI;
import java.util.Map;
import java.util.List;
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen")
public class ApiKeyAuth implements Authentication {
private final String location;
private final String paramName;
private String apiKey;
private String apiKeyPrefix;
public ApiKeyAuth(String location, String paramName) {
this.location = location;
this.paramName = paramName;
}
public String getLocation() {
return location;
}
public String getParamName() {
return paramName;
}
public String getApiKey() {
return apiKey;
}
public void setApiKey(String apiKey) {
this.apiKey = apiKey;
}
public String getApiKeyPrefix() {
return apiKeyPrefix;
}
public void setApiKeyPrefix(String apiKeyPrefix) {
this.apiKeyPrefix = apiKeyPrefix;
}
@Override
public void applyToParams(List<Pair> queryParams, Map<String, String> headerParams, Map<String, String> cookieParams,
String payload, String method, URI uri) throws ApiException {
if (apiKey == null) {
return;
}
String value;
if (apiKeyPrefix != null) {
value = apiKeyPrefix + " " + apiKey;
} else {
value = apiKey;
}
if ("query".equals(location)) {
queryParams.add(new Pair(paramName, value));
} else if ("header".equals(location)) {
headerParams.put(paramName, value);
} else if ("cookie".equals(location)) {
cookieParams.put(paramName, value);
}
}
}

View File

@ -0,0 +1,36 @@
/*
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.client.auth;
import org.openapitools.client.Pair;
import org.openapitools.client.ApiException;
import java.net.URI;
import java.util.Map;
import java.util.List;
public interface Authentication {
/**
* Apply authentication settings to header and query params.
*
* @param queryParams List of query parameters
* @param headerParams Map of header parameters
* @param cookieParams Map of cookie parameters
* @param payload HTTP request body
* @param method HTTP method
* @param uri URI
* @throws ApiException if failed to update the parameters
*/
void applyToParams(List<Pair> queryParams, Map<String, String> headerParams, Map<String, String> cookieParams, String payload, String method, URI uri) throws ApiException;
}

View File

@ -0,0 +1,57 @@
/*
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.client.auth;
import org.openapitools.client.Pair;
import org.openapitools.client.ApiException;
import okhttp3.Credentials;
import java.net.URI;
import java.util.Map;
import java.util.List;
import java.io.UnsupportedEncodingException;
public class HttpBasicAuth implements Authentication {
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public void applyToParams(List<Pair> queryParams, Map<String, String> headerParams, Map<String, String> cookieParams,
String payload, String method, URI uri) throws ApiException {
if (username == null && password == null) {
return;
}
headerParams.put("Authorization", Credentials.basic(
username == null ? "" : username,
password == null ? "" : password));
}
}

View File

@ -0,0 +1,63 @@
/*
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.client.auth;
import org.openapitools.client.ApiException;
import org.openapitools.client.Pair;
import java.net.URI;
import java.util.Map;
import java.util.List;
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen")
public class HttpBearerAuth implements Authentication {
private final String scheme;
private String bearerToken;
public HttpBearerAuth(String scheme) {
this.scheme = scheme;
}
/**
* Gets the token, which together with the scheme, will be sent as the value of the Authorization header.
*
* @return The bearer token
*/
public String getBearerToken() {
return bearerToken;
}
/**
* Sets the token, which together with the scheme, will be sent as the value of the Authorization header.
*
* @param bearerToken The bearer token to send in the Authorization header
*/
public void setBearerToken(String bearerToken) {
this.bearerToken = bearerToken;
}
@Override
public void applyToParams(List<Pair> queryParams, Map<String, String> headerParams, Map<String, String> cookieParams,
String payload, String method, URI uri) throws ApiException {
if (bearerToken == null) {
return;
}
headerParams.put("Authorization", (scheme != null ? upperCaseBearer(scheme) + " " : "") + bearerToken);
}
private static String upperCaseBearer(String scheme) {
return ("bearer".equalsIgnoreCase(scheme)) ? "Bearer" : scheme;
}
}

View File

@ -0,0 +1,42 @@
/*
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.client.auth;
import org.openapitools.client.Pair;
import org.openapitools.client.ApiException;
import java.net.URI;
import java.util.Map;
import java.util.List;
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen")
public class OAuth implements Authentication {
private String accessToken;
public String getAccessToken() {
return accessToken;
}
public void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
@Override
public void applyToParams(List<Pair> queryParams, Map<String, String> headerParams, Map<String, String> cookieParams,
String payload, String method, URI uri) throws ApiException {
if (accessToken != null) {
headerParams.put("Authorization", "Bearer " + accessToken);
}
}
}

View File

@ -0,0 +1,25 @@
/*
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.client.auth;
/**
* OAuth flows that are supported by this client
*/
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen")
public enum OAuthFlow {
ACCESS_CODE, //called authorizationCode in OpenAPI 3.0
IMPLICIT,
PASSWORD,
APPLICATION //called clientCredentials in OpenAPI 3.0
}

View File

@ -0,0 +1,69 @@
package org.openapitools.client.auth;
import okhttp3.OkHttpClient;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.apache.oltu.oauth2.client.HttpClient;
import org.apache.oltu.oauth2.client.request.OAuthClientRequest;
import org.apache.oltu.oauth2.client.response.OAuthClientResponse;
import org.apache.oltu.oauth2.client.response.OAuthClientResponseFactory;
import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import java.io.IOException;
import java.util.Map;
import java.util.Map.Entry;
public class OAuthOkHttpClient implements HttpClient {
private OkHttpClient client;
public OAuthOkHttpClient() {
this.client = new OkHttpClient();
}
public OAuthOkHttpClient(OkHttpClient client) {
this.client = client;
}
@Override
public <T extends OAuthClientResponse> T execute(OAuthClientRequest request, Map<String, String> headers,
String requestMethod, Class<T> responseClass)
throws OAuthSystemException, OAuthProblemException {
MediaType mediaType = MediaType.parse("application/json");
Request.Builder requestBuilder = new Request.Builder().url(request.getLocationUri());
if(headers != null) {
for (Entry<String, String> entry : headers.entrySet()) {
if (entry.getKey().equalsIgnoreCase("Content-Type")) {
mediaType = MediaType.parse(entry.getValue());
} else {
requestBuilder.addHeader(entry.getKey(), entry.getValue());
}
}
}
RequestBody body = request.getBody() != null ? RequestBody.create(request.getBody(), mediaType) : null;
requestBuilder.method(requestMethod, body);
try {
Response response = client.newCall(requestBuilder.build()).execute();
return OAuthClientResponseFactory.createCustomResponse(
response.body().string(),
response.body().contentType().toString(),
response.code(),
response.headers().toMultimap(),
responseClass);
} catch (IOException e) {
throw new OAuthSystemException(e);
}
}
@Override
public void shutdown() {
// Nothing to do here
}
}

View File

@ -0,0 +1,210 @@
package org.openapitools.client.auth;
import org.openapitools.client.ApiException;
import org.openapitools.client.Pair;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.apache.oltu.oauth2.client.OAuthClient;
import org.apache.oltu.oauth2.client.request.OAuthBearerClientRequest;
import org.apache.oltu.oauth2.client.request.OAuthClientRequest;
import org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder;
import org.apache.oltu.oauth2.client.response.OAuthJSONAccessTokenResponse;
import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import org.apache.oltu.oauth2.common.message.types.GrantType;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URI;
import java.util.Map;
import java.util.List;
public class RetryingOAuth extends OAuth implements Interceptor {
private OAuthClient oAuthClient;
private TokenRequestBuilder tokenRequestBuilder;
/**
* @param client An OkHttp client
* @param tokenRequestBuilder A token request builder
*/
public RetryingOAuth(OkHttpClient client, TokenRequestBuilder tokenRequestBuilder) {
this.oAuthClient = new OAuthClient(new OAuthOkHttpClient(client));
this.tokenRequestBuilder = tokenRequestBuilder;
}
/**
* @param tokenRequestBuilder A token request builder
*/
public RetryingOAuth(TokenRequestBuilder tokenRequestBuilder) {
this(new OkHttpClient(), tokenRequestBuilder);
}
/**
* @param tokenUrl The token URL to be used for this OAuth2 flow.
* Applicable to the following OAuth2 flows: "password", "clientCredentials" and "authorizationCode".
* The value must be an absolute URL.
* @param clientId The OAuth2 client ID for the "clientCredentials" flow.
* @param flow OAuth flow.
* @param clientSecret The OAuth2 client secret for the "clientCredentials" flow.
* @param parameters A map of string.
*/
public RetryingOAuth(
String tokenUrl,
String clientId,
OAuthFlow flow,
String clientSecret,
Map<String, String> parameters
) {
this(OAuthClientRequest.tokenLocation(tokenUrl)
.setClientId(clientId)
.setClientSecret(clientSecret));
setFlow(flow);
if (parameters != null) {
for (Map.Entry<String, String> entry : parameters.entrySet()) {
tokenRequestBuilder.setParameter(entry.getKey(), entry.getValue());
}
}
}
/**
* Set the OAuth flow
*
* @param flow The OAuth flow.
*/
public void setFlow(OAuthFlow flow) {
switch(flow) {
case ACCESS_CODE:
tokenRequestBuilder.setGrantType(GrantType.AUTHORIZATION_CODE);
break;
case IMPLICIT:
tokenRequestBuilder.setGrantType(GrantType.IMPLICIT);
break;
case PASSWORD:
tokenRequestBuilder.setGrantType(GrantType.PASSWORD);
break;
case APPLICATION:
tokenRequestBuilder.setGrantType(GrantType.CLIENT_CREDENTIALS);
break;
default:
break;
}
}
@Override
public Response intercept(Chain chain) throws IOException {
return retryingIntercept(chain, true);
}
private Response retryingIntercept(Chain chain, boolean updateTokenAndRetryOnAuthorizationFailure) throws IOException {
Request request = chain.request();
// If the request already has an authorization (e.g. Basic auth), proceed with the request as is
if (request.header("Authorization") != null) {
return chain.proceed(request);
}
// Get the token if it has not yet been acquired
if (getAccessToken() == null) {
updateAccessToken(null);
}
OAuthClientRequest oAuthRequest;
if (getAccessToken() != null) {
// Build the request
Request.Builder requestBuilder = request.newBuilder();
String requestAccessToken = getAccessToken();
try {
oAuthRequest =
new OAuthBearerClientRequest(request.url().toString()).
setAccessToken(requestAccessToken).
buildHeaderMessage();
} catch (OAuthSystemException e) {
throw new IOException(e);
}
Map<String, String> headers = oAuthRequest.getHeaders();
for (Map.Entry<String, String> entry : headers.entrySet()) {
requestBuilder.addHeader(entry.getKey(), entry.getValue());
}
requestBuilder.url(oAuthRequest.getLocationUri());
// Execute the request
Response response = chain.proceed(requestBuilder.build());
// 401/403 response codes most likely indicate an expired access token, unless it happens two times in a row
if (
response != null &&
( response.code() == HttpURLConnection.HTTP_UNAUTHORIZED ||
response.code() == HttpURLConnection.HTTP_FORBIDDEN ) &&
updateTokenAndRetryOnAuthorizationFailure
) {
try {
if (updateAccessToken(requestAccessToken)) {
response.body().close();
return retryingIntercept(chain, false);
}
} catch (Exception e) {
response.body().close();
throw e;
}
}
return response;
}
else {
return chain.proceed(chain.request());
}
}
/**
* Returns true if the access token has been updated
*
* @param requestAccessToken the request access token
* @return True if the update is successful
* @throws java.io.IOException If fail to update the access token
*/
public synchronized boolean updateAccessToken(String requestAccessToken) throws IOException {
if (getAccessToken() == null || getAccessToken().equals(requestAccessToken)) {
try {
OAuthJSONAccessTokenResponse accessTokenResponse =
oAuthClient.accessToken(tokenRequestBuilder.buildBodyMessage());
if (accessTokenResponse != null && accessTokenResponse.getAccessToken() != null) {
setAccessToken(accessTokenResponse.getAccessToken());
}
} catch (OAuthSystemException | OAuthProblemException e) {
throw new IOException(e);
}
}
return getAccessToken() == null || !getAccessToken().equals(requestAccessToken);
}
/**
* Gets the token request builder
*
* @return A token request builder
*/
public TokenRequestBuilder getTokenRequestBuilder() {
return tokenRequestBuilder;
}
/**
* Sets the token request builder
*
* @param tokenRequestBuilder Token request builder
*/
public void setTokenRequestBuilder(TokenRequestBuilder tokenRequestBuilder) {
this.tokenRequestBuilder = tokenRequestBuilder;
}
// Applying authorization to parameters is performed in the retryingIntercept method
@Override
public void applyToParams(List<Pair> queryParams, Map<String, String> headerParams, Map<String, String> cookieParams,
String payload, String method, URI uri) throws ApiException {
// No implementation necessary
}
}

View File

@ -0,0 +1,148 @@
/*
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.client.model;
import org.openapitools.client.ApiException;
import java.util.Objects;
import java.lang.reflect.Type;
import java.util.Map;
//import com.fasterxml.jackson.annotation.JsonValue;
/**
* Abstract class for oneOf,anyOf schemas defined in OpenAPI spec
*/
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen")
public abstract class AbstractOpenApiSchema {
// store the actual instance of the schema/object
private Object instance;
// is nullable
private Boolean isNullable;
// schema type (e.g. oneOf, anyOf)
private final String schemaType;
public AbstractOpenApiSchema(String schemaType, Boolean isNullable) {
this.schemaType = schemaType;
this.isNullable = isNullable;
}
/**
* Get the list of oneOf/anyOf composed schemas allowed to be stored in this object
*
* @return an instance of the actual schema/object
*/
public abstract Map<String, Class<?>> getSchemas();
/**
* Get the actual instance
*
* @return an instance of the actual schema/object
*/
//@JsonValue
public Object getActualInstance() {return instance;}
/**
* Set the actual instance
*
* @param instance the actual instance of the schema/object
*/
public void setActualInstance(Object instance) {this.instance = instance;}
/**
* Get the instant recursively when the schemas defined in oneOf/anyof happen to be oneOf/anyOf schema as well
*
* @return an instance of the actual schema/object
*/
public Object getActualInstanceRecursively() {
return getActualInstanceRecursively(this);
}
private Object getActualInstanceRecursively(AbstractOpenApiSchema object) {
if (object.getActualInstance() == null) {
return null;
} else if (object.getActualInstance() instanceof AbstractOpenApiSchema) {
return getActualInstanceRecursively((AbstractOpenApiSchema)object.getActualInstance());
} else {
return object.getActualInstance();
}
}
/**
* Get the schema type (e.g. anyOf, oneOf)
*
* @return the schema type
*/
public String getSchemaType() {
return schemaType;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class ").append(getClass()).append(" {\n");
sb.append(" instance: ").append(toIndentedString(instance)).append("\n");
sb.append(" isNullable: ").append(toIndentedString(isNullable)).append("\n");
sb.append(" schemaType: ").append(toIndentedString(schemaType)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
AbstractOpenApiSchema a = (AbstractOpenApiSchema) o;
return Objects.equals(this.instance, a.instance) &&
Objects.equals(this.isNullable, a.isNullable) &&
Objects.equals(this.schemaType, a.schemaType);
}
@Override
public int hashCode() {
return Objects.hash(instance, isNullable, schemaType);
}
/**
* Is nullable
*
* @return true if it's nullable
*/
public Boolean isNullable() {
if (Boolean.TRUE.equals(isNullable)) {
return Boolean.TRUE;
} else {
return Boolean.FALSE;
}
}
}

View File

@ -0,0 +1,256 @@
/*
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.client.model;
import java.util.Objects;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.util.Arrays;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.openapitools.client.JSON;
/**
* Animal
*/
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen")
public class Animal {
public static final String SERIALIZED_NAME_CLASS_NAME = "className";
@SerializedName(SERIALIZED_NAME_CLASS_NAME)
protected String className;
public static final String SERIALIZED_NAME_COLOR = "color";
@SerializedName(SERIALIZED_NAME_COLOR)
private String color = "red";
public Animal() {
this.className = this.getClass().getSimpleName();
}
public Animal className(String className) {
this.className = className;
return this;
}
/**
* Get className
* @return className
**/
@javax.annotation.Nonnull
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
public Animal color(String color) {
this.color = color;
return this;
}
/**
* Get color
* @return color
**/
@javax.annotation.Nullable
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
/**
* A container for additional, undeclared properties.
* This is a holder for any undeclared properties as specified with
* the 'additionalProperties' keyword in the OAS document.
*/
private Map<String, Object> additionalProperties;
/**
* Set the additional (undeclared) property with the specified name and value.
* If the property does not already exist, create it otherwise replace it.
*
* @param key name of the property
* @param value value of the property
* @return the Animal instance itself
*/
public Animal putAdditionalProperty(String key, Object value) {
if (this.additionalProperties == null) {
this.additionalProperties = new HashMap<String, Object>();
}
this.additionalProperties.put(key, value);
return this;
}
/**
* Return the additional (undeclared) property.
*
* @return a map of objects
*/
public Map<String, Object> getAdditionalProperties() {
return additionalProperties;
}
/**
* Return the additional (undeclared) property with the specified name.
*
* @param key name of the property
* @return an object
*/
public Object getAdditionalProperty(String key) {
if (this.additionalProperties == null) {
return null;
}
return this.additionalProperties.get(key);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Animal animal = (Animal) o;
return Objects.equals(this.className, animal.className) &&
Objects.equals(this.color, animal.color)&&
Objects.equals(this.additionalProperties, animal.additionalProperties);
}
@Override
public int hashCode() {
return Objects.hash(className, color, additionalProperties);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class Animal {\n");
sb.append(" className: ").append(toIndentedString(className)).append("\n");
sb.append(" color: ").append(toIndentedString(color)).append("\n");
sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
public static HashSet<String> openapiFields;
public static HashSet<String> openapiRequiredFields;
static {
// a set of all properties/fields (JSON key names)
openapiFields = new HashSet<String>();
openapiFields.add("className");
openapiFields.add("color");
// a set of required properties/fields (JSON key names)
openapiRequiredFields = new HashSet<String>();
openapiRequiredFields.add("className");
}
/**
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to Animal
*/
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!Animal.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in Animal is not found in the empty JSON string", Animal.openapiRequiredFields.toString()));
}
}
String discriminatorValue = jsonElement.getAsJsonObject().get("className").getAsString();
switch (discriminatorValue) {
case "Cat":
Cat.validateJsonElement(jsonElement);
break;
case "Dog":
Dog.validateJsonElement(jsonElement);
break;
default:
throw new IllegalArgumentException(String.format("The value of the `className` field `%s` does not match any key defined in the discriminator's mapping.", discriminatorValue));
}
}
/**
* Create an instance of Animal given an JSON string
*
* @param jsonString JSON string
* @return An instance of Animal
* @throws IOException if the JSON string is invalid with respect to Animal
*/
public static Animal fromJson(String jsonString) throws IOException {
return JSON.getGson().fromJson(jsonString, Animal.class);
}
/**
* Convert an instance of Animal to an JSON string
*
* @return JSON string
*/
public String toJson() {
return JSON.getGson().toJson(this);
}
}

View File

@ -0,0 +1,244 @@
/*
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.client.model;
import java.util.Objects;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.openapitools.client.JSON;
/**
* string or int (anyOf)
*/
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen")
public class AnyOfStringOrInt {
public AnyOfStringOrInt() {
}
/**
* A container for additional, undeclared properties.
* This is a holder for any undeclared properties as specified with
* the 'additionalProperties' keyword in the OAS document.
*/
private Map<String, Object> additionalProperties;
/**
* Set the additional (undeclared) property with the specified name and value.
* If the property does not already exist, create it otherwise replace it.
*
* @param key name of the property
* @param value value of the property
* @return the AnyOfStringOrInt instance itself
*/
public AnyOfStringOrInt putAdditionalProperty(String key, Object value) {
if (this.additionalProperties == null) {
this.additionalProperties = new HashMap<String, Object>();
}
this.additionalProperties.put(key, value);
return this;
}
/**
* Return the additional (undeclared) property.
*
* @return a map of objects
*/
public Map<String, Object> getAdditionalProperties() {
return additionalProperties;
}
/**
* Return the additional (undeclared) property with the specified name.
*
* @param key name of the property
* @return an object
*/
public Object getAdditionalProperty(String key) {
if (this.additionalProperties == null) {
return null;
}
return this.additionalProperties.get(key);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
return true;
}
@Override
public int hashCode() {
return Objects.hash(additionalProperties);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class AnyOfStringOrInt {\n");
sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
public static HashSet<String> openapiFields;
public static HashSet<String> openapiRequiredFields;
static {
// a set of all properties/fields (JSON key names)
openapiFields = new HashSet<String>();
// a set of required properties/fields (JSON key names)
openapiRequiredFields = new HashSet<String>();
}
/**
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to AnyOfStringOrInt
*/
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!AnyOfStringOrInt.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in AnyOfStringOrInt is not found in the empty JSON string", AnyOfStringOrInt.openapiRequiredFields.toString()));
}
}
}
public static class CustomTypeAdapterFactory implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (!AnyOfStringOrInt.class.isAssignableFrom(type.getRawType())) {
return null; // this class only serializes 'AnyOfStringOrInt' and its subtypes
}
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
final TypeAdapter<AnyOfStringOrInt> thisAdapter
= gson.getDelegateAdapter(this, TypeToken.get(AnyOfStringOrInt.class));
return (TypeAdapter<T>) new TypeAdapter<AnyOfStringOrInt>() {
@Override
public void write(JsonWriter out, AnyOfStringOrInt value) throws IOException {
JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject();
obj.remove("additionalProperties");
// serialize additional properties
if (value.getAdditionalProperties() != null) {
for (Map.Entry<String, Object> entry : value.getAdditionalProperties().entrySet()) {
if (entry.getValue() instanceof String)
obj.addProperty(entry.getKey(), (String) entry.getValue());
else if (entry.getValue() instanceof Number)
obj.addProperty(entry.getKey(), (Number) entry.getValue());
else if (entry.getValue() instanceof Boolean)
obj.addProperty(entry.getKey(), (Boolean) entry.getValue());
else if (entry.getValue() instanceof Character)
obj.addProperty(entry.getKey(), (Character) entry.getValue());
else {
obj.add(entry.getKey(), gson.toJsonTree(entry.getValue()).getAsJsonObject());
}
}
}
elementAdapter.write(out, obj);
}
@Override
public AnyOfStringOrInt read(JsonReader in) throws IOException {
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
JsonObject jsonObj = jsonElement.getAsJsonObject();
// store additional fields in the deserialized instance
AnyOfStringOrInt instance = thisAdapter.fromJsonTree(jsonObj);
for (Map.Entry<String, JsonElement> entry : jsonObj.entrySet()) {
if (!openapiFields.contains(entry.getKey())) {
if (entry.getValue().isJsonPrimitive()) { // primitive type
if (entry.getValue().getAsJsonPrimitive().isString())
instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString());
else if (entry.getValue().getAsJsonPrimitive().isNumber())
instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber());
else if (entry.getValue().getAsJsonPrimitive().isBoolean())
instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean());
else
throw new IllegalArgumentException(String.format("The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString()));
} else if (entry.getValue().isJsonArray()) {
instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class));
} else { // JSON object
instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class));
}
}
}
return instance;
}
}.nullSafe();
}
}
/**
* Create an instance of AnyOfStringOrInt given an JSON string
*
* @param jsonString JSON string
* @return An instance of AnyOfStringOrInt
* @throws IOException if the JSON string is invalid with respect to AnyOfStringOrInt
*/
public static AnyOfStringOrInt fromJson(String jsonString) throws IOException {
return JSON.getGson().fromJson(jsonString, AnyOfStringOrInt.class);
}
/**
* Convert an instance of AnyOfStringOrInt to an JSON string
*
* @return JSON string
*/
public String toJson() {
return JSON.getGson().toJson(this);
}
}

View File

@ -0,0 +1,294 @@
/*
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.client.model;
import java.util.Objects;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.util.Arrays;
import org.openapitools.client.model.Animal;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.openapitools.client.JSON;
/**
* Cat
*/
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen")
public class Cat extends Animal {
public static final String SERIALIZED_NAME_DECLAWED = "declawed";
@SerializedName(SERIALIZED_NAME_DECLAWED)
private Boolean declawed;
public Cat() {
this.className = this.getClass().getSimpleName();
}
public Cat declawed(Boolean declawed) {
this.declawed = declawed;
return this;
}
/**
* Get declawed
* @return declawed
**/
@javax.annotation.Nullable
public Boolean getDeclawed() {
return declawed;
}
public void setDeclawed(Boolean declawed) {
this.declawed = declawed;
}
/**
* A container for additional, undeclared properties.
* This is a holder for any undeclared properties as specified with
* the 'additionalProperties' keyword in the OAS document.
*/
private Map<String, Object> additionalProperties;
/**
* Set the additional (undeclared) property with the specified name and value.
* If the property does not already exist, create it otherwise replace it.
*
* @param key name of the property
* @param value value of the property
* @return the Cat instance itself
*/
public Cat putAdditionalProperty(String key, Object value) {
if (this.additionalProperties == null) {
this.additionalProperties = new HashMap<String, Object>();
}
this.additionalProperties.put(key, value);
return this;
}
/**
* Return the additional (undeclared) property.
*
* @return a map of objects
*/
public Map<String, Object> getAdditionalProperties() {
return additionalProperties;
}
/**
* Return the additional (undeclared) property with the specified name.
*
* @param key name of the property
* @return an object
*/
public Object getAdditionalProperty(String key) {
if (this.additionalProperties == null) {
return null;
}
return this.additionalProperties.get(key);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Cat cat = (Cat) o;
return Objects.equals(this.declawed, cat.declawed)&&
Objects.equals(this.additionalProperties, cat.additionalProperties) &&
super.equals(o);
}
@Override
public int hashCode() {
return Objects.hash(declawed, super.hashCode(), additionalProperties);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class Cat {\n");
sb.append(" ").append(toIndentedString(super.toString())).append("\n");
sb.append(" declawed: ").append(toIndentedString(declawed)).append("\n");
sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
public static HashSet<String> openapiFields;
public static HashSet<String> openapiRequiredFields;
static {
// a set of all properties/fields (JSON key names)
openapiFields = new HashSet<String>();
openapiFields.add("className");
openapiFields.add("color");
openapiFields.add("declawed");
// a set of required properties/fields (JSON key names)
openapiRequiredFields = new HashSet<String>();
openapiRequiredFields.add("className");
}
/**
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to Cat
*/
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!Cat.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in Cat is not found in the empty JSON string", Cat.openapiRequiredFields.toString()));
}
}
// check to make sure all required properties/fields are present in the JSON string
for (String requiredField : Cat.openapiRequiredFields) {
if (jsonElement.getAsJsonObject().get(requiredField) == null) {
throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString()));
}
}
}
public static class CustomTypeAdapterFactory implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (!Cat.class.isAssignableFrom(type.getRawType())) {
return null; // this class only serializes 'Cat' and its subtypes
}
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
final TypeAdapter<Cat> thisAdapter
= gson.getDelegateAdapter(this, TypeToken.get(Cat.class));
return (TypeAdapter<T>) new TypeAdapter<Cat>() {
@Override
public void write(JsonWriter out, Cat value) throws IOException {
JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject();
obj.remove("additionalProperties");
// serialize additional properties
if (value.getAdditionalProperties() != null) {
for (Map.Entry<String, Object> entry : value.getAdditionalProperties().entrySet()) {
if (entry.getValue() instanceof String)
obj.addProperty(entry.getKey(), (String) entry.getValue());
else if (entry.getValue() instanceof Number)
obj.addProperty(entry.getKey(), (Number) entry.getValue());
else if (entry.getValue() instanceof Boolean)
obj.addProperty(entry.getKey(), (Boolean) entry.getValue());
else if (entry.getValue() instanceof Character)
obj.addProperty(entry.getKey(), (Character) entry.getValue());
else {
obj.add(entry.getKey(), gson.toJsonTree(entry.getValue()).getAsJsonObject());
}
}
}
elementAdapter.write(out, obj);
}
@Override
public Cat read(JsonReader in) throws IOException {
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
JsonObject jsonObj = jsonElement.getAsJsonObject();
// store additional fields in the deserialized instance
Cat instance = thisAdapter.fromJsonTree(jsonObj);
for (Map.Entry<String, JsonElement> entry : jsonObj.entrySet()) {
if (!openapiFields.contains(entry.getKey())) {
if (entry.getValue().isJsonPrimitive()) { // primitive type
if (entry.getValue().getAsJsonPrimitive().isString())
instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString());
else if (entry.getValue().getAsJsonPrimitive().isNumber())
instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber());
else if (entry.getValue().getAsJsonPrimitive().isBoolean())
instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean());
else
throw new IllegalArgumentException(String.format("The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString()));
} else if (entry.getValue().isJsonArray()) {
instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class));
} else { // JSON object
instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class));
}
}
}
return instance;
}
}.nullSafe();
}
}
/**
* Create an instance of Cat given an JSON string
*
* @param jsonString JSON string
* @return An instance of Cat
* @throws IOException if the JSON string is invalid with respect to Cat
*/
public static Cat fromJson(String jsonString) throws IOException {
return JSON.getGson().fromJson(jsonString, Cat.class);
}
/**
* Convert an instance of Cat to an JSON string
*
* @return JSON string
*/
public String toJson() {
return JSON.getGson().toJson(this);
}
}

View File

@ -0,0 +1,312 @@
/*
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.client.model;
import java.util.Objects;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.util.Arrays;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.openapitools.client.JSON;
/**
* A category for a pet
*/
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen")
public class Category {
public static final String SERIALIZED_NAME_ID = "id";
@SerializedName(SERIALIZED_NAME_ID)
private Long id;
public static final String SERIALIZED_NAME_NAME = "name";
@SerializedName(SERIALIZED_NAME_NAME)
private String name;
public Category() {
}
public Category id(Long id) {
this.id = id;
return this;
}
/**
* Get id
* @return id
**/
@javax.annotation.Nullable
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Category name(String name) {
this.name = name;
return this;
}
/**
* Get name
* @return name
**/
@javax.annotation.Nullable
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
/**
* A container for additional, undeclared properties.
* This is a holder for any undeclared properties as specified with
* the 'additionalProperties' keyword in the OAS document.
*/
private Map<String, Object> additionalProperties;
/**
* Set the additional (undeclared) property with the specified name and value.
* If the property does not already exist, create it otherwise replace it.
*
* @param key name of the property
* @param value value of the property
* @return the Category instance itself
*/
public Category putAdditionalProperty(String key, Object value) {
if (this.additionalProperties == null) {
this.additionalProperties = new HashMap<String, Object>();
}
this.additionalProperties.put(key, value);
return this;
}
/**
* Return the additional (undeclared) property.
*
* @return a map of objects
*/
public Map<String, Object> getAdditionalProperties() {
return additionalProperties;
}
/**
* Return the additional (undeclared) property with the specified name.
*
* @param key name of the property
* @return an object
*/
public Object getAdditionalProperty(String key) {
if (this.additionalProperties == null) {
return null;
}
return this.additionalProperties.get(key);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Category category = (Category) o;
return Objects.equals(this.id, category.id) &&
Objects.equals(this.name, category.name)&&
Objects.equals(this.additionalProperties, category.additionalProperties);
}
@Override
public int hashCode() {
return Objects.hash(id, name, additionalProperties);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class Category {\n");
sb.append(" id: ").append(toIndentedString(id)).append("\n");
sb.append(" name: ").append(toIndentedString(name)).append("\n");
sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
public static HashSet<String> openapiFields;
public static HashSet<String> openapiRequiredFields;
static {
// a set of all properties/fields (JSON key names)
openapiFields = new HashSet<String>();
openapiFields.add("id");
openapiFields.add("name");
// a set of required properties/fields (JSON key names)
openapiRequiredFields = new HashSet<String>();
}
/**
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to Category
*/
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!Category.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in Category is not found in the empty JSON string", Category.openapiRequiredFields.toString()));
}
}
JsonObject jsonObj = jsonElement.getAsJsonObject();
if ((jsonObj.get("name") != null && !jsonObj.get("name").isJsonNull()) && !jsonObj.get("name").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `name` to be a primitive type in the JSON string but got `%s`", jsonObj.get("name").toString()));
}
}
public static class CustomTypeAdapterFactory implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (!Category.class.isAssignableFrom(type.getRawType())) {
return null; // this class only serializes 'Category' and its subtypes
}
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
final TypeAdapter<Category> thisAdapter
= gson.getDelegateAdapter(this, TypeToken.get(Category.class));
return (TypeAdapter<T>) new TypeAdapter<Category>() {
@Override
public void write(JsonWriter out, Category value) throws IOException {
JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject();
obj.remove("additionalProperties");
// serialize additional properties
if (value.getAdditionalProperties() != null) {
for (Map.Entry<String, Object> entry : value.getAdditionalProperties().entrySet()) {
if (entry.getValue() instanceof String)
obj.addProperty(entry.getKey(), (String) entry.getValue());
else if (entry.getValue() instanceof Number)
obj.addProperty(entry.getKey(), (Number) entry.getValue());
else if (entry.getValue() instanceof Boolean)
obj.addProperty(entry.getKey(), (Boolean) entry.getValue());
else if (entry.getValue() instanceof Character)
obj.addProperty(entry.getKey(), (Character) entry.getValue());
else {
obj.add(entry.getKey(), gson.toJsonTree(entry.getValue()).getAsJsonObject());
}
}
}
elementAdapter.write(out, obj);
}
@Override
public Category read(JsonReader in) throws IOException {
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
JsonObject jsonObj = jsonElement.getAsJsonObject();
// store additional fields in the deserialized instance
Category instance = thisAdapter.fromJsonTree(jsonObj);
for (Map.Entry<String, JsonElement> entry : jsonObj.entrySet()) {
if (!openapiFields.contains(entry.getKey())) {
if (entry.getValue().isJsonPrimitive()) { // primitive type
if (entry.getValue().getAsJsonPrimitive().isString())
instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString());
else if (entry.getValue().getAsJsonPrimitive().isNumber())
instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber());
else if (entry.getValue().getAsJsonPrimitive().isBoolean())
instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean());
else
throw new IllegalArgumentException(String.format("The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString()));
} else if (entry.getValue().isJsonArray()) {
instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class));
} else { // JSON object
instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class));
}
}
}
return instance;
}
}.nullSafe();
}
}
/**
* Create an instance of Category given an JSON string
*
* @param jsonString JSON string
* @return An instance of Category
* @throws IOException if the JSON string is invalid with respect to Category
*/
public static Category fromJson(String jsonString) throws IOException {
return JSON.getGson().fromJson(jsonString, Category.class);
}
/**
* Convert an instance of Category to an JSON string
*
* @return JSON string
*/
public String toJson() {
return JSON.getGson().toJson(this);
}
}

View File

@ -0,0 +1,294 @@
/*
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.client.model;
import java.util.Objects;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.util.Arrays;
import org.openapitools.client.model.Animal;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.openapitools.client.JSON;
/**
* Dog
*/
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen")
public class Dog extends Animal {
public static final String SERIALIZED_NAME_BREED = "breed";
@SerializedName(SERIALIZED_NAME_BREED)
private String breed;
public Dog() {
this.className = this.getClass().getSimpleName();
}
public Dog breed(String breed) {
this.breed = breed;
return this;
}
/**
* Get breed
* @return breed
**/
@javax.annotation.Nullable
public String getBreed() {
return breed;
}
public void setBreed(String breed) {
this.breed = breed;
}
/**
* A container for additional, undeclared properties.
* This is a holder for any undeclared properties as specified with
* the 'additionalProperties' keyword in the OAS document.
*/
private Map<String, Object> additionalProperties;
/**
* Set the additional (undeclared) property with the specified name and value.
* If the property does not already exist, create it otherwise replace it.
*
* @param key name of the property
* @param value value of the property
* @return the Dog instance itself
*/
public Dog putAdditionalProperty(String key, Object value) {
if (this.additionalProperties == null) {
this.additionalProperties = new HashMap<String, Object>();
}
this.additionalProperties.put(key, value);
return this;
}
/**
* Return the additional (undeclared) property.
*
* @return a map of objects
*/
public Map<String, Object> getAdditionalProperties() {
return additionalProperties;
}
/**
* Return the additional (undeclared) property with the specified name.
*
* @param key name of the property
* @return an object
*/
public Object getAdditionalProperty(String key) {
if (this.additionalProperties == null) {
return null;
}
return this.additionalProperties.get(key);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Dog dog = (Dog) o;
return Objects.equals(this.breed, dog.breed)&&
Objects.equals(this.additionalProperties, dog.additionalProperties) &&
super.equals(o);
}
@Override
public int hashCode() {
return Objects.hash(breed, super.hashCode(), additionalProperties);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class Dog {\n");
sb.append(" ").append(toIndentedString(super.toString())).append("\n");
sb.append(" breed: ").append(toIndentedString(breed)).append("\n");
sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
public static HashSet<String> openapiFields;
public static HashSet<String> openapiRequiredFields;
static {
// a set of all properties/fields (JSON key names)
openapiFields = new HashSet<String>();
openapiFields.add("className");
openapiFields.add("color");
openapiFields.add("breed");
// a set of required properties/fields (JSON key names)
openapiRequiredFields = new HashSet<String>();
openapiRequiredFields.add("className");
}
/**
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to Dog
*/
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!Dog.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in Dog is not found in the empty JSON string", Dog.openapiRequiredFields.toString()));
}
}
// check to make sure all required properties/fields are present in the JSON string
for (String requiredField : Dog.openapiRequiredFields) {
if (jsonElement.getAsJsonObject().get(requiredField) == null) {
throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString()));
}
}
}
public static class CustomTypeAdapterFactory implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (!Dog.class.isAssignableFrom(type.getRawType())) {
return null; // this class only serializes 'Dog' and its subtypes
}
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
final TypeAdapter<Dog> thisAdapter
= gson.getDelegateAdapter(this, TypeToken.get(Dog.class));
return (TypeAdapter<T>) new TypeAdapter<Dog>() {
@Override
public void write(JsonWriter out, Dog value) throws IOException {
JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject();
obj.remove("additionalProperties");
// serialize additional properties
if (value.getAdditionalProperties() != null) {
for (Map.Entry<String, Object> entry : value.getAdditionalProperties().entrySet()) {
if (entry.getValue() instanceof String)
obj.addProperty(entry.getKey(), (String) entry.getValue());
else if (entry.getValue() instanceof Number)
obj.addProperty(entry.getKey(), (Number) entry.getValue());
else if (entry.getValue() instanceof Boolean)
obj.addProperty(entry.getKey(), (Boolean) entry.getValue());
else if (entry.getValue() instanceof Character)
obj.addProperty(entry.getKey(), (Character) entry.getValue());
else {
obj.add(entry.getKey(), gson.toJsonTree(entry.getValue()).getAsJsonObject());
}
}
}
elementAdapter.write(out, obj);
}
@Override
public Dog read(JsonReader in) throws IOException {
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
JsonObject jsonObj = jsonElement.getAsJsonObject();
// store additional fields in the deserialized instance
Dog instance = thisAdapter.fromJsonTree(jsonObj);
for (Map.Entry<String, JsonElement> entry : jsonObj.entrySet()) {
if (!openapiFields.contains(entry.getKey())) {
if (entry.getValue().isJsonPrimitive()) { // primitive type
if (entry.getValue().getAsJsonPrimitive().isString())
instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString());
else if (entry.getValue().getAsJsonPrimitive().isNumber())
instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber());
else if (entry.getValue().getAsJsonPrimitive().isBoolean())
instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean());
else
throw new IllegalArgumentException(String.format("The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString()));
} else if (entry.getValue().isJsonArray()) {
instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class));
} else { // JSON object
instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class));
}
}
}
return instance;
}
}.nullSafe();
}
}
/**
* Create an instance of Dog given an JSON string
*
* @param jsonString JSON string
* @return An instance of Dog
* @throws IOException if the JSON string is invalid with respect to Dog
*/
public static Dog fromJson(String jsonString) throws IOException {
return JSON.getGson().fromJson(jsonString, Dog.class);
}
/**
* Convert an instance of Dog to an JSON string
*
* @return JSON string
*/
public String toJson() {
return JSON.getGson().toJson(this);
}
}

View File

@ -0,0 +1,343 @@
/*
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.client.model;
import java.util.Objects;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.util.Arrays;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.openapitools.client.JSON;
/**
* Describes the result of uploading an image resource
*/
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen")
public class ModelApiResponse {
public static final String SERIALIZED_NAME_CODE = "code";
@SerializedName(SERIALIZED_NAME_CODE)
private Integer code;
public static final String SERIALIZED_NAME_TYPE = "type";
@SerializedName(SERIALIZED_NAME_TYPE)
private String type;
public static final String SERIALIZED_NAME_MESSAGE = "message";
@SerializedName(SERIALIZED_NAME_MESSAGE)
private String message;
public ModelApiResponse() {
}
public ModelApiResponse code(Integer code) {
this.code = code;
return this;
}
/**
* Get code
* @return code
**/
@javax.annotation.Nullable
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public ModelApiResponse type(String type) {
this.type = type;
return this;
}
/**
* Get type
* @return type
**/
@javax.annotation.Nullable
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public ModelApiResponse message(String message) {
this.message = message;
return this;
}
/**
* Get message
* @return message
**/
@javax.annotation.Nullable
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
/**
* A container for additional, undeclared properties.
* This is a holder for any undeclared properties as specified with
* the 'additionalProperties' keyword in the OAS document.
*/
private Map<String, Object> additionalProperties;
/**
* Set the additional (undeclared) property with the specified name and value.
* If the property does not already exist, create it otherwise replace it.
*
* @param key name of the property
* @param value value of the property
* @return the ModelApiResponse instance itself
*/
public ModelApiResponse putAdditionalProperty(String key, Object value) {
if (this.additionalProperties == null) {
this.additionalProperties = new HashMap<String, Object>();
}
this.additionalProperties.put(key, value);
return this;
}
/**
* Return the additional (undeclared) property.
*
* @return a map of objects
*/
public Map<String, Object> getAdditionalProperties() {
return additionalProperties;
}
/**
* Return the additional (undeclared) property with the specified name.
*
* @param key name of the property
* @return an object
*/
public Object getAdditionalProperty(String key) {
if (this.additionalProperties == null) {
return null;
}
return this.additionalProperties.get(key);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ModelApiResponse _apiResponse = (ModelApiResponse) o;
return Objects.equals(this.code, _apiResponse.code) &&
Objects.equals(this.type, _apiResponse.type) &&
Objects.equals(this.message, _apiResponse.message)&&
Objects.equals(this.additionalProperties, _apiResponse.additionalProperties);
}
@Override
public int hashCode() {
return Objects.hash(code, type, message, additionalProperties);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class ModelApiResponse {\n");
sb.append(" code: ").append(toIndentedString(code)).append("\n");
sb.append(" type: ").append(toIndentedString(type)).append("\n");
sb.append(" message: ").append(toIndentedString(message)).append("\n");
sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
public static HashSet<String> openapiFields;
public static HashSet<String> openapiRequiredFields;
static {
// a set of all properties/fields (JSON key names)
openapiFields = new HashSet<String>();
openapiFields.add("code");
openapiFields.add("type");
openapiFields.add("message");
// a set of required properties/fields (JSON key names)
openapiRequiredFields = new HashSet<String>();
}
/**
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to ModelApiResponse
*/
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!ModelApiResponse.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in ModelApiResponse is not found in the empty JSON string", ModelApiResponse.openapiRequiredFields.toString()));
}
}
JsonObject jsonObj = jsonElement.getAsJsonObject();
if ((jsonObj.get("type") != null && !jsonObj.get("type").isJsonNull()) && !jsonObj.get("type").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `type` to be a primitive type in the JSON string but got `%s`", jsonObj.get("type").toString()));
}
if ((jsonObj.get("message") != null && !jsonObj.get("message").isJsonNull()) && !jsonObj.get("message").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `message` to be a primitive type in the JSON string but got `%s`", jsonObj.get("message").toString()));
}
}
public static class CustomTypeAdapterFactory implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (!ModelApiResponse.class.isAssignableFrom(type.getRawType())) {
return null; // this class only serializes 'ModelApiResponse' and its subtypes
}
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
final TypeAdapter<ModelApiResponse> thisAdapter
= gson.getDelegateAdapter(this, TypeToken.get(ModelApiResponse.class));
return (TypeAdapter<T>) new TypeAdapter<ModelApiResponse>() {
@Override
public void write(JsonWriter out, ModelApiResponse value) throws IOException {
JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject();
obj.remove("additionalProperties");
// serialize additional properties
if (value.getAdditionalProperties() != null) {
for (Map.Entry<String, Object> entry : value.getAdditionalProperties().entrySet()) {
if (entry.getValue() instanceof String)
obj.addProperty(entry.getKey(), (String) entry.getValue());
else if (entry.getValue() instanceof Number)
obj.addProperty(entry.getKey(), (Number) entry.getValue());
else if (entry.getValue() instanceof Boolean)
obj.addProperty(entry.getKey(), (Boolean) entry.getValue());
else if (entry.getValue() instanceof Character)
obj.addProperty(entry.getKey(), (Character) entry.getValue());
else {
obj.add(entry.getKey(), gson.toJsonTree(entry.getValue()).getAsJsonObject());
}
}
}
elementAdapter.write(out, obj);
}
@Override
public ModelApiResponse read(JsonReader in) throws IOException {
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
JsonObject jsonObj = jsonElement.getAsJsonObject();
// store additional fields in the deserialized instance
ModelApiResponse instance = thisAdapter.fromJsonTree(jsonObj);
for (Map.Entry<String, JsonElement> entry : jsonObj.entrySet()) {
if (!openapiFields.contains(entry.getKey())) {
if (entry.getValue().isJsonPrimitive()) { // primitive type
if (entry.getValue().getAsJsonPrimitive().isString())
instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString());
else if (entry.getValue().getAsJsonPrimitive().isNumber())
instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber());
else if (entry.getValue().getAsJsonPrimitive().isBoolean())
instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean());
else
throw new IllegalArgumentException(String.format("The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString()));
} else if (entry.getValue().isJsonArray()) {
instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class));
} else { // JSON object
instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class));
}
}
}
return instance;
}
}.nullSafe();
}
}
/**
* Create an instance of ModelApiResponse given an JSON string
*
* @param jsonString JSON string
* @return An instance of ModelApiResponse
* @throws IOException if the JSON string is invalid with respect to ModelApiResponse
*/
public static ModelApiResponse fromJson(String jsonString) throws IOException {
return JSON.getGson().fromJson(jsonString, ModelApiResponse.class);
}
/**
* Convert an instance of ModelApiResponse to an JSON string
*
* @return JSON string
*/
public String toJson() {
return JSON.getGson().toJson(this);
}
}

View File

@ -0,0 +1,277 @@
/*
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.client.model;
import java.util.Objects;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapter;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import com.google.gson.JsonPrimitive;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonArray;
import com.google.gson.JsonParseException;
import org.openapitools.client.JSON;
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen")
public class OneOfStringOrInt extends AbstractOpenApiSchema {
private static final Logger log = Logger.getLogger(OneOfStringOrInt.class.getName());
public static class CustomTypeAdapterFactory implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (!OneOfStringOrInt.class.isAssignableFrom(type.getRawType())) {
return null; // this class only serializes 'OneOfStringOrInt' and its subtypes
}
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
final TypeAdapter<String> adapterString = gson.getDelegateAdapter(this, TypeToken.get(String.class));
final TypeAdapter<Integer> adapterInteger = gson.getDelegateAdapter(this, TypeToken.get(Integer.class));
return (TypeAdapter<T>) new TypeAdapter<OneOfStringOrInt>() {
@Override
public void write(JsonWriter out, OneOfStringOrInt value) throws IOException {
if (value == null || value.getActualInstance() == null) {
elementAdapter.write(out, null);
return;
}
// check if the actual instance is of the type `String`
if (value.getActualInstance() instanceof String) {
JsonPrimitive primitive = adapterString.toJsonTree((String)value.getActualInstance()).getAsJsonPrimitive();
elementAdapter.write(out, primitive);
return;
}
// check if the actual instance is of the type `Integer`
if (value.getActualInstance() instanceof Integer) {
JsonPrimitive primitive = adapterInteger.toJsonTree((Integer)value.getActualInstance()).getAsJsonPrimitive();
elementAdapter.write(out, primitive);
return;
}
throw new IOException("Failed to serialize as the type doesn't match oneOf schemas: Integer, String");
}
@Override
public OneOfStringOrInt read(JsonReader in) throws IOException {
Object deserialized = null;
JsonElement jsonElement = elementAdapter.read(in);
int match = 0;
ArrayList<String> errorMessages = new ArrayList<>();
TypeAdapter actualAdapter = elementAdapter;
// deserialize String
try {
// validate the JSON object to see if any exception is thrown
if(!jsonElement.getAsJsonPrimitive().isString()) {
throw new IllegalArgumentException(String.format("Expected json element to be of type String in the JSON string but got `%s`", jsonElement.toString()));
}
actualAdapter = adapterString;
match++;
log.log(Level.FINER, "Input data matches schema 'String'");
} catch (Exception e) {
// deserialization failed, continue
errorMessages.add(String.format("Deserialization for String failed with `%s`.", e.getMessage()));
log.log(Level.FINER, "Input data does not match schema 'String'", e);
}
// deserialize Integer
try {
// validate the JSON object to see if any exception is thrown
if(!jsonElement.getAsJsonPrimitive().isNumber()) {
throw new IllegalArgumentException(String.format("Expected json element to be of type Number in the JSON string but got `%s`", jsonElement.toString()));
}
actualAdapter = adapterInteger;
match++;
log.log(Level.FINER, "Input data matches schema 'Integer'");
} catch (Exception e) {
// deserialization failed, continue
errorMessages.add(String.format("Deserialization for Integer failed with `%s`.", e.getMessage()));
log.log(Level.FINER, "Input data does not match schema 'Integer'", e);
}
if (match == 1) {
OneOfStringOrInt ret = new OneOfStringOrInt();
ret.setActualInstance(actualAdapter.fromJsonTree(jsonElement));
return ret;
}
throw new IOException(String.format("Failed deserialization for OneOfStringOrInt: %d classes match result, expected 1. Detailed failure message for oneOf schemas: %s. JSON: %s", match, errorMessages, jsonElement.toString()));
}
}.nullSafe();
}
}
// store a list of schema names defined in oneOf
public static final Map<String, Class<?>> schemas = new HashMap<String, Class<?>>();
public OneOfStringOrInt() {
super("oneOf", Boolean.FALSE);
}
public OneOfStringOrInt(Integer o) {
super("oneOf", Boolean.FALSE);
setActualInstance(o);
}
public OneOfStringOrInt(String o) {
super("oneOf", Boolean.FALSE);
setActualInstance(o);
}
static {
schemas.put("String", String.class);
schemas.put("Integer", Integer.class);
}
@Override
public Map<String, Class<?>> getSchemas() {
return OneOfStringOrInt.schemas;
}
/**
* Set the instance that matches the oneOf child schema, check
* the instance parameter is valid against the oneOf child schemas:
* Integer, String
*
* It could be an instance of the 'oneOf' schemas.
*/
@Override
public void setActualInstance(Object instance) {
if (instance instanceof String) {
super.setActualInstance(instance);
return;
}
if (instance instanceof Integer) {
super.setActualInstance(instance);
return;
}
throw new RuntimeException("Invalid instance type. Must be Integer, String");
}
/**
* Get the actual instance, which can be the following:
* Integer, String
*
* @return The actual instance (Integer, String)
*/
@Override
public Object getActualInstance() {
return super.getActualInstance();
}
/**
* Get the actual instance of `String`. If the actual instance is not `String`,
* the ClassCastException will be thrown.
*
* @return The actual instance of `String`
* @throws ClassCastException if the instance is not `String`
*/
public String getString() throws ClassCastException {
return (String)super.getActualInstance();
}
/**
* Get the actual instance of `Integer`. If the actual instance is not `Integer`,
* the ClassCastException will be thrown.
*
* @return The actual instance of `Integer`
* @throws ClassCastException if the instance is not `Integer`
*/
public Integer getInteger() throws ClassCastException {
return (Integer)super.getActualInstance();
}
/**
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to OneOfStringOrInt
*/
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
// validate oneOf schemas one by one
int validCount = 0;
ArrayList<String> errorMessages = new ArrayList<>();
// validate the json string with String
try {
if(!jsonElement.getAsJsonPrimitive().isString()) {
throw new IllegalArgumentException(String.format("Expected json element to be of type String in the JSON string but got `%s`", jsonElement.toString()));
}
validCount++;
} catch (Exception e) {
errorMessages.add(String.format("Deserialization for String failed with `%s`.", e.getMessage()));
// continue to the next one
}
// validate the json string with Integer
try {
if(!jsonElement.getAsJsonPrimitive().isNumber()) {
throw new IllegalArgumentException(String.format("Expected json element to be of type Number in the JSON string but got `%s`", jsonElement.toString()));
}
validCount++;
} catch (Exception e) {
errorMessages.add(String.format("Deserialization for Integer failed with `%s`.", e.getMessage()));
// continue to the next one
}
if (validCount != 1) {
throw new IOException(String.format("The JSON string is invalid for OneOfStringOrInt with oneOf schemas: Integer, String. %d class(es) match the result, expected 1. Detailed failure message for oneOf schemas: %s. JSON: %s", validCount, errorMessages, jsonElement.toString()));
}
}
/**
* Create an instance of OneOfStringOrInt given an JSON string
*
* @param jsonString JSON string
* @return An instance of OneOfStringOrInt
* @throws IOException if the JSON string is invalid with respect to OneOfStringOrInt
*/
public static OneOfStringOrInt fromJson(String jsonString) throws IOException {
return JSON.getGson().fromJson(jsonString, OneOfStringOrInt.class);
}
/**
* Convert an instance of OneOfStringOrInt to an JSON string
*
* @return JSON string
*/
public String toJson() {
return JSON.getGson().toJson(this);
}
}

View File

@ -0,0 +1,474 @@
/*
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.client.model;
import java.util.Objects;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.time.OffsetDateTime;
import java.util.Arrays;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.openapitools.client.JSON;
/**
* An order for a pets from the pet store
*/
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen")
public class Order {
public static final String SERIALIZED_NAME_ID = "id";
@SerializedName(SERIALIZED_NAME_ID)
private Long id;
public static final String SERIALIZED_NAME_PET_ID = "petId";
@SerializedName(SERIALIZED_NAME_PET_ID)
private Long petId;
public static final String SERIALIZED_NAME_QUANTITY = "quantity";
@SerializedName(SERIALIZED_NAME_QUANTITY)
private Integer quantity;
public static final String SERIALIZED_NAME_SHIP_DATE = "shipDate";
@SerializedName(SERIALIZED_NAME_SHIP_DATE)
private OffsetDateTime shipDate;
/**
* Order Status
*/
@JsonAdapter(StatusEnum.Adapter.class)
public enum StatusEnum {
PLACED("placed"),
APPROVED("approved"),
DELIVERED("delivered");
private String value;
StatusEnum(String value) {
this.value = value;
}
public String getValue() {
return value;
}
@Override
public String toString() {
return String.valueOf(value);
}
public static StatusEnum fromValue(String value) {
for (StatusEnum b : StatusEnum.values()) {
if (b.value.equals(value)) {
return b;
}
}
throw new IllegalArgumentException("Unexpected value '" + value + "'");
}
public static class Adapter extends TypeAdapter<StatusEnum> {
@Override
public void write(final JsonWriter jsonWriter, final StatusEnum enumeration) throws IOException {
jsonWriter.value(enumeration.getValue());
}
@Override
public StatusEnum read(final JsonReader jsonReader) throws IOException {
String value = jsonReader.nextString();
return StatusEnum.fromValue(value);
}
}
}
public static final String SERIALIZED_NAME_STATUS = "status";
@SerializedName(SERIALIZED_NAME_STATUS)
private StatusEnum status;
public static final String SERIALIZED_NAME_COMPLETE = "complete";
@SerializedName(SERIALIZED_NAME_COMPLETE)
private Boolean complete = false;
public Order() {
}
public Order id(Long id) {
this.id = id;
return this;
}
/**
* Get id
* @return id
**/
@javax.annotation.Nullable
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Order petId(Long petId) {
this.petId = petId;
return this;
}
/**
* Get petId
* @return petId
**/
@javax.annotation.Nullable
public Long getPetId() {
return petId;
}
public void setPetId(Long petId) {
this.petId = petId;
}
public Order quantity(Integer quantity) {
this.quantity = quantity;
return this;
}
/**
* Get quantity
* @return quantity
**/
@javax.annotation.Nullable
public Integer getQuantity() {
return quantity;
}
public void setQuantity(Integer quantity) {
this.quantity = quantity;
}
public Order shipDate(OffsetDateTime shipDate) {
this.shipDate = shipDate;
return this;
}
/**
* Get shipDate
* @return shipDate
**/
@javax.annotation.Nullable
public OffsetDateTime getShipDate() {
return shipDate;
}
public void setShipDate(OffsetDateTime shipDate) {
this.shipDate = shipDate;
}
public Order status(StatusEnum status) {
this.status = status;
return this;
}
/**
* Order Status
* @return status
**/
@javax.annotation.Nullable
public StatusEnum getStatus() {
return status;
}
public void setStatus(StatusEnum status) {
this.status = status;
}
public Order complete(Boolean complete) {
this.complete = complete;
return this;
}
/**
* Get complete
* @return complete
**/
@javax.annotation.Nullable
public Boolean getComplete() {
return complete;
}
public void setComplete(Boolean complete) {
this.complete = complete;
}
/**
* A container for additional, undeclared properties.
* This is a holder for any undeclared properties as specified with
* the 'additionalProperties' keyword in the OAS document.
*/
private Map<String, Object> additionalProperties;
/**
* Set the additional (undeclared) property with the specified name and value.
* If the property does not already exist, create it otherwise replace it.
*
* @param key name of the property
* @param value value of the property
* @return the Order instance itself
*/
public Order putAdditionalProperty(String key, Object value) {
if (this.additionalProperties == null) {
this.additionalProperties = new HashMap<String, Object>();
}
this.additionalProperties.put(key, value);
return this;
}
/**
* Return the additional (undeclared) property.
*
* @return a map of objects
*/
public Map<String, Object> getAdditionalProperties() {
return additionalProperties;
}
/**
* Return the additional (undeclared) property with the specified name.
*
* @param key name of the property
* @return an object
*/
public Object getAdditionalProperty(String key) {
if (this.additionalProperties == null) {
return null;
}
return this.additionalProperties.get(key);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Order order = (Order) o;
return Objects.equals(this.id, order.id) &&
Objects.equals(this.petId, order.petId) &&
Objects.equals(this.quantity, order.quantity) &&
Objects.equals(this.shipDate, order.shipDate) &&
Objects.equals(this.status, order.status) &&
Objects.equals(this.complete, order.complete)&&
Objects.equals(this.additionalProperties, order.additionalProperties);
}
@Override
public int hashCode() {
return Objects.hash(id, petId, quantity, shipDate, status, complete, additionalProperties);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class Order {\n");
sb.append(" id: ").append(toIndentedString(id)).append("\n");
sb.append(" petId: ").append(toIndentedString(petId)).append("\n");
sb.append(" quantity: ").append(toIndentedString(quantity)).append("\n");
sb.append(" shipDate: ").append(toIndentedString(shipDate)).append("\n");
sb.append(" status: ").append(toIndentedString(status)).append("\n");
sb.append(" complete: ").append(toIndentedString(complete)).append("\n");
sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
public static HashSet<String> openapiFields;
public static HashSet<String> openapiRequiredFields;
static {
// a set of all properties/fields (JSON key names)
openapiFields = new HashSet<String>();
openapiFields.add("id");
openapiFields.add("petId");
openapiFields.add("quantity");
openapiFields.add("shipDate");
openapiFields.add("status");
openapiFields.add("complete");
// a set of required properties/fields (JSON key names)
openapiRequiredFields = new HashSet<String>();
}
/**
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to Order
*/
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!Order.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in Order is not found in the empty JSON string", Order.openapiRequiredFields.toString()));
}
}
JsonObject jsonObj = jsonElement.getAsJsonObject();
if ((jsonObj.get("status") != null && !jsonObj.get("status").isJsonNull()) && !jsonObj.get("status").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `status` to be a primitive type in the JSON string but got `%s`", jsonObj.get("status").toString()));
}
}
public static class CustomTypeAdapterFactory implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (!Order.class.isAssignableFrom(type.getRawType())) {
return null; // this class only serializes 'Order' and its subtypes
}
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
final TypeAdapter<Order> thisAdapter
= gson.getDelegateAdapter(this, TypeToken.get(Order.class));
return (TypeAdapter<T>) new TypeAdapter<Order>() {
@Override
public void write(JsonWriter out, Order value) throws IOException {
JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject();
obj.remove("additionalProperties");
// serialize additional properties
if (value.getAdditionalProperties() != null) {
for (Map.Entry<String, Object> entry : value.getAdditionalProperties().entrySet()) {
if (entry.getValue() instanceof String)
obj.addProperty(entry.getKey(), (String) entry.getValue());
else if (entry.getValue() instanceof Number)
obj.addProperty(entry.getKey(), (Number) entry.getValue());
else if (entry.getValue() instanceof Boolean)
obj.addProperty(entry.getKey(), (Boolean) entry.getValue());
else if (entry.getValue() instanceof Character)
obj.addProperty(entry.getKey(), (Character) entry.getValue());
else {
obj.add(entry.getKey(), gson.toJsonTree(entry.getValue()).getAsJsonObject());
}
}
}
elementAdapter.write(out, obj);
}
@Override
public Order read(JsonReader in) throws IOException {
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
JsonObject jsonObj = jsonElement.getAsJsonObject();
// store additional fields in the deserialized instance
Order instance = thisAdapter.fromJsonTree(jsonObj);
for (Map.Entry<String, JsonElement> entry : jsonObj.entrySet()) {
if (!openapiFields.contains(entry.getKey())) {
if (entry.getValue().isJsonPrimitive()) { // primitive type
if (entry.getValue().getAsJsonPrimitive().isString())
instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString());
else if (entry.getValue().getAsJsonPrimitive().isNumber())
instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber());
else if (entry.getValue().getAsJsonPrimitive().isBoolean())
instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean());
else
throw new IllegalArgumentException(String.format("The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString()));
} else if (entry.getValue().isJsonArray()) {
instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class));
} else { // JSON object
instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class));
}
}
}
return instance;
}
}.nullSafe();
}
}
/**
* Create an instance of Order given an JSON string
*
* @param jsonString JSON string
* @return An instance of Order
* @throws IOException if the JSON string is invalid with respect to Order
*/
public static Order fromJson(String jsonString) throws IOException {
return JSON.getGson().fromJson(jsonString, Order.class);
}
/**
* Convert an instance of Order to an JSON string
*
* @return JSON string
*/
public String toJson() {
return JSON.getGson().toJson(this);
}
}

View File

@ -0,0 +1,534 @@
/*
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.client.model;
import java.util.Objects;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.openapitools.client.model.Category;
import org.openapitools.client.model.Tag;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.openapitools.client.JSON;
/**
* A pet for sale in the pet store
*/
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen")
public class Pet {
public static final String SERIALIZED_NAME_ID = "id";
@SerializedName(SERIALIZED_NAME_ID)
private Long id;
public static final String SERIALIZED_NAME_CATEGORY = "category";
@SerializedName(SERIALIZED_NAME_CATEGORY)
private Category category;
public static final String SERIALIZED_NAME_NAME = "name";
@SerializedName(SERIALIZED_NAME_NAME)
private String name;
public static final String SERIALIZED_NAME_PHOTO_URLS = "photoUrls";
@SerializedName(SERIALIZED_NAME_PHOTO_URLS)
private List<String> photoUrls = new ArrayList<>();
public static final String SERIALIZED_NAME_TAGS = "tags";
@SerializedName(SERIALIZED_NAME_TAGS)
private List<Tag> tags;
/**
* pet status in the store
*/
@JsonAdapter(StatusEnum.Adapter.class)
public enum StatusEnum {
AVAILABLE("available"),
PENDING("pending"),
SOLD("sold");
private String value;
StatusEnum(String value) {
this.value = value;
}
public String getValue() {
return value;
}
@Override
public String toString() {
return String.valueOf(value);
}
public static StatusEnum fromValue(String value) {
for (StatusEnum b : StatusEnum.values()) {
if (b.value.equals(value)) {
return b;
}
}
throw new IllegalArgumentException("Unexpected value '" + value + "'");
}
public static class Adapter extends TypeAdapter<StatusEnum> {
@Override
public void write(final JsonWriter jsonWriter, final StatusEnum enumeration) throws IOException {
jsonWriter.value(enumeration.getValue());
}
@Override
public StatusEnum read(final JsonReader jsonReader) throws IOException {
String value = jsonReader.nextString();
return StatusEnum.fromValue(value);
}
}
}
public static final String SERIALIZED_NAME_STATUS = "status";
@Deprecated
@SerializedName(SERIALIZED_NAME_STATUS)
private StatusEnum status;
public Pet() {
}
public Pet id(Long id) {
this.id = id;
return this;
}
/**
* Get id
* @return id
**/
@javax.annotation.Nullable
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Pet category(Category category) {
this.category = category;
return this;
}
/**
* Get category
* @return category
**/
@javax.annotation.Nullable
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
public Pet name(String name) {
this.name = name;
return this;
}
/**
* Get name
* @return name
**/
@javax.annotation.Nonnull
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Pet photoUrls(List<String> photoUrls) {
this.photoUrls = photoUrls;
return this;
}
public Pet addPhotoUrlsItem(String photoUrlsItem) {
if (this.photoUrls == null) {
this.photoUrls = new ArrayList<>();
}
this.photoUrls.add(photoUrlsItem);
return this;
}
/**
* Get photoUrls
* @return photoUrls
**/
@javax.annotation.Nonnull
public List<String> getPhotoUrls() {
return photoUrls;
}
public void setPhotoUrls(List<String> photoUrls) {
this.photoUrls = photoUrls;
}
public Pet tags(List<Tag> tags) {
this.tags = tags;
return this;
}
public Pet addTagsItem(Tag tagsItem) {
if (this.tags == null) {
this.tags = new ArrayList<>();
}
this.tags.add(tagsItem);
return this;
}
/**
* Get tags
* @return tags
**/
@javax.annotation.Nullable
public List<Tag> getTags() {
return tags;
}
public void setTags(List<Tag> tags) {
this.tags = tags;
}
@Deprecated
public Pet status(StatusEnum status) {
this.status = status;
return this;
}
/**
* pet status in the store
* @return status
* @deprecated
**/
@Deprecated
@javax.annotation.Nullable
public StatusEnum getStatus() {
return status;
}
@Deprecated
public void setStatus(StatusEnum status) {
this.status = status;
}
/**
* A container for additional, undeclared properties.
* This is a holder for any undeclared properties as specified with
* the 'additionalProperties' keyword in the OAS document.
*/
private Map<String, Object> additionalProperties;
/**
* Set the additional (undeclared) property with the specified name and value.
* If the property does not already exist, create it otherwise replace it.
*
* @param key name of the property
* @param value value of the property
* @return the Pet instance itself
*/
public Pet putAdditionalProperty(String key, Object value) {
if (this.additionalProperties == null) {
this.additionalProperties = new HashMap<String, Object>();
}
this.additionalProperties.put(key, value);
return this;
}
/**
* Return the additional (undeclared) property.
*
* @return a map of objects
*/
public Map<String, Object> getAdditionalProperties() {
return additionalProperties;
}
/**
* Return the additional (undeclared) property with the specified name.
*
* @param key name of the property
* @return an object
*/
public Object getAdditionalProperty(String key) {
if (this.additionalProperties == null) {
return null;
}
return this.additionalProperties.get(key);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Pet pet = (Pet) o;
return Objects.equals(this.id, pet.id) &&
Objects.equals(this.category, pet.category) &&
Objects.equals(this.name, pet.name) &&
Objects.equals(this.photoUrls, pet.photoUrls) &&
Objects.equals(this.tags, pet.tags) &&
Objects.equals(this.status, pet.status)&&
Objects.equals(this.additionalProperties, pet.additionalProperties);
}
@Override
public int hashCode() {
return Objects.hash(id, category, name, photoUrls, tags, status, additionalProperties);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class Pet {\n");
sb.append(" id: ").append(toIndentedString(id)).append("\n");
sb.append(" category: ").append(toIndentedString(category)).append("\n");
sb.append(" name: ").append(toIndentedString(name)).append("\n");
sb.append(" photoUrls: ").append(toIndentedString(photoUrls)).append("\n");
sb.append(" tags: ").append(toIndentedString(tags)).append("\n");
sb.append(" status: ").append(toIndentedString(status)).append("\n");
sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
public static HashSet<String> openapiFields;
public static HashSet<String> openapiRequiredFields;
static {
// a set of all properties/fields (JSON key names)
openapiFields = new HashSet<String>();
openapiFields.add("id");
openapiFields.add("category");
openapiFields.add("name");
openapiFields.add("photoUrls");
openapiFields.add("tags");
openapiFields.add("status");
// a set of required properties/fields (JSON key names)
openapiRequiredFields = new HashSet<String>();
openapiRequiredFields.add("name");
openapiRequiredFields.add("photoUrls");
}
/**
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to Pet
*/
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!Pet.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in Pet is not found in the empty JSON string", Pet.openapiRequiredFields.toString()));
}
}
// check to make sure all required properties/fields are present in the JSON string
for (String requiredField : Pet.openapiRequiredFields) {
if (jsonElement.getAsJsonObject().get(requiredField) == null) {
throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString()));
}
}
JsonObject jsonObj = jsonElement.getAsJsonObject();
// validate the optional field `category`
if (jsonObj.get("category") != null && !jsonObj.get("category").isJsonNull()) {
Category.validateJsonElement(jsonObj.get("category"));
}
if (!jsonObj.get("name").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `name` to be a primitive type in the JSON string but got `%s`", jsonObj.get("name").toString()));
}
// ensure the required json array is present
if (jsonObj.get("photoUrls") == null) {
throw new IllegalArgumentException("Expected the field `linkedContent` to be an array in the JSON string but got `null`");
} else if (!jsonObj.get("photoUrls").isJsonArray()) {
throw new IllegalArgumentException(String.format("Expected the field `photoUrls` to be an array in the JSON string but got `%s`", jsonObj.get("photoUrls").toString()));
}
if (jsonObj.get("tags") != null && !jsonObj.get("tags").isJsonNull()) {
JsonArray jsonArraytags = jsonObj.getAsJsonArray("tags");
if (jsonArraytags != null) {
// ensure the json data is an array
if (!jsonObj.get("tags").isJsonArray()) {
throw new IllegalArgumentException(String.format("Expected the field `tags` to be an array in the JSON string but got `%s`", jsonObj.get("tags").toString()));
}
// validate the optional field `tags` (array)
for (int i = 0; i < jsonArraytags.size(); i++) {
Tag.validateJsonElement(jsonArraytags.get(i));
};
}
}
if ((jsonObj.get("status") != null && !jsonObj.get("status").isJsonNull()) && !jsonObj.get("status").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `status` to be a primitive type in the JSON string but got `%s`", jsonObj.get("status").toString()));
}
}
public static class CustomTypeAdapterFactory implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (!Pet.class.isAssignableFrom(type.getRawType())) {
return null; // this class only serializes 'Pet' and its subtypes
}
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
final TypeAdapter<Pet> thisAdapter
= gson.getDelegateAdapter(this, TypeToken.get(Pet.class));
return (TypeAdapter<T>) new TypeAdapter<Pet>() {
@Override
public void write(JsonWriter out, Pet value) throws IOException {
JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject();
obj.remove("additionalProperties");
// serialize additional properties
if (value.getAdditionalProperties() != null) {
for (Map.Entry<String, Object> entry : value.getAdditionalProperties().entrySet()) {
if (entry.getValue() instanceof String)
obj.addProperty(entry.getKey(), (String) entry.getValue());
else if (entry.getValue() instanceof Number)
obj.addProperty(entry.getKey(), (Number) entry.getValue());
else if (entry.getValue() instanceof Boolean)
obj.addProperty(entry.getKey(), (Boolean) entry.getValue());
else if (entry.getValue() instanceof Character)
obj.addProperty(entry.getKey(), (Character) entry.getValue());
else {
obj.add(entry.getKey(), gson.toJsonTree(entry.getValue()).getAsJsonObject());
}
}
}
elementAdapter.write(out, obj);
}
@Override
public Pet read(JsonReader in) throws IOException {
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
JsonObject jsonObj = jsonElement.getAsJsonObject();
// store additional fields in the deserialized instance
Pet instance = thisAdapter.fromJsonTree(jsonObj);
for (Map.Entry<String, JsonElement> entry : jsonObj.entrySet()) {
if (!openapiFields.contains(entry.getKey())) {
if (entry.getValue().isJsonPrimitive()) { // primitive type
if (entry.getValue().getAsJsonPrimitive().isString())
instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString());
else if (entry.getValue().getAsJsonPrimitive().isNumber())
instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber());
else if (entry.getValue().getAsJsonPrimitive().isBoolean())
instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean());
else
throw new IllegalArgumentException(String.format("The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString()));
} else if (entry.getValue().isJsonArray()) {
instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class));
} else { // JSON object
instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class));
}
}
}
return instance;
}
}.nullSafe();
}
}
/**
* Create an instance of Pet given an JSON string
*
* @param jsonString JSON string
* @return An instance of Pet
* @throws IOException if the JSON string is invalid with respect to Pet
*/
public static Pet fromJson(String jsonString) throws IOException {
return JSON.getGson().fromJson(jsonString, Pet.class);
}
/**
* Convert an instance of Pet to an JSON string
*
* @return JSON string
*/
public String toJson() {
return JSON.getGson().toJson(this);
}
}

View File

@ -0,0 +1,270 @@
/*
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.client.model;
import java.util.Objects;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapter;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import com.google.gson.JsonPrimitive;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonArray;
import com.google.gson.JsonParseException;
import org.openapitools.client.JSON;
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen")
public class StringOrInt extends AbstractOpenApiSchema {
private static final Logger log = Logger.getLogger(StringOrInt.class.getName());
public static class CustomTypeAdapterFactory implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (!StringOrInt.class.isAssignableFrom(type.getRawType())) {
return null; // this class only serializes 'StringOrInt' and its subtypes
}
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
final TypeAdapter<String> adapterString = gson.getDelegateAdapter(this, TypeToken.get(String.class));
final TypeAdapter<Integer> adapterInteger = gson.getDelegateAdapter(this, TypeToken.get(Integer.class));
return (TypeAdapter<T>) new TypeAdapter<StringOrInt>() {
@Override
public void write(JsonWriter out, StringOrInt value) throws IOException {
if (value == null || value.getActualInstance() == null) {
elementAdapter.write(out, null);
return;
}
// check if the actual instance is of the type `String`
if (value.getActualInstance() instanceof String) {
JsonPrimitive primitive = adapterString.toJsonTree((String)value.getActualInstance()).getAsJsonPrimitive();
elementAdapter.write(out, primitive);
return;
}
// check if the actual instance is of the type `Integer`
if (value.getActualInstance() instanceof Integer) {
JsonPrimitive primitive = adapterInteger.toJsonTree((Integer)value.getActualInstance()).getAsJsonPrimitive();
elementAdapter.write(out, primitive);
return;
}
throw new IOException("Failed to serialize as the type doesn't match anyOf schemae: Integer, String");
}
@Override
public StringOrInt read(JsonReader in) throws IOException {
Object deserialized = null;
JsonElement jsonElement = elementAdapter.read(in);
ArrayList<String> errorMessages = new ArrayList<>();
TypeAdapter actualAdapter = elementAdapter;
// deserialize String
try {
// validate the JSON object to see if any exception is thrown
if(!jsonElement.getAsJsonPrimitive().isString()) {
throw new IllegalArgumentException(String.format("Expected json element to be of type String in the JSON string but got `%s`", jsonElement.toString()));
}
actualAdapter = adapterString;
StringOrInt ret = new StringOrInt();
ret.setActualInstance(actualAdapter.fromJsonTree(jsonElement));
return ret;
} catch (Exception e) {
// deserialization failed, continue
errorMessages.add(String.format("Deserialization for String failed with `%s`.", e.getMessage()));
log.log(Level.FINER, "Input data does not match schema 'String'", e);
}
// deserialize Integer
try {
// validate the JSON object to see if any exception is thrown
if(!jsonElement.getAsJsonPrimitive().isNumber()) {
throw new IllegalArgumentException(String.format("Expected json element to be of type Number in the JSON string but got `%s`", jsonElement.toString()));
}
actualAdapter = adapterInteger;
StringOrInt ret = new StringOrInt();
ret.setActualInstance(actualAdapter.fromJsonTree(jsonElement));
return ret;
} catch (Exception e) {
// deserialization failed, continue
errorMessages.add(String.format("Deserialization for Integer failed with `%s`.", e.getMessage()));
log.log(Level.FINER, "Input data does not match schema 'Integer'", e);
}
throw new IOException(String.format("Failed deserialization for StringOrInt: no class matches result, expected at least 1. Detailed failure message for anyOf schemas: %s. JSON: %s", errorMessages, jsonElement.toString()));
}
}.nullSafe();
}
}
// store a list of schema names defined in anyOf
public static final Map<String, Class<?>> schemas = new HashMap<String, Class<?>>();
public StringOrInt() {
super("anyOf", Boolean.FALSE);
}
public StringOrInt(Integer o) {
super("anyOf", Boolean.FALSE);
setActualInstance(o);
}
public StringOrInt(String o) {
super("anyOf", Boolean.FALSE);
setActualInstance(o);
}
static {
schemas.put("String", String.class);
schemas.put("Integer", Integer.class);
}
@Override
public Map<String, Class<?>> getSchemas() {
return StringOrInt.schemas;
}
/**
* Set the instance that matches the anyOf child schema, check
* the instance parameter is valid against the anyOf child schemas:
* Integer, String
*
* It could be an instance of the 'anyOf' schemas.
*/
@Override
public void setActualInstance(Object instance) {
if (instance instanceof String) {
super.setActualInstance(instance);
return;
}
if (instance instanceof Integer) {
super.setActualInstance(instance);
return;
}
throw new RuntimeException("Invalid instance type. Must be Integer, String");
}
/**
* Get the actual instance, which can be the following:
* Integer, String
*
* @return The actual instance (Integer, String)
*/
@Override
public Object getActualInstance() {
return super.getActualInstance();
}
/**
* Get the actual instance of `String`. If the actual instance is not `String`,
* the ClassCastException will be thrown.
*
* @return The actual instance of `String`
* @throws ClassCastException if the instance is not `String`
*/
public String getString() throws ClassCastException {
return (String)super.getActualInstance();
}
/**
* Get the actual instance of `Integer`. If the actual instance is not `Integer`,
* the ClassCastException will be thrown.
*
* @return The actual instance of `Integer`
* @throws ClassCastException if the instance is not `Integer`
*/
public Integer getInteger() throws ClassCastException {
return (Integer)super.getActualInstance();
}
/**
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to StringOrInt
*/
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
// validate anyOf schemas one by one
ArrayList<String> errorMessages = new ArrayList<>();
// validate the json string with String
try {
if(!jsonElement.getAsJsonPrimitive().isString()) {
throw new IllegalArgumentException(String.format("Expected json element to be of type String in the JSON string but got `%s`", jsonElement.toString()));
}
return;
} catch (Exception e) {
errorMessages.add(String.format("Deserialization for String failed with `%s`.", e.getMessage()));
// continue to the next one
}
// validate the json string with Integer
try {
if(!jsonElement.getAsJsonPrimitive().isNumber()) {
throw new IllegalArgumentException(String.format("Expected json element to be of type Number in the JSON string but got `%s`", jsonElement.toString()));
}
return;
} catch (Exception e) {
errorMessages.add(String.format("Deserialization for Integer failed with `%s`.", e.getMessage()));
// continue to the next one
}
throw new IOException(String.format("The JSON string is invalid for StringOrInt with anyOf schemas: Integer, String. no class match the result, expected at least 1. Detailed failure message for anyOf schemas: %s. JSON: %s", errorMessages, jsonElement.toString()));
}
/**
* Create an instance of StringOrInt given an JSON string
*
* @param jsonString JSON string
* @return An instance of StringOrInt
* @throws IOException if the JSON string is invalid with respect to StringOrInt
*/
public static StringOrInt fromJson(String jsonString) throws IOException {
return JSON.getGson().fromJson(jsonString, StringOrInt.class);
}
/**
* Convert an instance of StringOrInt to an JSON string
*
* @return JSON string
*/
public String toJson() {
return JSON.getGson().toJson(this);
}
}

View File

@ -0,0 +1,312 @@
/*
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.client.model;
import java.util.Objects;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.util.Arrays;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.openapitools.client.JSON;
/**
* A tag for a pet
*/
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen")
public class Tag {
public static final String SERIALIZED_NAME_ID = "id";
@SerializedName(SERIALIZED_NAME_ID)
private Long id;
public static final String SERIALIZED_NAME_NAME = "name";
@SerializedName(SERIALIZED_NAME_NAME)
private String name;
public Tag() {
}
public Tag id(Long id) {
this.id = id;
return this;
}
/**
* Get id
* @return id
**/
@javax.annotation.Nullable
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Tag name(String name) {
this.name = name;
return this;
}
/**
* Get name
* @return name
**/
@javax.annotation.Nullable
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
/**
* A container for additional, undeclared properties.
* This is a holder for any undeclared properties as specified with
* the 'additionalProperties' keyword in the OAS document.
*/
private Map<String, Object> additionalProperties;
/**
* Set the additional (undeclared) property with the specified name and value.
* If the property does not already exist, create it otherwise replace it.
*
* @param key name of the property
* @param value value of the property
* @return the Tag instance itself
*/
public Tag putAdditionalProperty(String key, Object value) {
if (this.additionalProperties == null) {
this.additionalProperties = new HashMap<String, Object>();
}
this.additionalProperties.put(key, value);
return this;
}
/**
* Return the additional (undeclared) property.
*
* @return a map of objects
*/
public Map<String, Object> getAdditionalProperties() {
return additionalProperties;
}
/**
* Return the additional (undeclared) property with the specified name.
*
* @param key name of the property
* @return an object
*/
public Object getAdditionalProperty(String key) {
if (this.additionalProperties == null) {
return null;
}
return this.additionalProperties.get(key);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Tag tag = (Tag) o;
return Objects.equals(this.id, tag.id) &&
Objects.equals(this.name, tag.name)&&
Objects.equals(this.additionalProperties, tag.additionalProperties);
}
@Override
public int hashCode() {
return Objects.hash(id, name, additionalProperties);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class Tag {\n");
sb.append(" id: ").append(toIndentedString(id)).append("\n");
sb.append(" name: ").append(toIndentedString(name)).append("\n");
sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
public static HashSet<String> openapiFields;
public static HashSet<String> openapiRequiredFields;
static {
// a set of all properties/fields (JSON key names)
openapiFields = new HashSet<String>();
openapiFields.add("id");
openapiFields.add("name");
// a set of required properties/fields (JSON key names)
openapiRequiredFields = new HashSet<String>();
}
/**
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to Tag
*/
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!Tag.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in Tag is not found in the empty JSON string", Tag.openapiRequiredFields.toString()));
}
}
JsonObject jsonObj = jsonElement.getAsJsonObject();
if ((jsonObj.get("name") != null && !jsonObj.get("name").isJsonNull()) && !jsonObj.get("name").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `name` to be a primitive type in the JSON string but got `%s`", jsonObj.get("name").toString()));
}
}
public static class CustomTypeAdapterFactory implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (!Tag.class.isAssignableFrom(type.getRawType())) {
return null; // this class only serializes 'Tag' and its subtypes
}
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
final TypeAdapter<Tag> thisAdapter
= gson.getDelegateAdapter(this, TypeToken.get(Tag.class));
return (TypeAdapter<T>) new TypeAdapter<Tag>() {
@Override
public void write(JsonWriter out, Tag value) throws IOException {
JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject();
obj.remove("additionalProperties");
// serialize additional properties
if (value.getAdditionalProperties() != null) {
for (Map.Entry<String, Object> entry : value.getAdditionalProperties().entrySet()) {
if (entry.getValue() instanceof String)
obj.addProperty(entry.getKey(), (String) entry.getValue());
else if (entry.getValue() instanceof Number)
obj.addProperty(entry.getKey(), (Number) entry.getValue());
else if (entry.getValue() instanceof Boolean)
obj.addProperty(entry.getKey(), (Boolean) entry.getValue());
else if (entry.getValue() instanceof Character)
obj.addProperty(entry.getKey(), (Character) entry.getValue());
else {
obj.add(entry.getKey(), gson.toJsonTree(entry.getValue()).getAsJsonObject());
}
}
}
elementAdapter.write(out, obj);
}
@Override
public Tag read(JsonReader in) throws IOException {
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
JsonObject jsonObj = jsonElement.getAsJsonObject();
// store additional fields in the deserialized instance
Tag instance = thisAdapter.fromJsonTree(jsonObj);
for (Map.Entry<String, JsonElement> entry : jsonObj.entrySet()) {
if (!openapiFields.contains(entry.getKey())) {
if (entry.getValue().isJsonPrimitive()) { // primitive type
if (entry.getValue().getAsJsonPrimitive().isString())
instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString());
else if (entry.getValue().getAsJsonPrimitive().isNumber())
instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber());
else if (entry.getValue().getAsJsonPrimitive().isBoolean())
instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean());
else
throw new IllegalArgumentException(String.format("The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString()));
} else if (entry.getValue().isJsonArray()) {
instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class));
} else { // JSON object
instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class));
}
}
}
return instance;
}
}.nullSafe();
}
}
/**
* Create an instance of Tag given an JSON string
*
* @param jsonString JSON string
* @return An instance of Tag
* @throws IOException if the JSON string is invalid with respect to Tag
*/
public static Tag fromJson(String jsonString) throws IOException {
return JSON.getGson().fromJson(jsonString, Tag.class);
}
/**
* Convert an instance of Tag to an JSON string
*
* @return JSON string
*/
public String toJson() {
return JSON.getGson().toJson(this);
}
}

View File

@ -0,0 +1,495 @@
/*
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.client.model;
import java.util.Objects;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.util.Arrays;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.openapitools.client.JSON;
/**
* A User who is purchasing from the pet store
*/
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen")
public class User {
public static final String SERIALIZED_NAME_ID = "id";
@SerializedName(SERIALIZED_NAME_ID)
private Long id;
public static final String SERIALIZED_NAME_USERNAME = "username";
@SerializedName(SERIALIZED_NAME_USERNAME)
private String username;
public static final String SERIALIZED_NAME_FIRST_NAME = "firstName";
@SerializedName(SERIALIZED_NAME_FIRST_NAME)
private String firstName;
public static final String SERIALIZED_NAME_LAST_NAME = "lastName";
@SerializedName(SERIALIZED_NAME_LAST_NAME)
private String lastName;
public static final String SERIALIZED_NAME_EMAIL = "email";
@SerializedName(SERIALIZED_NAME_EMAIL)
private String email;
public static final String SERIALIZED_NAME_PASSWORD = "password";
@SerializedName(SERIALIZED_NAME_PASSWORD)
private String password;
public static final String SERIALIZED_NAME_PHONE = "phone";
@SerializedName(SERIALIZED_NAME_PHONE)
private String phone;
public static final String SERIALIZED_NAME_USER_STATUS = "userStatus";
@SerializedName(SERIALIZED_NAME_USER_STATUS)
private Integer userStatus;
public User() {
}
public User id(Long id) {
this.id = id;
return this;
}
/**
* Get id
* @return id
**/
@javax.annotation.Nullable
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public User username(String username) {
this.username = username;
return this;
}
/**
* Get username
* @return username
**/
@javax.annotation.Nullable
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public User firstName(String firstName) {
this.firstName = firstName;
return this;
}
/**
* Get firstName
* @return firstName
**/
@javax.annotation.Nullable
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public User lastName(String lastName) {
this.lastName = lastName;
return this;
}
/**
* Get lastName
* @return lastName
**/
@javax.annotation.Nullable
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public User email(String email) {
this.email = email;
return this;
}
/**
* Get email
* @return email
**/
@javax.annotation.Nullable
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public User password(String password) {
this.password = password;
return this;
}
/**
* Get password
* @return password
**/
@javax.annotation.Nullable
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public User phone(String phone) {
this.phone = phone;
return this;
}
/**
* Get phone
* @return phone
**/
@javax.annotation.Nullable
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public User userStatus(Integer userStatus) {
this.userStatus = userStatus;
return this;
}
/**
* User Status
* @return userStatus
**/
@javax.annotation.Nullable
public Integer getUserStatus() {
return userStatus;
}
public void setUserStatus(Integer userStatus) {
this.userStatus = userStatus;
}
/**
* A container for additional, undeclared properties.
* This is a holder for any undeclared properties as specified with
* the 'additionalProperties' keyword in the OAS document.
*/
private Map<String, Object> additionalProperties;
/**
* Set the additional (undeclared) property with the specified name and value.
* If the property does not already exist, create it otherwise replace it.
*
* @param key name of the property
* @param value value of the property
* @return the User instance itself
*/
public User putAdditionalProperty(String key, Object value) {
if (this.additionalProperties == null) {
this.additionalProperties = new HashMap<String, Object>();
}
this.additionalProperties.put(key, value);
return this;
}
/**
* Return the additional (undeclared) property.
*
* @return a map of objects
*/
public Map<String, Object> getAdditionalProperties() {
return additionalProperties;
}
/**
* Return the additional (undeclared) property with the specified name.
*
* @param key name of the property
* @return an object
*/
public Object getAdditionalProperty(String key) {
if (this.additionalProperties == null) {
return null;
}
return this.additionalProperties.get(key);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
User user = (User) o;
return Objects.equals(this.id, user.id) &&
Objects.equals(this.username, user.username) &&
Objects.equals(this.firstName, user.firstName) &&
Objects.equals(this.lastName, user.lastName) &&
Objects.equals(this.email, user.email) &&
Objects.equals(this.password, user.password) &&
Objects.equals(this.phone, user.phone) &&
Objects.equals(this.userStatus, user.userStatus)&&
Objects.equals(this.additionalProperties, user.additionalProperties);
}
@Override
public int hashCode() {
return Objects.hash(id, username, firstName, lastName, email, password, phone, userStatus, additionalProperties);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class User {\n");
sb.append(" id: ").append(toIndentedString(id)).append("\n");
sb.append(" username: ").append(toIndentedString(username)).append("\n");
sb.append(" firstName: ").append(toIndentedString(firstName)).append("\n");
sb.append(" lastName: ").append(toIndentedString(lastName)).append("\n");
sb.append(" email: ").append(toIndentedString(email)).append("\n");
sb.append(" password: ").append(toIndentedString(password)).append("\n");
sb.append(" phone: ").append(toIndentedString(phone)).append("\n");
sb.append(" userStatus: ").append(toIndentedString(userStatus)).append("\n");
sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
public static HashSet<String> openapiFields;
public static HashSet<String> openapiRequiredFields;
static {
// a set of all properties/fields (JSON key names)
openapiFields = new HashSet<String>();
openapiFields.add("id");
openapiFields.add("username");
openapiFields.add("firstName");
openapiFields.add("lastName");
openapiFields.add("email");
openapiFields.add("password");
openapiFields.add("phone");
openapiFields.add("userStatus");
// a set of required properties/fields (JSON key names)
openapiRequiredFields = new HashSet<String>();
}
/**
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to User
*/
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!User.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in User is not found in the empty JSON string", User.openapiRequiredFields.toString()));
}
}
JsonObject jsonObj = jsonElement.getAsJsonObject();
if ((jsonObj.get("username") != null && !jsonObj.get("username").isJsonNull()) && !jsonObj.get("username").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `username` to be a primitive type in the JSON string but got `%s`", jsonObj.get("username").toString()));
}
if ((jsonObj.get("firstName") != null && !jsonObj.get("firstName").isJsonNull()) && !jsonObj.get("firstName").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `firstName` to be a primitive type in the JSON string but got `%s`", jsonObj.get("firstName").toString()));
}
if ((jsonObj.get("lastName") != null && !jsonObj.get("lastName").isJsonNull()) && !jsonObj.get("lastName").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `lastName` to be a primitive type in the JSON string but got `%s`", jsonObj.get("lastName").toString()));
}
if ((jsonObj.get("email") != null && !jsonObj.get("email").isJsonNull()) && !jsonObj.get("email").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `email` to be a primitive type in the JSON string but got `%s`", jsonObj.get("email").toString()));
}
if ((jsonObj.get("password") != null && !jsonObj.get("password").isJsonNull()) && !jsonObj.get("password").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `password` to be a primitive type in the JSON string but got `%s`", jsonObj.get("password").toString()));
}
if ((jsonObj.get("phone") != null && !jsonObj.get("phone").isJsonNull()) && !jsonObj.get("phone").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `phone` to be a primitive type in the JSON string but got `%s`", jsonObj.get("phone").toString()));
}
}
public static class CustomTypeAdapterFactory implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (!User.class.isAssignableFrom(type.getRawType())) {
return null; // this class only serializes 'User' and its subtypes
}
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
final TypeAdapter<User> thisAdapter
= gson.getDelegateAdapter(this, TypeToken.get(User.class));
return (TypeAdapter<T>) new TypeAdapter<User>() {
@Override
public void write(JsonWriter out, User value) throws IOException {
JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject();
obj.remove("additionalProperties");
// serialize additional properties
if (value.getAdditionalProperties() != null) {
for (Map.Entry<String, Object> entry : value.getAdditionalProperties().entrySet()) {
if (entry.getValue() instanceof String)
obj.addProperty(entry.getKey(), (String) entry.getValue());
else if (entry.getValue() instanceof Number)
obj.addProperty(entry.getKey(), (Number) entry.getValue());
else if (entry.getValue() instanceof Boolean)
obj.addProperty(entry.getKey(), (Boolean) entry.getValue());
else if (entry.getValue() instanceof Character)
obj.addProperty(entry.getKey(), (Character) entry.getValue());
else {
obj.add(entry.getKey(), gson.toJsonTree(entry.getValue()).getAsJsonObject());
}
}
}
elementAdapter.write(out, obj);
}
@Override
public User read(JsonReader in) throws IOException {
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
JsonObject jsonObj = jsonElement.getAsJsonObject();
// store additional fields in the deserialized instance
User instance = thisAdapter.fromJsonTree(jsonObj);
for (Map.Entry<String, JsonElement> entry : jsonObj.entrySet()) {
if (!openapiFields.contains(entry.getKey())) {
if (entry.getValue().isJsonPrimitive()) { // primitive type
if (entry.getValue().getAsJsonPrimitive().isString())
instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString());
else if (entry.getValue().getAsJsonPrimitive().isNumber())
instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber());
else if (entry.getValue().getAsJsonPrimitive().isBoolean())
instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean());
else
throw new IllegalArgumentException(String.format("The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString()));
} else if (entry.getValue().isJsonArray()) {
instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class));
} else { // JSON object
instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class));
}
}
}
return instance;
}
}.nullSafe();
}
}
/**
* Create an instance of User given an JSON string
*
* @param jsonString JSON string
* @return An instance of User
* @throws IOException if the JSON string is invalid with respect to User
*/
public static User fromJson(String jsonString) throws IOException {
return JSON.getGson().fromJson(jsonString, User.class);
}
/**
* Convert an instance of User to an JSON string
*
* @return JSON string
*/
public String toJson() {
return JSON.getGson().toJson(this);
}
}

View File

@ -0,0 +1,520 @@
/*
* OpenAPI 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: \" \\
*
* OpenAPI spec version: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.client.api;
import static org.junit.jupiter.api.Assertions.*;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.*;
import org.openapitools.client.*;
import org.openapitools.client.ApiException;
import org.openapitools.client.auth.*;
import org.openapitools.client.model.*;
import org.openapitools.client.model.Pet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* API tests for PetApi
*/
public class PetApiTest {
private PetApi api = new PetApi();
private final Logger LOG = LoggerFactory.getLogger(PetApiTest.class);
// In the circle.yml file, /etc/host is configured with an entry to resolve petstore.swagger.io
// to 127.0.0.1
private static String basePath = "http://petstore.swagger.io:80/v2";
@BeforeEach
public void setup() {
// setup authentication
ApiKeyAuth apiKeyAuth = (ApiKeyAuth) api.getApiClient().getAuthentication("api_key");
apiKeyAuth.setApiKey("special-key");
api.getApiClient().setBasePath(basePath);
}
@Test
public void testApiClient() {
// the default api client is used
assertEquals(Configuration.getDefaultApiClient(), api.getApiClient());
assertNotNull(api.getApiClient());
assertEquals(basePath, api.getApiClient().getBasePath());
assertFalse(api.getApiClient().isDebugging());
ApiClient oldClient = api.getApiClient();
ApiClient newClient = new ApiClient();
newClient.setVerifyingSsl(true);
newClient.setBasePath("http://example.com");
newClient.setDebugging(true);
// set api client via constructor
api = new PetApi(newClient);
assertNotNull(api.getApiClient());
assertEquals("http://example.com", api.getApiClient().getBasePath());
assertTrue(api.getApiClient().isDebugging());
// set api client via setter method
api.setApiClient(oldClient);
assertNotNull(api.getApiClient());
assertEquals(basePath, api.getApiClient().getBasePath());
assertFalse(api.getApiClient().isDebugging());
}
@Test
public void testCreateAndGetPet() throws Exception {
Pet pet = createPet();
api.addPet(pet);
Pet fetched = api.getPetById(pet.getId());
assertPetMatches(pet, fetched);
api.deletePet(pet.getId(), null);
}
@Test
public void testCreateAndGetPetWithHttpInfo() throws Exception {
Pet pet = createPet();
api.addPetWithHttpInfo(pet);
ApiResponse<Pet> resp = api.getPetByIdWithHttpInfo(pet.getId());
assertEquals(200, resp.getStatusCode());
assertEquals("application/json", resp.getHeaders().get("Content-Type").get(0));
Pet fetched = resp.getData();
assertPetMatches(pet, fetched);
api.deletePet(pet.getId(), null);
}
@Test
public void testCreateAndGetPetAsync() throws Exception {
Pet pet = createPet();
api.addPet(pet);
// to store returned Pet or error message/exception
final Map<String, Object> result = new HashMap<String, Object>();
api.getPetByIdAsync(
pet.getId(),
new ApiCallback<Pet>() {
@Override
public void onFailure(
ApiException e,
int statusCode,
Map<String, List<String>> responseHeaders) {
result.put("error", e.getMessage());
}
@Override
public void onSuccess(
Pet pet, int statusCode, Map<String, List<String>> responseHeaders) {
result.put("pet", pet);
}
@Override
public void onUploadProgress(
long bytesWritten, long contentLength, boolean done) {
// empty
}
@Override
public void onDownloadProgress(
long bytesRead, long contentLength, boolean done) {
// empty
}
});
// wait for the asynchronous call to finish (at most 10 seconds)
final int maxTry = 10;
int tryCount = 1;
Pet fetched = null;
do {
if (tryCount > maxTry) fail("have not got result of getPetByIdAsync after 10 seconds");
Thread.sleep(1000);
tryCount += 1;
if (result.get("error") != null) fail((String) result.get("error"));
if (result.get("pet") != null) {
fetched = (Pet) result.get("pet");
break;
}
} while (result.isEmpty());
assertPetMatches(pet, fetched);
api.deletePet(pet.getId(), null);
}
@Test
public void testCreateAndGetPetAsyncInvalidID() throws Exception {
Pet pet = createPet();
api.addPet(pet);
// to store returned Pet or error message/exception
final Map<String, Object> result = new HashMap<String, Object>();
// test getting a nonexistent pet
result.clear();
api.getPetByIdAsync(
-10000L,
new ApiCallback<Pet>() {
@Override
public void onFailure(
ApiException e,
int statusCode,
Map<String, List<String>> responseHeaders) {
result.put("exception", e);
}
@Override
public void onSuccess(
Pet pet, int statusCode, Map<String, List<String>> responseHeaders) {
result.put("pet", pet);
}
@Override
public void onUploadProgress(
long bytesWritten, long contentLength, boolean done) {
// empty
}
@Override
public void onDownloadProgress(
long bytesRead, long contentLength, boolean done) {
// empty
}
});
// wait for the asynchronous call to finish (at most 10 seconds)
final int maxTry = 10;
int tryCount = 1;
Pet fetched = null;
ApiException exception = null;
do {
if (tryCount > maxTry) fail("have not got result of getPetByIdAsync after 10 seconds");
Thread.sleep(1000);
tryCount += 1;
if (result.get("pet") != null) fail("expected an error");
if (result.get("exception") != null) {
exception = (ApiException) result.get("exception");
break;
}
} while (result.isEmpty());
assertNotNull(exception);
assertEquals(404, exception.getCode());
String pattern = "^Message: Not Found\\RHTTP response code: 404\\RHTTP response body: .*\\RHTTP response headers: .*$";
assertTrue(exception.getMessage().matches(pattern));
assertEquals("application/json", exception.getResponseHeaders().get("Content-Type").get(0));
api.deletePet(pet.getId(), null);
}
@Test
public void testUpdatePet() throws Exception {
Pet pet = createPet();
api.addPet(pet);
pet.setName("programmer");
api.updatePet(pet);
Pet fetched = api.getPetById(pet.getId());
assertPetMatches(pet, fetched);
api.deletePet(pet.getId(), null);
}
@Test
public void testFindPetsByStatus() throws Exception {
assertEquals(basePath, api.getApiClient().getBasePath());
Pet pet = createPet();
api.addPet(pet);
pet.setName("programmer");
pet.setStatus(Pet.StatusEnum.PENDING);
api.updatePet(pet);
List<Pet> pets = api.findPetsByStatus(Arrays.asList("pending"));
assertNotNull(pets);
boolean found = false;
for (Pet fetched : pets) {
if (fetched.getId().equals(pet.getId())) {
found = true;
break;
}
}
assertTrue(found);
api.deletePet(pet.getId(), null);
}
@Test
@Disabled
public void testFindPetsByTags() throws Exception {
Pet pet = createPet();
pet.setName("monster");
pet.setStatus(Pet.StatusEnum.AVAILABLE);
List<org.openapitools.client.model.Tag> tags = new ArrayList<org.openapitools.client.model.Tag>();
org.openapitools.client.model.Tag tag1 = new org.openapitools.client.model.Tag();
tag1.setName("friendly");
tags.add(tag1);
pet.setTags(tags);
api.updatePet(pet);
List<Pet> pets = api.findPetsByTags((Arrays.asList("friendly")));
assertNotNull(pets);
boolean found = false;
for (Pet fetched : pets) {
if (fetched.getId().equals(pet.getId())) {
found = true;
break;
}
}
assertTrue(found);
api.deletePet(pet.getId(), null);
}
@Test
public void testUpdatePetWithForm() throws Exception {
Pet pet = createPet();
pet.setName("frank");
api.addPet(pet);
Pet fetched = api.getPetById(pet.getId());
api.updatePetWithForm(fetched.getId(), "furt", null);
Pet updated = api.getPetById(fetched.getId());
assertEquals(updated.getName(), "furt");
api.deletePet(pet.getId(), null);
}
@Test
@Disabled
public void testDeletePet() throws Exception {
Pet pet = createPet();
api.addPet(pet);
Pet fetched = api.getPetById(pet.getId());
api.deletePet(pet.getId(), null);
try {
fetched = api.getPetById(fetched.getId());
fail("expected an error");
} catch (ApiException e) {
LOG.info("Code: {}. Message: {}", e.getCode(), e.getMessage());
assertEquals(404, e.getCode());
}
}
@Test
public void testUploadFile() throws Exception {
Pet pet = createPet();
api.addPet(pet);
File file = new File("hello.txt");
BufferedWriter writer = new BufferedWriter(new FileWriter(file));
writer.write("Hello world!");
writer.close();
api.uploadFile(pet.getId(), "a test file", new File(file.getAbsolutePath()));
api.deletePet(pet.getId(), null);
}
@Test
public void testEqualsAndHashCode() {
Pet pet1 = new Pet();
Pet pet2 = new Pet();
assertTrue(pet1.equals(pet2));
assertTrue(pet2.equals(pet1));
assertTrue(pet1.hashCode() == pet2.hashCode());
assertTrue(pet1.equals(pet1));
assertTrue(pet1.hashCode() == pet1.hashCode());
pet2.setName("really-happy");
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()));
assertTrue(pet2.equals(pet2));
assertTrue(pet2.hashCode() == pet2.hashCode());
pet1.setName("really-happy");
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());
assertTrue(pet1.equals(pet1));
assertTrue(pet1.hashCode() == pet1.hashCode());
}
private Pet createPet() {
Pet pet = new Pet();
pet.setId(ThreadLocalRandom.current().nextLong(Long.MAX_VALUE));
pet.setName("gorilla");
Category category = new Category();
category.setName("really-happy");
pet.setCategory(category);
pet.setStatus(Pet.StatusEnum.AVAILABLE);
List<String> photos =
(Arrays.asList("http://foo.bar.com/1", "http://foo.bar.com/2"));
pet.setPhotoUrls(photos);
return pet;
}
private String serializeJson(Object o, ApiClient apiClient) {
return apiClient.getJSON().serialize(o);
}
private <T> T deserializeJson(String json, Type type, ApiClient apiClient) {
return (T) apiClient.getJSON().deserialize(json, type);
}
private void assertPetMatches(Pet expected, Pet actual) {
assertNotNull(actual);
assertEquals(expected.getId(), actual.getId());
assertNotNull(actual.getCategory());
assertEquals(expected.getCategory().getName(), actual.getCategory().getName());
}
/**
* Assert that the given upload/download progress list satisfies the following constraints:
*
* <p>- List is not empty - Byte count should be nondecreasing - The last element, and only the
* last element, should have done=true
*/
private void assertValidProgress(List<Progress> progressList) {
assertFalse(progressList.isEmpty());
Progress prev = null;
int index = 0;
for (Progress progress : progressList) {
if (prev != null) {
if (prev.done || prev.bytes > progress.bytes) {
fail("Progress list out of order at index " + index + ": " + progressList);
}
}
prev = progress;
index += 1;
}
if (!prev.done) {
fail("Last progress item should have done=true: " + progressList);
}
}
private static class TestApiCallback<T> implements ApiCallback<T> {
private final CountDownLatch latch;
private final ConcurrentLinkedQueue<Progress> uploadProgress =
new ConcurrentLinkedQueue<Progress>();
private final ConcurrentLinkedQueue<Progress> downloadProgress =
new ConcurrentLinkedQueue<Progress>();
private boolean done;
private boolean success;
private ApiException exception;
private T result;
public TestApiCallback(CountDownLatch latch) {
this.latch = latch;
this.done = false;
}
@Override
public void onFailure(
ApiException e, int statusCode, Map<String, List<String>> responseHeaders) {
exception = e;
this.done = true;
this.success = false;
latch.countDown();
}
@Override
public void onSuccess(T result, int statusCode, Map<String, List<String>> responseHeaders) {
this.result = result;
this.done = true;
this.success = true;
latch.countDown();
}
@Override
public void onUploadProgress(long bytesWritten, long contentLength, boolean done) {
uploadProgress.add(new Progress(bytesWritten, contentLength, done));
}
@Override
public void onDownloadProgress(long bytesRead, long contentLength, boolean done) {
downloadProgress.add(new Progress(bytesRead, contentLength, done));
}
public boolean isDone() {
return done;
}
public boolean isSuccess() {
return success;
}
public ApiException getException() {
return exception;
}
public T getResult() {
return result;
}
public List<Progress> getUploadProgress() {
return new ArrayList<Progress>(uploadProgress);
}
public List<Progress> getDownloadProgress() {
return new ArrayList<Progress>(downloadProgress);
}
}
private static class Progress {
public final long bytes;
public final long contentLength;
public final boolean done;
public Progress(long bytes, long contentLength, boolean done) {
this.bytes = bytes;
this.contentLength = contentLength;
this.done = done;
}
@Override
public String toString() {
return "<Progress " + bytes + " " + contentLength + " " + done + ">";
}
}
}

View File

@ -0,0 +1,89 @@
/*
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.client.api;
import org.openapitools.client.ApiException;
import org.openapitools.client.model.Order;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* API tests for StoreApi
*/
@Disabled
public class StoreApiTest {
private final StoreApi api = new StoreApi();
/**
* Delete purchase order by ID
*
* For valid response try integer IDs with value &lt; 1000. Anything above 1000 or nonintegers will generate API errors
*
* @throws ApiException if the Api call fails
*/
@Test
public void deleteOrderTest() throws ApiException {
String orderId = null;
api.deleteOrder(orderId);
// TODO: test validations
}
/**
* Returns pet inventories by status
*
* Returns a map of status codes to quantities
*
* @throws ApiException if the Api call fails
*/
@Test
public void getInventoryTest() throws ApiException {
Map<String, Integer> response = api.getInventory();
// TODO: test validations
}
/**
* Find purchase order by ID
*
* For valid response try integer IDs with value &lt;&#x3D; 5 or &gt; 10. Other values will generate exceptions
*
* @throws ApiException if the Api call fails
*/
@Test
public void getOrderByIdTest() throws ApiException {
Long orderId = null;
Order response = api.getOrderById(orderId);
// TODO: test validations
}
/**
* Place an order for a pet
*
*
*
* @throws ApiException if the Api call fails
*/
@Test
public void placeOrderTest() throws ApiException {
Order order = null;
Order response = api.placeOrder(order);
// TODO: test validations
}
}

View File

@ -0,0 +1,148 @@
/*
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.client.api;
import org.openapitools.client.ApiException;
import java.time.OffsetDateTime;
import org.openapitools.client.model.User;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* API tests for UserApi
*/
@Disabled
public class UserApiTest {
private final UserApi api = new UserApi();
/**
* Create user
*
* This can only be done by the logged in user.
*
* @throws ApiException if the Api call fails
*/
@Test
public void createUserTest() throws ApiException {
User user = null;
api.createUser(user);
// TODO: test validations
}
/**
* Creates list of users with given input array
*
*
*
* @throws ApiException if the Api call fails
*/
@Test
public void createUsersWithArrayInputTest() throws ApiException {
List<User> user = null;
api.createUsersWithArrayInput(user);
// TODO: test validations
}
/**
* Creates list of users with given input array
*
*
*
* @throws ApiException if the Api call fails
*/
@Test
public void createUsersWithListInputTest() throws ApiException {
List<User> user = null;
api.createUsersWithListInput(user);
// TODO: test validations
}
/**
* Delete user
*
* This can only be done by the logged in user.
*
* @throws ApiException if the Api call fails
*/
@Test
public void deleteUserTest() throws ApiException {
String username = null;
api.deleteUser(username);
// TODO: test validations
}
/**
* Get user by user name
*
*
*
* @throws ApiException if the Api call fails
*/
@Test
public void getUserByNameTest() throws ApiException {
String username = null;
User response = api.getUserByName(username);
// TODO: test validations
}
/**
* Logs user into the system
*
*
*
* @throws ApiException if the Api call fails
*/
@Test
public void loginUserTest() throws ApiException {
String username = null;
String password = null;
String response = api.loginUser(username, password);
// TODO: test validations
}
/**
* Logs out current logged in user session
*
*
*
* @throws ApiException if the Api call fails
*/
@Test
public void logoutUserTest() throws ApiException {
api.logoutUser();
// TODO: test validations
}
/**
* Updated user
*
* This can only be done by the logged in user.
*
* @throws ApiException if the Api call fails
*/
@Test
public void updateUserTest() throws ApiException {
String username = null;
User user = null;
api.updateUser(username, user);
// TODO: test validations
}
}

View File

@ -0,0 +1,56 @@
/*
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.client.model;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.util.Arrays;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
/**
* Model tests for Animal
*/
public class AnimalTest {
private final Animal model = new Animal();
/**
* Model tests for Animal
*/
@Test
public void testAnimal() {
// TODO: test Animal
}
/**
* Test the property 'className'
*/
@Test
public void classNameTest() {
// TODO: test className
}
/**
* Test the property 'color'
*/
@Test
public void colorTest() {
// TODO: test color
}
}

View File

@ -0,0 +1,33 @@
/*
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.client.model;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
/**
* Model tests for AnyOfStringOrInt
*/
public class AnyOfStringOrIntTest {
private final AnyOfStringOrInt model = new AnyOfStringOrInt();
/**
* Model tests for AnyOfStringOrInt
*/
@Test
public void testAnyOfStringOrInt() {
// TODO: test AnyOfStringOrInt
}
}

View File

@ -0,0 +1,65 @@
/*
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.client.model;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.util.Arrays;
import org.openapitools.client.model.Animal;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
/**
* Model tests for Cat
*/
public class CatTest {
private final Cat model = new Cat();
/**
* Model tests for Cat
*/
@Test
public void testCat() {
// TODO: test Cat
}
/**
* Test the property 'className'
*/
@Test
public void classNameTest() {
// TODO: test className
}
/**
* Test the property 'color'
*/
@Test
public void colorTest() {
// TODO: test color
}
/**
* Test the property 'declawed'
*/
@Test
public void declawedTest() {
// TODO: test declawed
}
}

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