diff --git a/bin/java-jaxrs-petstore-server-all.sh b/bin/java-jaxrs-petstore-server-all.sh index a2672b33d65..13347896882 100755 --- a/bin/java-jaxrs-petstore-server-all.sh +++ b/bin/java-jaxrs-petstore-server-all.sh @@ -17,3 +17,5 @@ ./bin/jaxrs-spec-petstore-server-interface.sh ./bin/jaxrs-spec-petstore-server.sh ./bin/jaxrs-usetags-petstore-server.sh + +echo " Please run ./bin/jaxrs-cxf-petstore-server-test-data.sh manually instead" diff --git a/bin/jaxrs-cxf-petstore-server-test-data.sh b/bin/jaxrs-cxf-petstore-server-test-data.sh new file mode 100755 index 00000000000..0be25cc5869 --- /dev/null +++ b/bin/jaxrs-cxf-petstore-server-test-data.sh @@ -0,0 +1,32 @@ +#!/bin/sh + +SCRIPT="$0" +echo "# START SCRIPT: $SCRIPT" + +while [ -h "$SCRIPT" ] ; do + ls=`ls -ld "$SCRIPT"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + SCRIPT="$link" + else + SCRIPT=`dirname "$SCRIPT"`/"$link" + fi +done + +if [ ! -d "${APP_DIR}" ]; then + APP_DIR=`dirname "$SCRIPT"`/.. + APP_DIR=`cd "${APP_DIR}"; pwd` +fi + +executable="./modules/openapi-generator-cli/target/openapi-generator-cli.jar" + +if [ ! -f "$executable" ] +then + mvn -B clean package +fi + +# if you've executed sbt assembly previously it will use that instead. +export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" +ags="generate --artifact-id cxf-test-data -t modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext -i modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -g jaxrs-cxf-extended -o samples/server/petstore/jaxrs-cxf-test-data -DhideGenerationTimestamp=true -DuseAnnotatedBasePath=true --generate-alias-as-model --additional-properties java8=true,generateSpringApplication=true,generateSpringBootApplication=true,generateOperationBody=true,loadTestDataFromFile=true $@" + +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/windows/jaxrs-cxf-cdi-petstore-server.bat b/bin/windows/jaxrs-cxf-cdi-petstore-server.bat new file mode 100644 index 00000000000..54e5b6768f7 --- /dev/null +++ b/bin/windows/jaxrs-cxf-cdi-petstore-server.bat @@ -0,0 +1,10 @@ +set executable=.\modules\openapi-generator-cli\target\openapi-generator-cli.jar + +If Not Exist %executable% ( + mvn clean package +) + +REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M -DloggerPath=conf\log4j.properties +set ags=generate -t modules\openapi-generator\src\main\resources\JavaJaxRS\cxf-cdi -i modules\openapi-generator\src\test\resources\2_0\petstore.yaml -g jaxrs-cxf-cdi -o samples\server\petstore\jaxrs-cxf-cdi -DhideGenerationTimestamp=true %* + +java %JAVA_OPTS% -jar %executable% %ags% diff --git a/bin/windows/jaxrs-cxf-client-petstore.bat b/bin/windows/jaxrs-cxf-client-petstore.bat index d9cd22b8eed..2fb0ad0a827 100755 --- a/bin/windows/jaxrs-cxf-client-petstore.bat +++ b/bin/windows/jaxrs-cxf-client-petstore.bat @@ -5,6 +5,6 @@ If Not Exist %executable% ( ) REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M -DloggerPath=conf/log4j.properties -set ags=generate --artifact-id "jaxrs-cxf-client-petstore-client" -i modules\openapi-generator\src\test\resources\2_0\petstore.yaml -g jaxrs-cxf-client -o samples\client\petstore\jaxrs-cxf-client +set ags=generate --artifact-id "jaxrs-cxf-client-petstore-client" -i modules\openapi-generator\src\test\resources\2_0\petstore.yaml -g jaxrs-cxf-client -o samples\client\petstore\jaxrs-cxf-client %* java %JAVA_OPTS% -jar %executable% %ags% diff --git a/bin/windows/jaxrs-cxf-petstore-server-annotated-base-path.bat b/bin/windows/jaxrs-cxf-petstore-server-annotated-base-path.bat new file mode 100644 index 00000000000..92fea43aaa8 --- /dev/null +++ b/bin/windows/jaxrs-cxf-petstore-server-annotated-base-path.bat @@ -0,0 +1,10 @@ +set executable=.\modules\openapi-generator-cli\target\openapi-generator-cli.jar + +If Not Exist %executable% ( + mvn clean package +) + +REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M -DloggerPath=conf/log4j.properties +set ags=generate --artifact-id cxf-annotated-basepath -t modules\openapi-generator\src\main\resources\JavaJaxRS\cxf -i modules\openapi-generator\src\test\resources\2_0\petstore.yaml -g jaxrs-cxf -o samples\server\petstore\jaxrs-cxf-annotated-base-path -DhideGenerationTimestamp=true,useAnnotatedBasePath=true --additional-properties serverPort=8082 %* + +java %JAVA_OPTS% -jar %executable% %ags% diff --git a/bin/windows/jaxrs-cxf-petstore-server-non-spring-application.bat b/bin/windows/jaxrs-cxf-petstore-server-non-spring-application.bat new file mode 100644 index 00000000000..9df7780484f --- /dev/null +++ b/bin/windows/jaxrs-cxf-petstore-server-non-spring-application.bat @@ -0,0 +1,10 @@ +set executable=.\modules\openapi-generator-cli\target\openapi-generator-cli.jar + +If Not Exist %executable% ( + mvn clean package +) + +REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M -DloggerPath=conf/log4j.properties +set ags=generate --artifact-id cxf-server-non-spring -t modules\openapi-generator\src\main\resources\JavaJaxRS\cxf -i modules\openapi-generator\src\test\resources\2_0\petstore.yaml -g jaxrs-cxf -o samples\server\petstore\jaxrs-cxf-non-spring-app -DhideGenerationTimestamp=true,generateNonSpringApplication=true --additional-properties serverPort=8082 %* + +java %JAVA_OPTS% -jar %executable% %ags% diff --git a/bin/windows/jaxrs-cxf-petstore-server-test-data.bat b/bin/windows/jaxrs-cxf-petstore-server-test-data.bat new file mode 100644 index 00000000000..47c249ce0cf --- /dev/null +++ b/bin/windows/jaxrs-cxf-petstore-server-test-data.bat @@ -0,0 +1,10 @@ +set executable=.\modules\openapi-generator-cli\target\openapi-generator-cli.jar + +If Not Exist %executable% ( + mvn clean package +) + +REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M -DloggerPath=conf/log4j.properties +set ags=generate --artifact-id cxf-test-data -t modules\openapi-generator\src\main\resources\JavaJaxRS\cxf-ext -i modules\openapi-generator\src\test\resources\2_0\petstore-with-fake-endpoints-models-for-testing.yaml -g jaxrs-cxf-extended -o samples\server\petstore\jaxrs-cxf-test-data -DhideGenerationTimestamp=true -DuseAnnotatedBasePath=true --generate-alias-as-model --additional-properties java8=true,generateSpringApplication=true,generateSpringBootApplication=true,generateOperationBody=true,loadTestDataFromFile=true %* + +java %JAVA_OPTS% -jar %executable% %ags% diff --git a/bin/windows/jaxrs-cxf-petstore-server.bat b/bin/windows/jaxrs-cxf-petstore-server.bat index 354542bb931..d64116025f9 100644 --- a/bin/windows/jaxrs-cxf-petstore-server.bat +++ b/bin/windows/jaxrs-cxf-petstore-server.bat @@ -5,6 +5,6 @@ If Not Exist %executable% ( ) REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M -DloggerPath=conf/log4j.properties -set ags=generate -t modules\openapi-generator\src\main\resources\JavaJaxRS\cxf -i modules\openapi-generator\src\test\resources\2_0\petstore-with-fake-endpoints-models-for-testing.yaml -g jaxrs-cxf -o samples\server\petstore\jaxrs-cxf -DhideGenerationTimestamp=true +set ags=generate -t modules\openapi-generator\src\main\resources\JavaJaxRS\cxf -i modules\openapi-generator\src\test\resources\2_0\petstore-with-fake-endpoints-models-for-testing.yaml -g jaxrs-cxf -o samples\server\petstore\jaxrs-cxf -DhideGenerationTimestamp=true %* java %JAVA_OPTS% -jar %executable% %ags% diff --git a/docs/generators.md b/docs/generators.md index 588bf946ca5..909af11d775 100644 --- a/docs/generators.md +++ b/docs/generators.md @@ -83,6 +83,7 @@ The following generators are available: - [java-vertx](generators/java-vertx.md) - [jaxrs-cxf](generators/jaxrs-cxf.md) - [jaxrs-cxf-cdi](generators/jaxrs-cxf-cdi.md) + - [jaxrs-cxf-extended](generators/jaxrs-cxf-extended.md) - [jaxrs-jersey](generators/jaxrs-jersey.md) - [jaxrs-resteasy](generators/jaxrs-resteasy.md) - [jaxrs-resteasy-eap](generators/jaxrs-resteasy-eap.md) diff --git a/docs/generators/jaxrs-cxf-extended.md b/docs/generators/jaxrs-cxf-extended.md new file mode 100644 index 00000000000..8e63809ff49 --- /dev/null +++ b/docs/generators/jaxrs-cxf-extended.md @@ -0,0 +1,70 @@ + +--- +id: generator-opts-server-jaxrs-cxf-extended +title: Config Options for jaxrs-cxf-extended +sidebar_label: jaxrs-cxf-extended +--- + +| Option | Description | Values | Default | +| ------ | ----------- | ------ | ------- | +|sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| +|allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| +|prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| +|modelPackage|package for generated models| |null| +|apiPackage|package for generated api classes| |null| +|invokerPackage|root package for generated code| |null| +|groupId|groupId in generated pom.xml| |null| +|artifactId|artifactId in generated pom.xml| |null| +|artifactVersion|artifact version in generated pom.xml| |null| +|artifactUrl|artifact URL in generated pom.xml| |null| +|artifactDescription|artifact description in generated pom.xml| |null| +|scmConnection|SCM connection in generated pom.xml| |null| +|scmDeveloperConnection|SCM developer connection in generated pom.xml| |null| +|scmUrl|SCM URL in generated pom.xml| |null| +|developerName|developer name in generated pom.xml| |null| +|developerEmail|developer email in generated pom.xml| |null| +|developerOrganization|developer organization in generated pom.xml| |null| +|developerOrganizationUrl|developer organization URL in generated pom.xml| |null| +|licenseName|The name of the license| |null| +|licenseUrl|The URL of the license| |null| +|sourceFolder|source folder for generated code| |null| +|serializableModel|boolean - toggle "implements Serializable" for generated models| |false| +|bigDecimalAsString|Treat BigDecimal values as Strings to avoid precision loss.| |false| +|fullJavaUtil|whether to use fully qualified name for classes under java.util. This option only works for Java API client| |false| +|hideGenerationTimestamp|hides the timestamp when files were generated| |null| +|withXml|whether to include support for application/xml content type and include XML annotations in the model (works with libraries that provide support for JSON and XML)| |false| +|dateLibrary|Option. Date library to use|
**joda**
Joda (for legacy app only)
**legacy**
Legacy java.util.Date (if you really have a good reason not to use threetenbp
**java8-localdatetime**
Java 8 using LocalDateTime (for legacy app only)
**java8**
Java 8 native JSR310 (preferred for jdk 1.8+) - note: this also sets "java8" to true
**threetenbp**
Backport of JSR310 (preferred for jdk < 1.8)
|null| +|java8|Option. Use Java8 classes instead of third party equivalents|
**true**
Use Java 8 classes such as Base64
**false**
Various third party libraries as needed
|null| +|disableHtmlEscaping|Disable HTML escaping of JSON strings when using gson (needed to avoid problems with byte[] fields)| |false| +|booleanGetterPrefix|Set booleanGetterPrefix (default value 'get')| |null| +|parentGroupId|parent groupId in generated pom N.B. parentGroupId, parentArtifactId and parentVersion must all be specified for any of them to take effect| |null| +|parentArtifactId|parent artifactId in generated pom N.B. parentGroupId, parentArtifactId and parentVersion must all be specified for any of them to take effect| |null| +|parentVersion|parent version in generated pom N.B. parentGroupId, parentArtifactId and parentVersion must all be specified for any of them to take effect| |null| +|snapshotVersion|Uses a SNAPSHOT version.| |null| +|implFolder|folder for generated implementation code| |null| +|title|a title describing the application| |null| +|useBeanValidation|Use BeanValidation API annotations| |true| +|serverPort|The port on which the server should be started| |null| +|generateSpringApplication|Generate Spring application| |false| +|useSpringAnnotationConfig|Use Spring Annotation Config| |false| +|useSwaggerFeature|Use Swagger Feature| |false| +|useSwaggerUI|Use Swagger UI| |false| +|useWadlFeature|Use WADL Feature| |false| +|useMultipartFeature|Use Multipart Feature| |false| +|useGzipFeature|Use Gzip Feature| |false| +|useGzipFeatureForTests|Use Gzip Feature for tests| |false| +|useBeanValidationFeature|Use BeanValidation Feature| |false| +|useLoggingFeature|Use Logging Feature| |false| +|useLoggingFeatureForTests|Use Logging Feature for tests| |false| +|generateSpringBootApplication|Generate Spring Boot application| |false| +|generateJbossDeploymentDescriptor|Generate Jboss Deployment Descriptor| |false| +|addConsumesProducesJson|Add @Consumes/@Produces Json to API interface| |false| +|useAnnotatedBasePath|Use @Path annotations for basePath| |false| +|generateNonSpringApplication|Generate non-Spring application| |false| +|useGenericResponse|Use generic response| |false| +|supportMultipleSpringServices|Support generation of Spring services from multiple specifications| |false| +|generateOperationBody|Generate fully functional operation bodies| |false| +|loadTestDataFromFile|Load test data from a generated JSON file| |false| +|testDataFile|JSON file to contain generated test data| |null| +|testDataControlFile|JSON file to control test data generation| |null| diff --git a/modules/openapi-generator/pom.xml b/modules/openapi-generator/pom.xml index 85ab4b5aca8..33e389bbcf7 100644 --- a/modules/openapi-generator/pom.xml +++ b/modules/openapi-generator/pom.xml @@ -196,6 +196,9 @@ 1.3.0 26.0-jre + 1.0.2 + 2.9.5 + 2.6.4 @@ -278,6 +281,26 @@ 2.23.0 test + + com.github.mifmif + generex + ${generex-version} + + + com.fasterxml.jackson.datatype + jackson-datatype-jsr310 + ${jackson-version} + + + com.fasterxml.jackson.datatype + jackson-datatype-joda + ${jackson-version} + + + com.github.joschi.jackson + jackson-datatype-threetenbp + ${jackson-threetenbp-version} + diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java index 1528a064da2..e973ce6329e 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java @@ -1875,7 +1875,6 @@ public class DefaultCodegen implements CodegenConfig { return camelize(toVarName(name)); } - /** * Convert OAS Property object to Codegen Property object * @@ -2217,7 +2216,6 @@ public class DefaultCodegen implements CodegenConfig { return currentProperty == null ? new HashMap() : currentProperty.allowableValues; } - /** * Update datatypeWithEnum for array container * @@ -2881,7 +2879,6 @@ public class DefaultCodegen implements CodegenConfig { codegenParameter.isContainer = true; codegenParameter.isListContainer = true; - // recursively add import while (codegenProperty != null) { imports.add(codegenProperty.baseType); @@ -3095,7 +3092,7 @@ public class DefaultCodegen implements CodegenConfig { codegenParameter.paramName = "UNKNOWN_PARAMETER_NAME"; } - // set the parameter excample value + // set the parameter example value // should be overridden by lang codegen setParameterExampleValue(codegenParameter, parameter); @@ -3309,8 +3306,8 @@ public class DefaultCodegen implements CodegenConfig { Header header = ModelUtils.getReferencedHeader(this.openAPI, headerEntry.getValue()); Schema schema; - if(header.getSchema() == null) { - LOGGER.warn("No schema defined for Header '" + headerEntry.getKey() +"', using a String schema"); + if (header.getSchema() == null) { + LOGGER.warn("No schema defined for Header '" + headerEntry.getKey() + "', using a String schema"); schema = new StringSchema(); } else { schema = header.getSchema(); @@ -3374,7 +3371,6 @@ public class DefaultCodegen implements CodegenConfig { co.baseName = tag; } - private void addParentContainer(CodegenModel model, String name, Schema schema) { final CodegenProperty property = fromProperty(name, schema); addImport(model, property.complexType); @@ -3770,7 +3766,6 @@ public class DefaultCodegen implements CodegenConfig { this.docExtension = userDocExtension; } - /** * Set HTTP user agent. * @@ -3976,7 +3971,6 @@ public class DefaultCodegen implements CodegenConfig { } } - /** * Update codegen property's enum by adding "enumVars" (with name and value) * @@ -4029,7 +4023,7 @@ public class DefaultCodegen implements CodegenConfig { } // if "x-enum-varnames" or "x-enum-descriptions" defined, update varnames Map extensions = var.mostInnerItems != null ? var.mostInnerItems.getVendorExtensions() : var.getVendorExtensions(); - if(referencedSchema.isPresent()) { + if (referencedSchema.isPresent()) { extensions = referencedSchema.get().getExtensions(); } updateEnumVarsWithExtensions(enumVars, extensions); @@ -4039,7 +4033,7 @@ public class DefaultCodegen implements CodegenConfig { if (var.defaultValue != null) { String enumName = null; final String enumDefaultValue; - if("string".equalsIgnoreCase(dataType)) { + if ("string".equalsIgnoreCase(dataType)) { enumDefaultValue = toEnumValue(var.defaultValue, dataType); } else { enumDefaultValue = var.defaultValue; diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultGenerator.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultGenerator.java index 3a791f5e1d7..41d8c6daa5b 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultGenerator.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultGenerator.java @@ -153,7 +153,6 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { generateApiTests = GeneratorProperties.getProperty(CodegenConstants.API_TESTS) != null ? Boolean.valueOf(GeneratorProperties.getProperty(CodegenConstants.API_TESTS)) : getGeneratorPropertyDefaultSwitch(CodegenConstants.API_TESTS, true); generateApiDocumentation = GeneratorProperties.getProperty(CodegenConstants.API_DOCS) != null ? Boolean.valueOf(GeneratorProperties.getProperty(CodegenConstants.API_DOCS)) : getGeneratorPropertyDefaultSwitch(CodegenConstants.API_DOCS, true); - // Additional properties added for tests to exclude references in project related files config.additionalProperties().put(CodegenConstants.GENERATE_API_TESTS, generateApiTests); config.additionalProperties().put(CodegenConstants.GENERATE_MODEL_TESTS, generateModelTests); @@ -627,7 +626,6 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { } } - if (generateApiDocumentation) { // to generate api documentation files for (String templateName : config.apiDocTemplateFiles().keySet()) { @@ -678,7 +676,9 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { if (!of.isDirectory()) { of.mkdirs(); } - String outputFilename = outputFolder + File.separator + support.destinationFilename.replace('/', File.separatorChar); + String outputFilename = new File(support.destinationFilename).isAbsolute() // split + ? support.destinationFilename + : outputFolder + File.separator + support.destinationFilename.replace('/', File.separatorChar); if (!config.shouldOverwrite(outputFilename)) { LOGGER.info("Skipped overwriting " + outputFilename); continue; @@ -910,7 +910,6 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { return files; } - protected File processTemplateToFile(Map templateData, String templateName, String outputFilename) throws IOException { String adjustedOutputFilename = outputFilename.replaceAll("//", "/").replace('/', File.separatorChar); if (ignoreProcessor.allowsFile(new File(adjustedOutputFilename))) { @@ -1059,7 +1058,6 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { return parameter.getName() + ":" + parameter.getIn(); } - private Map processOperations(CodegenConfig config, String tag, List ops, List allModels) { Map operations = new HashMap(); Map objs = new HashMap(); @@ -1125,7 +1123,6 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { return operations; } - private Map processModels(CodegenConfig config, Map definitions) { Map objs = new HashMap(); objs.put("package", config.modelPackage()); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractJavaCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractJavaCodegen.java index 438cb8cae20..5d21576e688 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractJavaCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractJavaCodegen.java @@ -85,7 +85,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code protected boolean serializeBigDecimalAsString = false; protected String apiDocPath = "docs/"; protected String modelDocPath = "docs/"; - protected boolean supportJava6= false; + protected boolean supportJava6 = false; protected boolean disableHtmlEscaping = false; protected String booleanGetterPrefix = BOOLEAN_GETTER_PREFIX_DEFAULT; protected boolean useNullForUnknownEnumValue = false; @@ -187,7 +187,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code cliOptions.add(CliOption.newBoolean(DISABLE_HTML_ESCAPING, "Disable HTML escaping of JSON strings when using gson (needed to avoid problems with byte[] fields)")); cliOptions.add(CliOption.newString(BOOLEAN_GETTER_PREFIX, "Set booleanGetterPrefix (default value '" + BOOLEAN_GETTER_PREFIX_DEFAULT + "')")); - + cliOptions.add(CliOption.newString(CodegenConstants.PARENT_GROUP_ID, CodegenConstants.PARENT_GROUP_ID_DESC)); cliOptions.add(CliOption.newString(CodegenConstants.PARENT_ARTIFACT_ID, CodegenConstants.PARENT_ARTIFACT_ID_DESC)); cliOptions.add(CliOption.newString(CodegenConstants.PARENT_VERSION, CodegenConstants.PARENT_VERSION_DESC)); @@ -226,16 +226,16 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code this.setInvokerPackage((String) additionalProperties.get(CodegenConstants.INVOKER_PACKAGE)); } else if (additionalProperties.containsKey(CodegenConstants.API_PACKAGE)) { // guess from api package - String derviedInvokerPackage = deriveInvokerPackageName((String) additionalProperties.get(CodegenConstants.API_PACKAGE)); - this.additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, derviedInvokerPackage); + String derivedInvokerPackage = deriveInvokerPackageName((String) additionalProperties.get(CodegenConstants.API_PACKAGE)); + this.additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, derivedInvokerPackage); this.setInvokerPackage((String) additionalProperties.get(CodegenConstants.INVOKER_PACKAGE)); - LOGGER.info("Invoker Package Name, originally not set, is now dervied from api package name: " + derviedInvokerPackage); + LOGGER.info("Invoker Package Name, originally not set, is now derived from api package name: " + derivedInvokerPackage); } else if (additionalProperties.containsKey(CodegenConstants.MODEL_PACKAGE)) { // guess from model package - String derviedInvokerPackage = deriveInvokerPackageName((String) additionalProperties.get(CodegenConstants.MODEL_PACKAGE)); - this.additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, derviedInvokerPackage); + String derivedInvokerPackage = deriveInvokerPackageName((String) additionalProperties.get(CodegenConstants.MODEL_PACKAGE)); + this.additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, derivedInvokerPackage); this.setInvokerPackage((String) additionalProperties.get(CodegenConstants.INVOKER_PACKAGE)); - LOGGER.info("Invoker Package Name, originally not set, is now dervied from model package name: " + derviedInvokerPackage); + LOGGER.info("Invoker Package Name, originally not set, is now derived from model package name: " + derivedInvokerPackage); } else { //not set, use default to be passed to template additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage); @@ -380,19 +380,19 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code this.setWithXml(Boolean.valueOf(additionalProperties.get(WITH_XML).toString())); } additionalProperties.put(WITH_XML, withXml); - + if (additionalProperties.containsKey(CodegenConstants.PARENT_GROUP_ID)) { this.setParentGroupId((String) additionalProperties.get(CodegenConstants.PARENT_GROUP_ID)); } - + if (additionalProperties.containsKey(CodegenConstants.PARENT_ARTIFACT_ID)) { this.setParentArtifactId((String) additionalProperties.get(CodegenConstants.PARENT_ARTIFACT_ID)); } - + if (additionalProperties.containsKey(CodegenConstants.PARENT_VERSION)) { this.setParentVersion((String) additionalProperties.get(CodegenConstants.PARENT_VERSION)); } - + if (!StringUtils.isEmpty(parentGroupId) && !StringUtils.isEmpty(parentArtifactId) && !StringUtils.isEmpty(parentVersion)) { additionalProperties.put("parentOverridden", true); } @@ -617,7 +617,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code } // If name contains special chars -> replace them. - if ((((CharSequence) name).chars().anyMatch(character -> specialCharReplacements.keySet().contains( "" + ((char) character))))) { + if ((((CharSequence) name).chars().anyMatch(character -> specialCharReplacements.keySet().contains("" + ((char) character))))) { List allowedCharacters = new ArrayList<>(); allowedCharacters.add("_"); allowedCharacters.add("$"); @@ -1356,7 +1356,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code * * @return API version */ - private String getVersionFromSpecification () { + private String getVersionFromSpecification() { if (this.openAPI != null && this.openAPI.getInfo() != null) { return this.openAPI.getInfo().getVersion(); } else { @@ -1370,7 +1370,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code * @param version * @return SNAPSHOT version */ - private String buildSnapshotVersion (String version) { + private String buildSnapshotVersion(String version) { return version + "-" + "SNAPSHOT"; } @@ -1445,7 +1445,6 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code } - @Override public void postProcessFile(File file, String fileType) { if (file == null) { diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaCXFExtServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaCXFExtServerCodegen.java new file mode 100644 index 00000000000..972197030b8 --- /dev/null +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaCXFExtServerCodegen.java @@ -0,0 +1,1413 @@ +/* + * Copyright 2019 OpenAPI-Generator Contributors (https://openapi-generator.tech) + * Copyright 2019 SmartBear Software + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openapitools.codegen.languages; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.math.BigDecimal; +import java.text.DateFormat; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.Collection; +import java.util.Date; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.util.TimeZone; +import java.util.TreeSet; + +import org.apache.commons.lang3.StringEscapeUtils; +import org.apache.commons.lang3.StringUtils; +import org.openapitools.codegen.CliOption; +import org.openapitools.codegen.CodegenConstants; +import org.openapitools.codegen.CodegenModel; +import org.openapitools.codegen.CodegenOperation; +import org.openapitools.codegen.CodegenParameter; +import org.openapitools.codegen.CodegenProperty; +import org.openapitools.codegen.SupportingFile; +import org.openapitools.codegen.languages.features.CXFExtServerFeatures; +import org.openapitools.codegen.utils.JsonCache; +import org.openapitools.codegen.utils.ModelUtils; +import org.openapitools.codegen.utils.JsonCache.CacheException; +import org.openapitools.codegen.utils.JsonCache.Root.MergePolicy; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.fasterxml.jackson.core.JsonPointer; +import com.fasterxml.jackson.databind.node.JsonNodeFactory; +import com.mifmif.common.regex.Generex; + +import io.swagger.v3.oas.models.media.Schema; + +/** + * An Apache CXF-based JAX-RS server with extended capabilities. + * + * @author Adrian Price, TIBCO Software Inc. + */ +public class JavaCXFExtServerCodegen extends JavaCXFServerCodegen implements CXFExtServerFeatures { + class CodegenVariable { + CodegenVariable parent; + String name; + String dataFormat; + String dataType; + String enumName; + Map allowableValues; + boolean isArray; + boolean isContainer; + boolean isListContainer; + boolean isMapContainer; + boolean isPrimitiveType; + CodegenVariable items; + Integer minItems; + int itemCount = 1; + String minimum; + String maximum; + boolean exclusiveMinimum; + boolean exclusiveMaximum; + Integer minLength; + Integer maxLength; + String pattern; + String setter; + String testDataPath; + int index; + Map vendorExtensions; + + private CodegenVariable() { + vendorExtensions = new HashMap<>(); + } + + private CodegenVariable(CodegenVariable parent, CodegenOperation op, String testDataPath, + Map models) { + + name = "response"; + dataFormat = null;// op.dataFormat; + dataType = op.returnType; + enumName = null;// op.enumName; + allowableValues = null;// op.allowableValues; + isContainer = op.isListContainer || op.isMapContainer; + isListContainer = op.isListContainer; + isMapContainer = op.isMapContainer; + isPrimitiveType = op.returnTypeIsPrimitive; + minItems = null;// op.minItems; + minimum = null;// op.minimum; + maximum = null;// op.maximum; + exclusiveMinimum = false;// op.exclusiveMinimum; + exclusiveMaximum = false;// op.exclusiveMaximum; + minLength = null;// op.minLength; + maxLength = null;// op.maxLength; + pattern = null;// op.pattern; + setter = null;// op.getSetter(); + vendorExtensions = op.vendorExtensions; + init(parent, testDataPath, models); + + if (op.isListContainer || op.isMapContainer) { + items = new CodegenVariable(); + items.dataType = op.returnBaseType; + items.isPrimitiveType = op.returnTypeIsPrimitive; + items.name = "item"; + // TODO: populate other fields? + + items.init(this, testDataPath, models); + } + } + + private CodegenVariable(CodegenVariable parent, CodegenParameter param, String testDataPath, + Map models) { + + name = param.paramName; + dataFormat = param.dataFormat; + dataType = param.dataType; + enumName = param.enumName; + allowableValues = param.allowableValues; + isContainer = param.isContainer; + isListContainer = param.isListContainer; + isMapContainer = param.isMapContainer; + isPrimitiveType = param.isPrimitiveType; + minItems = param.minItems; + minimum = param.minimum; + maximum = param.maximum; + exclusiveMinimum = param.exclusiveMinimum; + exclusiveMaximum = param.exclusiveMaximum; + minLength = param.minLength; + maxLength = param.maxLength; + pattern = param.pattern; + setter = null; + vendorExtensions = param.vendorExtensions; + init(parent, testDataPath, models); + + items = param.items == null ? null : new CodegenVariable(this, param.items, null, models); + } + + private CodegenVariable(CodegenVariable parent, CodegenProperty prop, String testDataPath, + Map models) { + + name = prop.name; + dataFormat = prop.dataFormat; + dataType = prop.dataType; + enumName = prop.enumName; + allowableValues = prop.allowableValues; + isContainer = prop.isContainer; + isListContainer = prop.isListContainer; + isMapContainer = prop.isMapContainer; + isPrimitiveType = prop.isPrimitiveType; + minItems = prop.minItems; + minimum = prop.minimum; + maximum = prop.maximum; + exclusiveMinimum = prop.exclusiveMinimum; + exclusiveMaximum = prop.exclusiveMaximum; + minLength = prop.minLength; + maxLength = prop.maxLength; + pattern = prop.pattern; + setter = prop.getSetter(); + vendorExtensions = prop.vendorExtensions; + init(parent, testDataPath, models); + + items = prop.items == null ? null : new CodegenVariable(this, prop.items, null, models); + } + + void addTestData(Object value) { + JsonPointer ptr = getPointer(null, true, true); + if (!testDataCache.exists(ptr)) { + try { + testDataCache.set(ptr, value); + } catch (CacheException e) { + LOGGER.error("Unable to update test data cache for " + ptr, e); + } + } + } + + private void appendPath(StringBuilder path, boolean includeIndexes) { + if (parent == null) + path.append(testDataPath); + else + parent.appendPath(path, includeIndexes); + if (!isListItem()) + path.append('/').append(name); + if (includeIndexes && isIndexed()) + path.append('/').append(index); + } + + String getComponentType() { + return isArray ? dataType.substring(0, dataType.length() - 2) : (isContainer ? items : this).dataType; + } + + private JsonPointer getPointer(String suffix, boolean includeIndexes, boolean includeLastIndex) { + StringBuilder path = new StringBuilder(); + appendPath(path, includeIndexes); + if (includeIndexes && !includeLastIndex && isIndexed()) + path.setLength(path.lastIndexOf("/")); + if (suffix != null) + path.append('/').append(suffix); + return JsonPointer.compile(path.toString()); + } + + private void init(CodegenVariable parent, String testDataPath, Map models) { + this.parent = parent; + this.isArray = dataType.endsWith("[]"); + this.testDataPath = testDataPath; + CodegenModel cm = models.get(dataType); + if (cm != null && (cm.isArrayModel || cm.isMapModel)) { + this.isContainer = true; + this.isListContainer = cm.isArrayModel; + this.isMapContainer = cm.isMapModel; + this.items = new CodegenVariable(); + this.items.name = "item"; + this.items.dataType = cm.additionalPropertiesType; + this.items.init(this, testDataPath, models); + } + try { + if ((isArray || isContainer) && testDataControlCache != null) + this.itemCount = testDataControlCache.getInt(getPointer("testItemCount", false, false), 1); + } catch (CacheException e) { + LOGGER.error("Error accessing test data control cache", e); + } + } + + private boolean isIndexed() { + return isListContainer || isArray && !dataType.equals("byte[]"); + } + + private boolean isListItem() { + return parent != null && parent.isListContainer; + } + + int size() { + return loadTestDataFromFile ? testDataCache.size(getPointer(null, true, false)) : 0; + } + + @Override + public String toString() { + return "CodegenVariable [name=" + name + ", dataType=" + dataType + ", dataFormat=" + dataFormat + + ", isArray=" + isArray + ", isContainer=" + isContainer + ", isListContainer=" + isListContainer + + ", isMapContainer=" + isMapContainer + ", isPrimitiveType=" + isPrimitiveType + ", testDataPath=" + + testDataPath + ", enumName=" + enumName + ", allowableValues=" + allowableValues + ", minItems=" + + minItems + ", itemCount=" + itemCount + ", minimum=" + minimum + ", maximum=" + maximum + + ", exclusiveMinimum=" + exclusiveMinimum + ", exclusiveMaximum=" + exclusiveMaximum + + ", minLength=" + minLength + ", maxLength=" + maxLength + ", pattern=" + pattern + ", setter=" + + setter + ", vendorExtensions=" + vendorExtensions + "]"; + } + } + + private static final Logger LOGGER = LoggerFactory.getLogger(JavaCXFExtServerCodegen.class); + + private static final String INDENT = " "; + + private static final SimpleDateFormat ISO8601_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()); + + private static final SimpleDateFormat ISO8601_DATETIME_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX", + Locale.getDefault()); + + private static final long MILLIS_PER_DAY = 24 * 60 * 60 * 1000; + + private static final long MIN_DATE; + + private static final long MAX_DATE; + + private static final String NL = System.lineSeparator(); + + private static final Collection DATE_TYPES = Arrays.asList("Date", "DateTime", "OffsetDateTime", + "LocalDateTime", "LocalDate"); + + static { + ISO8601_DATE_FORMAT.setTimeZone(TimeZone.getTimeZone("UTC")); + ISO8601_DATETIME_FORMAT.setTimeZone(TimeZone.getTimeZone("UTC")); + long minDate = 0; + long maxDate = 0; + try { + minDate = ISO8601_DATETIME_FORMAT.parse("1970-01-01T00:00:00Z").getTime(); + maxDate = ISO8601_DATETIME_FORMAT.parse("2099-12-31T23:59:59Z").getTime(); + } catch (ParseException e) { + // Won't happen with the values provided. + } + MIN_DATE = minDate; + MAX_DATE = maxDate; + } + + private Map REGEX_GENERATORS = new HashMap<>(); + + protected boolean generateOperationBody = false; + + protected boolean loadTestDataFromFile = false; + + protected boolean supportMultipleSpringServices = false; + + protected JsonCache testDataCache = null; + + protected JsonCache testDataControlCache = null; + + protected File testDataFile = null; + + protected File testDataControlFile = null; + + public JavaCXFExtServerCodegen() { + super(); + + embeddedTemplateDir = templateDir = JAXRS_TEMPLATE_DIRECTORY_NAME + File.separator + "cxf-ext"; + cliOptions.add(CliOption.newBoolean(SUPPORT_MULTIPLE_SPRING_SERVICES, + "Support generation of Spring services from multiple specifications")); + cliOptions.add(CliOption.newBoolean(GENERATE_OPERATION_BODY, "Generate fully functional operation bodies")); + cliOptions.add(CliOption.newBoolean(LOAD_TEST_DATA_FROM_FILE, "Load test data from a generated JSON file")); + cliOptions.add(CliOption.newString(TEST_DATA_FILE, "JSON file to contain generated test data")); + cliOptions.add(CliOption.newString(TEST_DATA_CONTROL_FILE, "JSON file to control test data generation")); + } + + private void appendArrayValue(StringBuilder buffer, String indent, CodegenOperation op, CodegenVariable var, + String localVar, Collection localVars, Map models) { + + if (var.dataType.equals("byte[]")) { + // Byte arrays are represented as Base64-encoded strings. + appendByteArrayValue(buffer, indent, op, var, localVar, localVars, models); + } else { + boolean isPrimitiveType = var.isPrimitiveType && !"Object".equals(var.items.dataType); + int itemCount = Math.max(var.itemCount, var.minItems == null ? 1 : Math.max(1, var.minItems)); + if (!loadTestDataFromFile) { + buffer.append("new ").append(var.getComponentType()); + if (isPrimitiveType) + buffer.append("[] {"); + else + buffer.append('[').append(itemCount).append("];"); + } + var.index = var.size(); + for (int i = var.index; i < itemCount; i++) { + if (isPrimitiveType) { + // We don't need a local variable for a primitive value + appendValue(buffer, indent, op, var.items, localVar, localVars, models); + if (i < itemCount - 1 && !loadTestDataFromFile) + buffer.append(", "); + } else { + String itemVar = appendLocalVariable(buffer, indent, op, var.items, localVars, models); + if (!loadTestDataFromFile) { + buffer.append(NL).append(indent).append(localVar).append('[').append(i).append("] = ") + .append(itemVar).append(';'); + } + } + var.index++; + } + var.index = 0; + if (isPrimitiveType && !loadTestDataFromFile) + buffer.append("};"); + } + } + + private void appendByteArrayValue(StringBuilder buffer, String indent, CodegenOperation op, CodegenVariable var, + String localVar, Collection localVars, Map models) { + + if (!loadTestDataFromFile) + buffer.append('"'); + short min = var == null || var.minimum == null ? Byte.MIN_VALUE : Byte.parseByte(var.minimum); + short max = var == null || var.maximum == null ? Byte.MAX_VALUE : Byte.parseByte(var.maximum); + short exclusiveMin = (short) (var != null && var.exclusiveMinimum ? 1 : 0); + short inclusiveMax = (short) (var == null || !var.exclusiveMaximum ? 1 : 0); + int itemCount = Math.max(var.itemCount, var.minItems == null ? 1 : Math.max(1, var.minItems)); + byte[] randomBytes = new byte[itemCount]; + for (int i = 0; i < itemCount; i++) + randomBytes[i] = (byte) (min + exclusiveMin + ((max + inclusiveMax - min - exclusiveMin) * Math.random())); + String randomBytesBase64 = Base64.getEncoder().encodeToString(randomBytes); + if (loadTestDataFromFile) + var.addTestData(randomBytesBase64); + else + buffer.append('"'); + } + + private void appendListValue(StringBuilder buffer, String indent, CodegenOperation op, CodegenVariable var, + String localVar, Collection localVars, Map models) { + + op.imports.add("List"); + if (!loadTestDataFromFile) { + op.imports.add("ArrayList"); + buffer.append("new ArrayList<"); + if (supportJava6) + buffer.append(var.dataType); + buffer.append(">();"); + } + var.index = var.size(); + int itemCount = Math.max(var.itemCount, var.minItems == null ? 1 : Math.max(1, var.minItems)); + for (int i = var.index; i < itemCount; i++) { + if (var.isPrimitiveType && !"Object".equals(var.items.dataType)) { + // We don't need a local variable for a primitive value + if (!loadTestDataFromFile) + buffer.append(NL).append(indent).append(localVar).append(".add("); + appendValue(buffer, indent, op, var.items, localVar, localVars, models); + } else { + String itemVar = appendLocalVariable(buffer, indent, op, var.items, localVars, models); + if (!loadTestDataFromFile) + buffer.append(NL).append(indent).append(localVar).append(".add(").append(itemVar); + } + if (!loadTestDataFromFile) + buffer.append(");"); + var.index++; + } + var.index = 0; + } + + /** + * Declares and initialises a local variable of the specified type. + * + * @param buffer + * @param indent + * @param op + * @param localVars + * @param models + * @param type + * @param baseType + * @param isListContainer + * @param isMapContainer + * @param localVar + * @return localVar with a numeric suffix if necessary to ensure uniqueness. + */ + private String appendLocalVariable(StringBuilder buffer, String indent, CodegenOperation op, CodegenVariable var, + Collection localVars, Map models) { + + // Ensure that we're using a unique local variable name (to avoid typing and overwriting conflicts). + String localVar = localVariablePrefix + var.name; + for (int i = 2; localVars.contains(localVar); i++) + localVar = localVariablePrefix + var.name + i; + localVars.add(localVar); + + if (!loadTestDataFromFile) + buffer.append(NL).append(indent).append(var.dataType).append(' ').append(localVar).append(" = "); + appendValue(buffer, indent, op, var, localVar, localVars, models); + if (!loadTestDataFromFile) + appendSemicolon(buffer); + + return localVar; + } + + private void appendMapValue(StringBuilder buffer, String indent, CodegenOperation op, CodegenVariable var, + String localVar, Collection localVars, Map models) { + + op.imports.add("Map"); + if (!loadTestDataFromFile) { + op.imports.add("HashMap"); + buffer.append("new HashMap<"); + if (supportJava6) + buffer.append("String, ").append(var.dataType); + buffer.append(">();"); + } + var.index = var.size(); + int itemCount = Math.max(var.itemCount, var.minItems == null ? 1 : Math.max(1, var.minItems)); + for (int i = var.index; i < itemCount; i++) { + // Map entries need a random key (the default value for var.items.name is "items"). + var.items.name = generateRandomString(null); + if (var.isPrimitiveType) { + // We don't need a local variable for a primitive value + if (!loadTestDataFromFile) { + buffer.append(NL).append(indent).append(localVar).append(".put(").append(var.items.name) + .append(", "); + } + appendValue(buffer, indent, op, var.items, localVar, localVars, models); + } else { + String itemVar = appendLocalVariable(buffer, indent, op, var.items, localVars, models); + if (!loadTestDataFromFile) + buffer.append(localVar).append(".put(\"").append(var.items.name).append("\", ").append(itemVar); + } + if (!loadTestDataFromFile) + buffer.append(");"); + var.index++; + } + } + + private void appendObjectValue(StringBuilder buffer, String indent, CodegenOperation op, CodegenVariable var, + String localVar, Collection localVars, Map models) { + + if ("Object".equals(var.dataType)) { + // Jackson can't serialize java.lang.Object, so we'll provide an empty JSON ObjectNode instead. + if (loadTestDataFromFile) + var.addTestData(JsonNodeFactory.instance.objectNode()); + else + buffer.append("JsonNodeFactory.instance.objectNode();"); + } else { + if (needToImport(var.dataType)) + op.imports.add(var.dataType); + if (!loadTestDataFromFile) + buffer.append("new ").append(var.dataType).append("();"); + appendPropertyAssignments(buffer, indent, op, var, localVar, localVars, models); + } + } + + private void appendPropertyAssignments(StringBuilder buffer, String indent, CodegenOperation op, + CodegenVariable parent, String localVar, Collection localVars, Map models) { + + CodegenModel cm = models.get(parent.dataType); + if (cm != null) { // TODO: handle isArrayModel and isMapModel + for (CodegenProperty cp : cm.allVars) { + CodegenVariable var = new CodegenVariable(parent, cp, null, models); + if (var.isContainer || !var.isPrimitiveType) { + String containerVar = appendLocalVariable(buffer, indent, op, var, localVars, models); + if (!loadTestDataFromFile) { + buffer.append(NL).append(indent).append(localVar).append('.').append(var.setter).append('(') + .append(containerVar); + } + } else { + // No need to use a local variable for types which can be initialised with a single expression. + if (!loadTestDataFromFile) + buffer.append(NL).append(indent).append(localVar).append('.').append(var.setter).append('('); + appendValue(buffer, indent, op, var, localVar, localVars, models); + } + if (!loadTestDataFromFile) + buffer.append(");"); + } + } + } + + private void appendRandomBoolean(StringBuilder buffer, CodegenOperation op, CodegenVariable var) { + boolean randomBoolean = Math.random() > 0.5; + + if (loadTestDataFromFile) + var.addTestData(randomBoolean); + else + buffer.append(randomBoolean); + } + + private void appendRandomByte(StringBuilder buffer, CodegenOperation op, CodegenVariable var) { + if (!appendRandomEnum(buffer, op, var)) { + // NOTE: use short to hold byte values, to avoid numeric overflow. + short min = var == null || var.minimum == null ? Byte.MIN_VALUE : Byte.parseByte(var.minimum); + short max = var == null || var.maximum == null ? Byte.MAX_VALUE : Byte.parseByte(var.maximum); + short exclusiveMin = (short) (var != null && var.exclusiveMinimum ? 1 : 0); + short inclusiveMax = (short) (var == null || !var.exclusiveMaximum ? 1 : 0); + byte randomByte = (byte) (min + exclusiveMin + ((max + inclusiveMax - min - exclusiveMin) * Math.random())); + + if (loadTestDataFromFile) + var.addTestData(randomByte); + else + buffer.append(String.format(Locale.getDefault(), "(byte)%0#2x", randomByte)); + } + } + + private void appendRandomChar(StringBuilder buffer, CodegenOperation op, CodegenVariable var) { + if (!appendRandomEnum(buffer, op, var)) { + // TODO: consider whether to broaden the default range. + // NOTE: char is unsigned, so there's no overflow issue in computing (max - min). + char min = var == null || var.minimum == null ? 'a' : var.minimum.charAt(0); + char max = var == null || var.maximum == null ? 'z' : var.maximum.charAt(0); + char exclusiveMin = (char) (var != null && var.exclusiveMinimum ? 1 : 0); + char inclusiveMax = (char) (var == null || !var.exclusiveMaximum ? 1 : 0); + char randomChar = (char) (min + exclusiveMin + ((max + inclusiveMax - min - exclusiveMin) * Math.random())); + + if (loadTestDataFromFile) + var.addTestData(randomChar); + else + buffer.append(String.format(Locale.getDefault(), "'%c'", randomChar)); + } + } + + private void appendRandomDate(StringBuilder buffer, CodegenOperation op, CodegenVariable var) { + if (!appendRandomEnum(buffer, op, var)) { + long minDate = MIN_DATE; + long maxDate = MAX_DATE; + if (var != null) { + DateFormat df = var.dataFormat.equals("date-time") ? ISO8601_DATETIME_FORMAT : ISO8601_DATE_FORMAT; + String isoFormat = var.dataFormat.equals("date-time") ? "date-time" : "full-date"; + if (var.minimum != null) { + try { + minDate = df.parse(var.minimum).getTime(); + } catch (ParseException e) { + // Ignore, use MIN_DATE. + LOGGER.warn("Could not parse minimum {} value for '{}/{}' as an ISO-8601 {}: {}", + var.dataFormat, op.operationId, var.name, isoFormat, var.minimum); + } + } + if (var.maximum != null) { + try { + maxDate = df.parse(var.maximum).getTime(); + } catch (ParseException e) { + // Ignore, use MAX_DATE. + LOGGER.warn("Could not parse maximum {} value for '{}/{}' as an ISO-8601 {}: {}", + var.dataFormat, op.operationId, var.name, isoFormat, var.minimum); + } + } + } + // NOTE: use BigDecimal to hold long values, to avoid numeric overflow. + BigDecimal minLong = new BigDecimal(minDate); + BigDecimal maxLong = new BigDecimal(maxDate); + BigDecimal exclusiveMinLong = new BigDecimal(var != null && var.exclusiveMinimum ? 1 : 0); + BigDecimal inclusiveMaxLong = new BigDecimal(var == null || !var.exclusiveMaximum ? 1 : 0); + long randomDateLong = minLong.add(exclusiveMinLong).add(maxLong.add(inclusiveMaxLong).subtract(minLong) + .subtract(exclusiveMinLong).multiply(new BigDecimal(Math.random()))).longValue(); + + // If it's just a date without a time, round downwards to the nearest day. + if ("date".equals(var.dataFormat)) + randomDateLong = (randomDateLong % MILLIS_PER_DAY) * MILLIS_PER_DAY; + + // NOTE: By default Jackson serializes Date as long milliseconds since epoch date, but that conflicts with + // the OpenAPI 2.0/3.0 specs, which mandates the ISO-8601 full-date or date-time formats. Accordingly, date + // and date-time fields are annotated with @JsonFormat to specify the appropriate ISO format. + if (loadTestDataFromFile) { + Date randomDate = new Date(randomDateLong); + switch (var.dataFormat) { + case "date": + var.addTestData(ISO8601_DATE_FORMAT.format(randomDate)); + break; + case "date-time": + var.addTestData(ISO8601_DATETIME_FORMAT.format(randomDate)); + break; + } + } else { + buffer.append("new Date(").append(randomDateLong).append(')'); + } + } + } + + private void appendRandomDouble(StringBuilder buffer, CodegenOperation op, CodegenVariable var) { + if (!appendRandomEnum(buffer, op, var)) { + // NOTE: use BigDecimal to hold double values, to avoid numeric overflow. + BigDecimal min = new BigDecimal( + var == null || var.minimum == null ? Long.MIN_VALUE : Double.parseDouble(var.minimum)); + BigDecimal max = new BigDecimal( + var == null || var.maximum == null ? Long.MAX_VALUE : Double.parseDouble(var.maximum)); + BigDecimal exclusiveMin = new BigDecimal(var != null && var.exclusiveMinimum ? 1 : 0); + BigDecimal inclusiveMax = new BigDecimal(var == null || !var.exclusiveMaximum ? 1 : 0); + BigDecimal randomBigDecimal = min.add(exclusiveMin).add(max.add(inclusiveMax).subtract(min) + .subtract(exclusiveMin).multiply(new BigDecimal(String.valueOf(Math.random())))); + + if (loadTestDataFromFile) + var.addTestData(randomBigDecimal); + else + buffer.append(randomBigDecimal.toString()).append('D'); + } + } + + private boolean appendRandomEnum(StringBuilder buffer, CodegenOperation op, CodegenVariable var) { + if (var != null && var.allowableValues != null) { + List values = (List) var.allowableValues.get("values"); + int i = (int) (values.size() * Math.random()); + Object randomEnum = values.get(i); + boolean usingEnumLiteral = false; + String definingClass = (String) var.vendorExtensions.get("x-defining-class"); + if (definingClass != null) { + @SuppressWarnings("unchecked") + List> enumVars = (List>) var.allowableValues.get("enumVars"); + if (enumVars != null) { + if (!loadTestDataFromFile) { + Map randomEnumVar = enumVars.get(i); + // NOTE: to disambiguate identically named inner enums, qualify enum name with defining class. + buffer.append(definingClass).append('.').append(var.enumName).append('.') + .append(randomEnumVar.get("name")); + op.imports.add(definingClass); + } + usingEnumLiteral = true; + } + } + if (loadTestDataFromFile) { + var.addTestData(randomEnum); + } else if (!usingEnumLiteral) { + String quoteString = randomEnum instanceof String ? "\"" : ""; + buffer.append(quoteString).append(randomEnum).append(quoteString); + } + return true; + } + return false; + } + + private void appendRandomFile(StringBuilder buffer, CodegenOperation op, CodegenVariable var) { + // For code generation purposes we'll just supply a random string as the contents of a text 'file'. + String randomString = generateRandomString(var); + + if (loadTestDataFromFile) { + var.addTestData(randomString); + } else { + buffer.append('"').append(randomString).append('"'); + } + } + + private void appendRandomFloat(StringBuilder buffer, CodegenOperation op, CodegenVariable var) { + if (!appendRandomEnum(buffer, op, var)) { + // NOTE: use double to hold float values, to avoid numeric overflow. + double min = var == null || var.minimum == null ? -Float.MAX_VALUE : Float.parseFloat(var.minimum); + double max = var == null || var.maximum == null ? Float.MAX_VALUE : Float.parseFloat(var.maximum); + double exclusiveMin = (double) (var != null && var.exclusiveMinimum ? 1 : 0); + double inclusiveMax = (double) (var == null || !var.exclusiveMaximum ? 1 : 0); + float randomFloat = (float) (min + exclusiveMin + + ((max + inclusiveMax - min - exclusiveMin) * Math.random())); + + if (loadTestDataFromFile) + var.addTestData(randomFloat); + else + buffer.append(String.format(Locale.getDefault(), "%g", randomFloat)).append('F'); + } + } + + private void appendRandomInt(StringBuilder buffer, CodegenOperation op, CodegenVariable var) { + if (!appendRandomEnum(buffer, op, var)) { + // NOTE: use double to hold int values, to avoid numeric overflow. + long min = var == null || var.minimum == null ? Integer.MIN_VALUE : Integer.parseInt(var.minimum); + long max = var == null || var.maximum == null ? Integer.MAX_VALUE : Integer.parseInt(var.maximum); + long exclusiveMin = var != null && var.exclusiveMinimum ? 1 : 0; + long inclusiveMax = var == null || !var.exclusiveMaximum ? 1 : 0; + int randomInt = (int) (min + exclusiveMin + ((max + inclusiveMax - min - exclusiveMin) * Math.random())); + + if (loadTestDataFromFile) + var.addTestData(randomInt); + else + buffer.append(randomInt); + } + } + + private void appendRandomLong(StringBuilder buffer, CodegenOperation op, CodegenVariable var) { + if (!appendRandomEnum(buffer, op, var)) { + // NOTE: use BigDecimal to hold long values, to avoid numeric overflow. + BigDecimal min = new BigDecimal( + var == null || var.minimum == null ? Long.MIN_VALUE : Long.parseLong(var.minimum)); + BigDecimal max = new BigDecimal( + var == null || var.maximum == null ? Long.MAX_VALUE : Long.parseLong(var.maximum)); + BigDecimal exclusiveMin = new BigDecimal(var != null && var.exclusiveMinimum ? 1 : 0); + BigDecimal inclusiveMax = new BigDecimal(var == null || !var.exclusiveMaximum ? 1 : 0); + long randomLong = min.add(exclusiveMin).add( + max.add(inclusiveMax).subtract(min).subtract(exclusiveMin).multiply(new BigDecimal(Math.random()))) + .longValue(); + + if (loadTestDataFromFile) + var.addTestData(randomLong); + else + buffer.append(randomLong).append('L'); + } + } + + private void appendRandomShort(StringBuilder buffer, CodegenOperation op, CodegenVariable var) { + if (!appendRandomEnum(buffer, op, var)) { + // NOTE: use int to hold short values, to avoid numeric overflow. + int min = var == null || var.minimum == null ? Short.MIN_VALUE : Short.parseShort(var.minimum); + int max = var == null || var.maximum == null ? Short.MAX_VALUE : Short.parseShort(var.maximum); + int exclusiveMin = var != null && var.exclusiveMinimum ? 1 : 0; + int inclusiveMax = var == null || !var.exclusiveMaximum ? 1 : 0; + short randomShort = (short) (min + exclusiveMin + + ((max + inclusiveMax - min - exclusiveMin) * Math.random())); + + if (loadTestDataFromFile) + var.addTestData(randomShort); + else + buffer.append(String.format(Locale.getDefault(), "(short)%d", randomShort)); + } + } + + private void appendRandomString(StringBuilder buffer, CodegenOperation op, CodegenVariable var) { + if (!appendRandomEnum(buffer, op, var)) { + String randomString = generateRandomString(var); + + if (loadTestDataFromFile) { + var.addTestData(randomString); + } else { + buffer.append('"').append(randomString).append('"'); + } + } + } + + /** + * Appends a sample value for a scalar type - that is, one which is neither a list nor a map container. + * + * @param buffer The operation body to which the value expression is to be appended. + * @param indent Indentation to apply. + * @param op + * @param localVar The variable whose value is to be set. + * @param localVars Tracks local variables which have been allocated. + * @param models A map of models, keyed on class name. + * @param type The value type. + */ + private void appendScalarValue(StringBuilder buffer, String indent, CodegenOperation op, CodegenVariable var, + String localVar, Collection localVars, Map models) { + + if (!var.isPrimitiveType && !DATE_TYPES.contains(var.dataType) || var.dataType.equals("Object")) { + // All other non-container types: allocate a new object on the heap. + appendObjectValue(buffer, indent, op, var, localVar, localVars, models); + } else { + openValueBuffer(buffer, var); + // NOTE: this loop is only iterated once unless var.isArray is true and var.type is not byte[]. + int itemCount = Math.max(var.itemCount, var.minItems == null ? 1 : Math.max(1, var.minItems)); + for (int i = 0; i < itemCount; i++) { + switch (var.getComponentType()) { + case "byte": + case "Byte": + appendRandomByte(buffer, op, var); + break; + case "boolean": + case "Boolean": + appendRandomBoolean(buffer, op, var); + break; + case "char": + case "Char": + appendRandomChar(buffer, op, var); + break; + case "double": + case "Double": + appendRandomDouble(buffer, op, var); + break; + case "float": + case "Float": + appendRandomFloat(buffer, op, var); + break; + case "short": + case "Short": + appendRandomShort(buffer, op, var); + break; + case "int": + case "Integer": + appendRandomInt(buffer, op, var); + break; + case "long": + case "Long": + appendRandomLong(buffer, op, var); + break; + case "String": + appendRandomString(buffer, op, var); + break; + case "Date": + appendRandomDate(buffer, op, var); + break; + case "File": + appendRandomFile(buffer, op, var); + break; + default: + LOGGER.warn("Unrecognized component type '{}" + "' in '{}' property for '{}'operation", + var.getComponentType(), var.name, op.operationId); + } + if (!loadTestDataFromFile && i < itemCount - 1) + buffer.append(", "); + } + closeValueBuffer(buffer, var); + } + } + + private void appendSemicolon(StringBuilder buffer) { + if (buffer.charAt(buffer.length() - 1) != ';') + buffer.append(';'); + } + + private StringBuilder appendValue(StringBuilder buffer, String indent, CodegenOperation op, CodegenVariable var, + String localVar, Collection localVars, Map models) { + + if (var.isListContainer) + appendListValue(buffer, indent, op, var, localVar, localVars, models); + else if (var.isMapContainer) + appendMapValue(buffer, indent, op, var, localVar, localVars, models); + else if (var.isArray) + appendArrayValue(buffer, indent, op, var, localVar, localVars, models); + else + appendScalarValue(buffer, indent, op, var, localVar, localVars, models); + + return buffer; + } + + /** + * Applies appropriate default consumes and/or produces content type(s). Affects operations which do not specify a + * content type for consumes and/or produces and respectively have a body parameter and/or a return value. This is + * necessary since none of the configured CXF or Jackson JAX-RS providers support the inferred default content type + * of */*. + * + * @param op + */ + private void applyDefaultContentTypes(CodegenOperation op) { + if (op.bodyParam != null && !op.hasConsumes) { + CodegenParameter bodyParam = op.bodyParam; + String mediaType; + if (bodyParam.isContainer || bodyParam.isModel || bodyParam.isFreeFormObject) + mediaType = "application/json"; + else if (bodyParam.isBinary || bodyParam.isFile) + mediaType = "application/octet-stream"; + else + mediaType = "text/plain"; + Map contentType = new HashMap<>(); + contentType.put("mediaType", mediaType); + contentType.put("hasMore", null); + if (op.consumes == null) + op.consumes = new ArrayList<>(); + op.consumes.add(contentType); + op.hasConsumes = true; + } + if (!"void".equals(op.returnType) && !op.hasProduces) { + String mediaType; + if (op.returnContainer != null || !op.returnTypeIsPrimitive) + mediaType = "application/json"; + else + mediaType = "text/plain"; + Map contentType = new HashMap<>(); + contentType.put("mediaType", mediaType); + contentType.put("hasMore", null); + if (op.produces == null) + op.produces = new ArrayList<>(); + op.produces.add(contentType); + op.hasProduces = true; + } + } + + private void closeValueBuffer(StringBuilder buffer, CodegenVariable var) { + if (var.isArray && !loadTestDataFromFile) + buffer.append('}'); + } + + private String generateRandomString(CodegenVariable var) { + String pattern = patternFor(var); + Generex generex = REGEX_GENERATORS.get(pattern); + if (generex == null) { + generex = new Generex(pattern); + REGEX_GENERATORS.put(pattern, generex); + } + return generex.random(); + } + + private String getCacheMethod(CodegenVariable var) { + String method; + switch (var.dataType) { + case "boolean": + case "Boolean": + method = "getBoolean"; + break; + case "BigDecimal": + method = "getBigDecimal"; + break; + case "BigInteger": + method = "getBigInteger"; + break; + case "byte[]": + method = "getBinary"; + break; + case "double": + case "Double": + method = "getDouble"; + break; + case "float": + case "Float": + method = "getFloat"; + break; + case "long": + case "Long": + method = "getLong"; + break; + case "int": + case "Integer": + method = "getInt"; + break; + case "String": + method = "getString"; + break; + default: + method = var.isListContainer ? "getObjects" : "getObject"; + break; + } + return method; + } + + @Override + public String getName() { + return "jaxrs-cxf-extended"; + } + + @Override + public String getHelp() { + return "Extends jaxrs-cxf with options to generate a functional mock server."; + } + + private boolean hasCacheMethod(CodegenVariable var) { + boolean hasCacheMethod; + switch (var.dataType) { + case "boolean": + case "Boolean": + case "BigDecimal": + case "BigInteger": + case "byte[]": + case "double": + case "Double": + case "float": + case "Float": + case "long": + case "Long": + case "int": + case "Integer": + case "String": + hasCacheMethod = true; + break; + default: + hasCacheMethod = false; + break; + } + return hasCacheMethod; + } + + private void openValueBuffer(StringBuilder buffer, CodegenVariable var) { + if (var.isArray && !loadTestDataFromFile) + buffer.append("new ").append(var.dataType).append(" {"); + } + + private String patternFor(CodegenVariable var) { + String pattern = null; + if (var != null) { + if (var.pattern != null) { + pattern = StringEscapeUtils.unescapeJava(var.pattern); + } else if (var.dataFormat != null) { + // According to JSON Schema (https://tools.ietf.org/html/draft-fge-json-schema-validation-00), + // string-type values can be constrained by a format, one of: {date-time, email, hostname, ipv4, ipv6, + // uri}. Custom formats are allowed. The OpenAPI Specification also mentions binary, byte, date, + // password, uuid. + switch (var.dataFormat) { + case "binary": + // Any sequence of octets. + pattern = "[0-9A-F]{2}{4,24}"; + break; + case "byte": + // Base64 encoded bytes: 4 characters represent 3 bytes. + pattern = "[A-Za-z0-9+/]{4}{4,24}"; + break; + case "date": + // ISO-8601: YYYY-MM-DD + pattern = "20\\d{2}-(?:" // YY- (20yy) + + "(?:01|03|05|07|08|10|12)-(?:0[1-9]|[1-2][0-9]|3[0-1])|" // MM-DD (31 days) + + "(?:04|06|09|11)-(?:0[1-9]|[1-2][0-9]|30)|" // MM-DD (30 days) + + "02-(?:0[1-9]|1[0-9]|2[0-8]))"; // MM-DD (28 days) + break; + case "date-time": + // ISO-8601: YYYY-MM-DDTHH:mm:ss(Z|+-HH:mm) NOTE: the time zone offset is mandatory. + pattern = "20\\d{2}-(?:" // YYYY- + + "(?:01|03|05|07|08|10|12)-(?:0[1-9]|[1-2][0-9]|3[0-1])|" // MM-DD (31 days) + + "(?:04|06|09|11)-(?:0[1-9]|[1-2][0-9]|30)|" // MM-DD (30 days) + + "02-(?:0[1-9]|1[0-9]|2[0-8]))" // MM-DD (28 days) + + "T(?:[0-1][0-9]|2[0-3])" // THH + + ":[0-5][0-9]" // :mm + + ":[0-5][0-9]" // :ss + + "(?:Z|(?:-0[1-9]|-1[0-2]|\\+0[0-9]|\\+1[0-4]):(?:00|30|45))"; // timezone + break; + case "email": + pattern = "[a-z][a-z0-9_.-]{1,8}@[a-z][a-z0-9-.]{2,12}\\.[a-z]{2,4}"; // (simplistic but + // sufficient) + break; + case "hostname": + pattern = "[a-z][a-z0-9-.]{2,12}\\.[a-z]{2,4}"; // (simplistic but sufficient) + break; + case "ipv4": + pattern = "(?:(?:25[0-5]|2[0-4][0-9]|[1-9][0-9]|[0-9])\\.){3}" + + "(?:25[0-5]|2[0-4][0-9]|[1-9][0-9]|[0-9])"; + break; + case "ipv6": + // Simplified (!) from + // https://community.helpsystems.com/forums/intermapper/miscellaneous-topics/5acc4fcf-fa83-e511-80cf-0050568460e4 + pattern = "(?:(?:[0-9A-F]{1,4}:){7}(?:[0-9A-F]{1,4}|:))|" + + "(?:(?:[0-9A-F]{1,4}:){6}(?::[0-9A-F]{1,4}|(?:(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|" + + "(?:(?:[0-9A-F]{1,4}:){5}(?:(?:(?::[0-9A-F]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|" + + "(?:(?:[0-9A-F]{1,4}:){4}(?:(?:(?::[0-9A-F]{1,4}){1,3})|(?:(?::[0-9A-F]{1,4})?:(?:(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|" + + "(?:(?:[0-9A-F]{1,4}:){3}(?:(?:(?::[0-9A-F]{1,4}){1,4})|(?:(?::[0-9A-F]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|" + + "(?:(?:[0-9A-F]{1,4}:){2}(?:(?:(?::[0-9A-F]{1,4}){1,5})|(?:(?::[0-9A-F]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|" + + "(?:(?:[0-9A-F]{1,4}:){1}(?:(?:(?::[0-9A-F]{1,4}){1,6})|(?:(?::[0-9A-F]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|" + + "(?::(?:(?:(?::[0-9A-F]{1,4}){1,7})|(?:(?::[0-9A-F]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))"; + break; + case "uri": + // SCHEME://AUTHORITY/PATH/PATH?PARAM=VALUE,PARAM=VALUE#ANCHOR + pattern = "(?:(?:http[s]?|ftp):)?" // scheme + + "(?://[a-z][a-z.]{4,12})?" // authority + + "(?:/[a-z]{1,8}){0,4}" // path + + "(?:\\?[a-z]{1,8}=[a-z0-9]{1,8}(?:&[a-z]{1,8}=[a-z0-9]{1,8}){0,3})?" // query + + "(?:#[a-z0-9_]{1,16})?"; // fragment + break; + case "uuid": + pattern = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"; // 8-4-4-4-12 + break; + case "password": + // Fall through. + default: + break; + } + } + } + if (pattern == null) { + int minLength = var == null || var.minLength == null ? 4 : var.minLength; + int maxLength = var == null || var.maxLength == null ? 16 : var.maxLength; + pattern = "[a-zA-Z][a-zA-Z0-9]{" + minLength + ',' + maxLength + '}'; + } + return pattern; + } + + @Override + public Map postProcessAllModels(Map objs) { + objs = super.postProcessAllModels(objs); + + // When populating operation bodies we need to import enum types, which requires the class that defines them. + if (generateOperationBody) { + for (Object value : objs.values()) { + @SuppressWarnings("unchecked") + Map inner = (Map) value; + @SuppressWarnings("unchecked") + List> models = (List>) inner.get("models"); + for (Map mo : models) + postProcessModel((CodegenModel) mo.get("model")); + } + } + + return objs; + } + + private void postProcessModel(CodegenModel cm) { + // NOTE: if supportsInheritance is false, cm.vars == cm.allVars so we only have to update one list. + for (CodegenProperty var : cm.vars) { + var.vendorExtensions.put("x-defining-class", cm.classname); + } + if (supportsInheritance) { + if (cm.allVars != cm.vars) { + for (CodegenProperty var : cm.allVars) { + String definingClass = cm.classname; + if (cm.vars.stream().noneMatch(v -> v.name.equals(var.name))) { + CodegenModel ancestor = cm; + while ((ancestor = ancestor.parentModel) != null) { + if (ancestor.vars.stream().anyMatch(v -> v.name.equals(var.name))) { + definingClass = ancestor.classname; + break; + } + } + } + var.vendorExtensions.put("x-defining-class", definingClass); + } + } + if (cm.parentModel != null) + postProcessModel(cm.parentModel); + } + } + + @Override + public Map postProcessOperationsWithModels(Map objs, List allModels) { + Map result = super.postProcessOperationsWithModels(objs, allModels); + + if (generateOperationBody) { + // We generate the operation body in code because the logic to do so is far too complicated to be expressed + // in the logic-less Mustache templating system. + + @SuppressWarnings("unchecked") + Map operations = (Map) result.get("operations"); + if (operations != null) { + String classname = (String) operations.get("classname"); + + // Map the models so we can look them up by name. + Map models = new HashMap<>(); + for (Object model : allModels) { + @SuppressWarnings("unchecked") + CodegenModel cgModel = ((Map) model).get("model"); + models.put(cgModel.classname, cgModel); + } + + StringBuilder buffer = new StringBuilder(); + @SuppressWarnings("unchecked") + List ops = (List) operations.get("operation"); + for (CodegenOperation op : ops) { + applyDefaultContentTypes(op); + String testDataPath = '/' + classname + '/' + op.operationId; + + // Test client: provide local variable declarations for all parameters. + boolean first = true; + for (CodegenParameter cp : op.allParams) { + buffer.setLength(0); + CodegenVariable var = new CodegenVariable(null, cp, testDataPath, models); + String localVar = appendLocalVariable(buffer, INDENT, op, var, new ArrayList<>(), models); + if (loadTestDataFromFile) { + buffer.append(NL).append(INDENT).append(var.dataType).append(' ').append(localVar) + .append(" = cache.").append(getCacheMethod(var)).append("(\"/") + .append(op.operationId).append('/').append(var.name).append('"'); + if (var.isListContainer) + buffer.append(", ").append(var.getComponentType()).append(".class"); + else if (var.isMapContainer) + buffer.append(", Map.class"); + else if (!hasCacheMethod(var)) + buffer.append(", ").append(var.dataType).append(".class"); + buffer.append(");"); + } + if (first && buffer.indexOf(NL) == 0) { + buffer.delete(0, NL.length()); + first = false; + } + cp.vendorExtensions.put("x-java-param-decl", buffer.toString()); + } + + // Test server: generate operation body where it returns a non-void result. + if (!(Boolean) op.vendorExtensions.getOrDefault("x-java-is-response-void", false)) { + CodegenVariable var = new CodegenVariable(null, op, testDataPath, models); + buffer.setLength(0); + String localVar = appendLocalVariable(buffer, INDENT, op, var, new ArrayList<>(), models); + if (loadTestDataFromFile) { + buffer.append(NL).append(INDENT).append("try {") // split + .append(NL).append(INDENT).append(" ").append(var.dataType).append(' ') + .append(localVar).append(" = cache.").append(getCacheMethod(var)).append("(\"/") + .append(op.operationId).append('/').append(var.name).append('"'); + if (var.isListContainer) + buffer.append(", ").append(var.getComponentType()).append(".class"); + else if (var.isMapContainer) + buffer.append(", Map.class"); + else if (!hasCacheMethod(var)) + buffer.append(", ").append(var.dataType).append(".class"); + buffer.append(");") // split + .append(NL).append(INDENT).append(" return ").append(localVar).append(';') + .append(NL).append(INDENT).append("} catch (CacheException e) {") // split + .append(NL).append(INDENT).append(" throw new RuntimeException(e);") // split + .append(NL).append(INDENT).append("}"); + } else { + buffer.append(NL).append(INDENT).append("return ").append(localVar).append(';'); + } + if (buffer.indexOf(NL) == 0) + buffer.delete(0, NL.length()); + op.vendorExtensions.put("x-java-operation-body", buffer.toString()); + } + } + + // DefaultGenerator already processed all the imports from the generated operations, but these imports + // did not include the ones we've just added to support the code in the operation bodies. Therefore it + // is necessary to recompute the imports and overwrite the existing ones. The code below was copied from + // the private DefaultGenerator.processOperations() method to achieve this end. + Set allImports = new TreeSet(); + for (CodegenOperation op : ops) { + allImports.addAll(op.imports); + } + allImports.add("List"); + allImports.add("Map"); + + List> imports = new ArrayList>(); + for (String nextImport : allImports) { + Map im = new LinkedHashMap(); + String mapping = importMapping().get(nextImport); + if (mapping == null) { + mapping = toModelImport(nextImport); + } + if (mapping != null) { + im.put("import", mapping); + if (!imports.contains(im)) { // avoid duplicates + imports.add(im); + } + } + } + + objs.put("imports", imports); + + // add a flag to indicate whether there's any {{import}} + if (imports.size() > 0) { + objs.put("hasImport", true); + } + } + } + + return result; + } + + @Override + public Map postProcessSupportingFileData(Map objs) { + objs = super.postProcessSupportingFileData(objs); + + if (loadTestDataFromFile) { + // DefaultGenerator doesn't provide any mechanism for emitting supporting files other than by a Mustache + // template, so we're obliged to serialize the caches to JSON strings and use templates to write them. + try { + if (testDataCache.root().isDirty()) { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + testDataCache.root().flush(out); + String testDataJson = new String(out.toByteArray(), "UTF-8"); + objs.put("test-data.json", testDataJson); + supportingFiles.add(new SupportingFile("testData.mustache", testDataFile.getAbsolutePath())); + } + } catch (CacheException | UnsupportedEncodingException e) { + LOGGER.error("Error writing JSON test data file " + testDataFile, e); + } + + try { + if (testDataControlCache.root().isDirty()) { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + testDataControlCache.root().flush(out); + String testDataControlJson = new String(out.toByteArray(), "UTF-8"); + objs.put("test-data-control.json", testDataControlJson); + supportingFiles + .add(new SupportingFile("testDataControl.mustache", testDataControlFile.getAbsolutePath())); + } + } catch (CacheException | UnsupportedEncodingException e) { + LOGGER.error("Error writing JSON test data control file " + testDataControlFile, e); + } + } + + return objs; + } + + @Override + public void processOpts() { + super.processOpts(); + + if (additionalProperties.containsKey(GENERATE_SPRING_APPLICATION)) { + this.setSupportMultipleSpringServices( + convertPropertyToBooleanAndWriteBack(SUPPORT_MULTIPLE_SPRING_SERVICES)); + } + if (additionalProperties.containsKey(GENERATE_OPERATION_BODY)) { + boolean generateOperationBody = convertPropertyToBooleanAndWriteBack(GENERATE_OPERATION_BODY); + this.setGenerateOperationBody(generateOperationBody); + + boolean loadTestDataFromFile = convertPropertyToBooleanAndWriteBack(LOAD_TEST_DATA_FROM_FILE); + this.setLoadTestDataFromFile(loadTestDataFromFile); + + if (loadTestDataFromFile) { + String testDataFileStr; + if (additionalProperties.containsKey(TEST_DATA_FILE)) + testDataFileStr = (String) additionalProperties.get(TEST_DATA_FILE); + else + testDataFileStr = outputFolder() + "/src/main/resources/test-data.json"; + testDataFileStr = testDataFileStr.replace('/', File.separatorChar); + try { + File testDataFile = new File(testDataFileStr).getCanonicalFile(); + testDataFileStr = testDataFile.getPath(); + additionalProperties.put(TEST_DATA_FILE, testDataFileStr.replaceAll("\\\\", "\\\\\\\\")); + setTestDataFile(testDataFile); + } catch (IOException e) { + throw new RuntimeException("Failed to canonicalize file " + testDataFileStr, e); + } + + testDataCache = JsonCache.Factory.instance.get("test-data").mergePolicy(MergePolicy.KEEP_EXISTING) + .child('/' + invokerPackage); + if (this.testDataFile.exists()) { + try { + testDataCache.root().load(this.testDataFile); + } catch (CacheException e) { + LOGGER.error("Unable to load test data file " + testDataFileStr, e); + } + } + + String testDataControlFileStr; + if (additionalProperties.containsKey(TEST_DATA_CONTROL_FILE)) + testDataControlFileStr = (String) additionalProperties.get(TEST_DATA_CONTROL_FILE); + else + testDataControlFileStr = outputFolder() + "/test-data-control.json"; + testDataControlFileStr = testDataControlFileStr.replace('/', File.separatorChar); + try { + File testDataControlFile = new File(testDataControlFileStr).getCanonicalFile(); + testDataControlFileStr = testDataControlFile.getPath(); + additionalProperties.put(TEST_DATA_CONTROL_FILE, + testDataControlFileStr.replaceAll("\\\\", "\\\\\\\\")); + setTestDataControlFile(testDataControlFile); + } catch (IOException e) { + throw new RuntimeException("Failed to canonicalize file " + testDataControlFileStr, e); + } + + testDataControlCache = JsonCache.Factory.instance.get("test-data-control") + .mergePolicy(MergePolicy.KEEP_EXISTING).child('/' + invokerPackage); + if (this.testDataControlFile.exists()) { + try { + testDataControlCache.root().load(this.testDataControlFile); + } catch (CacheException e) { + LOGGER.error("Unable to load test data control file " + testDataControlFileStr, e); + } + } + } + } + if (this.generateSpringApplication) { + if (supportMultipleSpringServices) { + for (SupportingFile sf : supportingFiles) { + if ("server/ApplicationContext.xml.mustache".equals(sf.templateFile)) { + sf.destinationFilename = "ApplicationContext-" + invokerPackage + ".xml"; + break; + } + } + } + } + } + + public void setGenerateOperationBody(boolean generateOperationBody) { + this.generateOperationBody = generateOperationBody; + } + + public void setLoadTestDataFromFile(boolean loadTestDataFromFile) { + this.loadTestDataFromFile = loadTestDataFromFile; + } + + public void setSupportMultipleSpringServices(boolean supportMultipleSpringServices) { + this.supportMultipleSpringServices = supportMultipleSpringServices; + } + + public void setTestDataControlFile(File testDataControlFile) { + this.testDataControlFile = testDataControlFile; + } + + public void setTestDataFile(File testDataFile) { + this.testDataFile = testDataFile; + } + + @Override + public String toDefaultValue(Schema p) { + if (ModelUtils.isGenerateAliasAsModel() && StringUtils.isNotEmpty(p.get$ref())) { + Schema ref = ModelUtils.getReferencedSchema(this.openAPI, p); + if (ModelUtils.isArraySchema(ref) || ModelUtils.isMapSchema(ref)) { + String typeDeclaration = getTypeDeclaration(p); + return String.format(Locale.ROOT, "new %s()", typeDeclaration); + } + } + return super.toDefaultValue(p); + } +} diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/features/CXFExtServerFeatures.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/features/CXFExtServerFeatures.java new file mode 100644 index 00000000000..679ec0a24c2 --- /dev/null +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/features/CXFExtServerFeatures.java @@ -0,0 +1,20 @@ +package org.openapitools.codegen.languages.features; + +import java.io.File; + +public interface CXFExtServerFeatures extends CXFServerFeatures { + + String GENERATE_OPERATION_BODY = "generateOperationBody"; + String SUPPORT_MULTIPLE_SPRING_SERVICES = "supportMultipleSpringServices"; + String TEST_DATA_FILE = "testDataFile"; + String TEST_DATA_CONTROL_FILE = "testDataControlFile"; + + void setGenerateOperationBody(boolean generateOperationBody); + + void setLoadTestDataFromFile(boolean loadTestDataFromFile); + + void setTestDataFile(File testDataFile); + + void setTestDataControlFile(File testDataControlFile); + +} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/features/CXFServerFeatures.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/features/CXFServerFeatures.java index cb89facbc9d..4a23170c05d 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/features/CXFServerFeatures.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/features/CXFServerFeatures.java @@ -33,6 +33,8 @@ public interface CXFServerFeatures public static final String GENERATE_NON_SPRING_APPLICATION = "generateNonSpringApplication"; + public static final String LOAD_TEST_DATA_FROM_FILE = "loadTestDataFromFile"; + public void setUseWadlFeature(boolean useWadlFeature); public void setUseMultipartFeature(boolean useMultipartFeature); @@ -42,5 +44,4 @@ public interface CXFServerFeatures public void setUseAnnotatedBasePath(boolean useAnnotatedBasePath); public void setGenerateNonSpringApplication(boolean generateNonSpringApplication); - } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/utils/ImplementationVersion.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/utils/ImplementationVersion.java index a97606e54dc..1a144200183 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/utils/ImplementationVersion.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/utils/ImplementationVersion.java @@ -21,10 +21,12 @@ public class ImplementationVersion { public static String read() { // Assumes this version is required at runtime. This could be modified to use a properties file like the CLI. String compiledVersion = ImplementationVersion.class.getPackage().getImplementationVersion(); - if(compiledVersion != null) { + if (compiledVersion != null) { return compiledVersion; } - return "unset"; + // When running non-JARed class within an IDE the implementation version is not available, so we provide a means + // to set it externally via a system property so that generated artefacts contain the correct version. + return System.getProperty("openapitools.implementation.version", "unset"); } } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/utils/JsonCache.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/utils/JsonCache.java new file mode 100644 index 00000000000..561d1e6e53b --- /dev/null +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/utils/JsonCache.java @@ -0,0 +1,1512 @@ +/* + * Copyright 2019 OpenAPI-Generator Contributors (https://openapi-generator.tech) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openapitools.codegen.utils; + +import java.io.File; +import java.io.InputStream; +import java.io.OutputStream; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.util.List; + +import com.fasterxml.jackson.core.JsonPointer; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.JsonNodeType; + +/** + * An interface for querying and mutating a JSON object graph. Clients indicate the location within the graph at which a + * value is to be read or written using a JSON Pointer as either a + * string or a JsonPointer instance. The latter is more efficient for repeated access to the same location. + * For the set(ptr|path, value) and getXxx(ptr|path, defaultValue)methods, the cache + * automatically creates missing container elements in the path as either object or array nodes according to whether the + * corresponding path segment is a property name or an integer index respectively, and creates the leaf element as a + * JSON value node of the appropriate type. Existing tree elements identified by a JSON pointer must match the pointer + * segments by type; that is, an existing parent of an integer path segment must be an array node and existing + * parent of a property name path segment must be an object node: if this condition is not met, the method throws + * a {@linkplain CacheException}. Note that it is possible to store the same object at multiple locations + * within the tree (thus converting the tree to a graph), in which case the same object may be retrieved using + * any of the corresponding paths. However, this shared object becomes multiple independent objects when serialised to + * JSON and if subsequently loaded into a cache instance. Such graphs must be acyclic: storing a cyclic graph in + * the tree will cause a stack overflow when the cache is saved. Instances are not guaranteed threadsafe and require + * external synchronisation if mutator methods may be called concurrently from multiple threads. Sparse arrays are not + * supported - all array elements have a value, even if it is null. + *

+ * N.B. some getXxx() methods can return mutable objects, mutations to which will be unobserved by the + * cache instance, thus compromising the reliability of the flush*() methods. Callers relying on these + * methods should either not mutate such objects or they should call the appropriate set() method + * afterwards to ensure that the cache's 'modified' flag is set. + *

+ * + * @author Adrian Price, TIBCO Software Inc. + * @since 4.0.0 + */ +public interface JsonCache { + /** + * Exception thrown by cache operations. Not intended to be created by client code. + */ + class CacheException extends Exception { + private static final long serialVersionUID = -1215367978375557620L; + + CacheException(String message) { + super(message); + } + + CacheException(Throwable cause) { + super(cause); + } + } + + /** + * A factory for creating JSON cache root instances. + */ + interface Factory { + /** + * The singleton factory instance. + */ + Factory instance = JsonCacheImpl.FactoryImpl.instance; + + /** + * Returns a new cache root instance. + * + * @return A new instance. + */ + Root create(); + + /** + * Returns the singleton cache root instance for the specified key. The same instance is returned every time the + * method is called with the same key value, being lazily created on the first such call. + * + * @param key The instance key. + * @return The singleton instance for key. + */ + Root get(String key); + } + + /** + * Load/merge/save/flush functionality implemented by the root of a JSON cache hierarchy. + */ + interface Root extends JsonCache { + /** + * Describes cache behaviour when a load method is called for a cache instance that is already loaded. + */ + enum MergePolicy { + /** + * Calls to load() methods are ignored when the cache is already loaded. + */ + NO_MERGE, + /** + * Recursively merges the incoming tree into the existing tree, retaining existing leaf properties. + */ + MERGE_RECURSIVE, + /** + * Retains existing root properties, ignoring incoming duplicate properties. + */ + KEEP_EXISTING, + /** + * Overwrites existing root properties with incoming duplicate properties. + */ + OVERWRITE_EXISTING + } + + ; + + /** + * If the cache is dirty, saves the object graph in JSON format to the specified file. + * + * @param file The output file. + * @return The receiver, to allow chaining. + * @throws CacheException if the root node does not exist or if unable to create or write the file. + * @throws NullPointerException if file is null. + * @see #flushOnShutdown(File) + * @see #save(File) + */ + Root flush(File file) throws CacheException; + + /** + * If the cache is dirty, saves the object graph in JSON format to the specified stream. + * + * @param out The output stream, which is closed before the method returns. + * @return The receiver, to allow chaining. + * @throws CacheException if the root node does not exist or if unable to create or write the file. + * @throws NullPointerException if out is null. + * @see #flushOnShutdown(OutputStream) + * @see #save(OutputStream) + */ + Root flush(OutputStream out) throws CacheException; + + /** + * Makes a best-effort attempt to ensure that the cache gets flushed to a disk file if dirty on shutdown. The + * call has no additional effect if the shutdown hook has already been registered. + * + * @param file The output file. + * @return The receiver, to allow chaining. + * @throws NullPointerException if file is null. + * @see #save(File) + */ + Root flushOnShutdown(File file); + + /** + * Makes a best-effort attempt to ensure that the cache gets flushed to an output stream if dirty on shutdown. + * The call has no additional effect if the shutdown hook has already been registered. + * + * @param out The output stream, which is closed after writing it on shutdown. + * @return The receiver, to allow chaining. + * @throws NullPointerException if out is null. + * @see #save(OutputStream) + */ + Root flushOnShutdown(OutputStream out); + + /** + * Returns the mapper used for JSON-object marshalling and serialisation operations. Callers may configure the + * mapper to achieve the desired JSON serialisation format. + * + * @return The mapper. + * @see #mapper(ObjectMapper) + */ + ObjectMapper getMapper(); + + /** + * Returns the merge policy that applies when load() is called on a cache that is already loaded. + * The default is {@link MergePolicy#MERGE_RECURSIVE}; + * + * @return The merge policy. + * @see #mergePolicy(MergePolicy) + */ + MergePolicy getMergePolicy(); + + /** + * Indicates whether the cached has unsaved changes. + * + * @return true if there are unsaved changes. + */ + boolean isDirty(); + + /** + * Loads the cache from the specified file. If the cache is already loaded, merges the incoming tree according + * to the current {@link #mergePolicy(MergePolicy) merge policy}. The call has no effect if the file does not + * exist. + * + * @param file The JSON file to load. + * @return The receiver, to allow chaining. + * @throws CacheException if the file exists but could not be read or its content is not valid JSON. + * @throws NullPointerException if file is null. + * @see #save(File) + * @see #save(OutputStream) + * @see #unload() + */ + Root load(File file) throws CacheException; + + /** + * Loads the cache from the specified stream. If the cache is already loaded, merges the incoming tree according + * to the current {@link #mergePolicy(MergePolicy) merge policy}. + * + * @param in The input stream from which to load, which is closed before the method returns. + * @return The receiver, to allow chaining. + * @throws CacheException if the stream content is not valid JSON. + * @throws NullPointerException if in is null. + * @see #save(File) + * @see #save(OutputStream) + * @see #unload() + */ + Root load(InputStream in) throws CacheException; + + /** + * Sets the mapper to use for JSON-object marshalling and serialisation operations. + * + * @param mapper The new mapper. + * @return The receiver, to allow chaining. + * @throws NullPointerException if mapper is null. + * @see #getMapper() + */ + Root mapper(ObjectMapper mapper); + + /** + * Sets the merge policy that applies when load() is called for a cache that is already loaded. + * + * @param policy The merge policy. + * @return The receiver, to allow chaining. + * @throws NullPointerException if policy is null. + * @see #getMergePolicy() + */ + Root mergePolicy(MergePolicy policy); + + /** + * Saves the object graph in JSON format to the specified file. + * + * @param file The output file. + * @return The receiver, to allow chaining. + * @throws NullPointerException if file is null. + * @throws CacheException if the root node does not exist or if unable to create or write the file. + */ + Root save(File file) throws CacheException; + + /** + * Saves the object graph in JSON format to the specified stream. + * + * @param out The output stream, which is closed before the method returns. + * @return The receiver, to allow chaining. + * @throws NullPointerException if out is null. + * @throws CacheException if the root node does not exist or if unable to create or write the file. + */ + Root save(OutputStream out) throws CacheException; + + /** + * Unloads the object graph, setting the root node to null. + * + * @return The receiver, to allow chaining. + * @see #load(File) + * @see #load(InputStream) + */ + Root unload(); + } + + /** + * Adds a BigDecimal to an array. The array is created if it does not already exist. + * + * @param ptr A pointer to the property to set. If the last segment is a positive integer less than the current + * array size, value is inserted at the specified index; otherwise, it is appended to the + * end of the array. + * @param value The value to add. + * @return The receiver, to support chaining. + * @throws CacheException if ptr is not a valid path within the object graph managed by the receiver. + */ + JsonCache add(JsonPointer ptr, BigDecimal value) throws CacheException; + + /** + * Adds a BigInteger to an array. The array is created if it does not already exist. + * + * @param ptr A pointer to the property to set. If the last segment is a positive integer less than the current + * array size, value is inserted at the specified index; otherwise, it is appended to the + * end of the array. + * @param value The value to add. + * @return The receiver, to support chaining. + * @throws CacheException if ptr is not a valid path within the object graph managed by the receiver. + */ + JsonCache add(JsonPointer ptr, BigInteger value) throws CacheException; + + /** + * Adds a boolean to an array. The array is created if it does not already exist. + * + * @param ptr A pointer to the property to set. If the last segment is a positive integer less than the current + * array size, value is inserted at the specified index; otherwise, it is appended to the + * end of the array. + * @param value The value to add. + * @return The receiver, to support chaining. + * @throws CacheException if ptr is not a valid path within the object graph managed by the receiver. + */ + JsonCache add(JsonPointer ptr, boolean value) throws CacheException; + + /** + * Adds a double value to an array. The array is created if it does not already exist. + * + * @param ptr A pointer to the property to set. If the last segment is a positive integer less than the current + * array size, value is inserted at the specified index; otherwise, it is appended to the + * end of the array. + * @param value The value to add. + * @return The receiver, to support chaining. + * @throws CacheException if ptr is not a valid path within the object graph managed by the receiver. + */ + JsonCache add(JsonPointer ptr, double value) throws CacheException; + + /** + * Adds a float value to an array. The array is created if it does not already exist. + * + * @param ptr A pointer to the property to set. If the last segment is a positive integer less than the current + * array size, value is inserted at the specified index; otherwise, it is appended to the + * end of the array. + * @param value The value to add. + * @return The receiver, to support chaining. + * @throws CacheException if ptr is not a valid path within the object graph managed by the receiver. + */ + JsonCache add(JsonPointer ptr, float value) throws CacheException; + + /** + * Adds an int value to an array. The array is created if it does not already exist. + * + * @param ptr A pointer to the property to set. If the last segment is a positive integer less than the current + * array size, value is inserted at the specified index; otherwise, it is appended to the + * end of the array. + * @param value The value to add. + * @return The receiver, to support chaining. + * @throws CacheException if ptr is not a valid path within the object graph managed by the receiver. + */ + JsonCache add(JsonPointer ptr, int value) throws CacheException; + + /** + * Adds a long value to an array. The array is created if it does not already exist. + * + * @param ptr A pointer to the property to set. If the last segment is a positive integer less than the current + * array size, value is inserted at the specified index; otherwise, it is appended to the + * end of the array. + * @param value The value to add. + * @return The receiver, to support chaining. + * @throws CacheException if ptr is not a valid path within the object graph managed by the receiver. + */ + JsonCache add(JsonPointer ptr, long value) throws CacheException; + + /** + * Adds an object to an array. The array is created if it does not already exist. + * + * @param ptr A pointer to the property to set. If the last segment is a positive integer less than the current + * array size, value is inserted at the specified index; otherwise, it is appended to the + * end of the array. + * @param value The value to add. + * @return The receiver, to support chaining. + * @throws CacheException if ptr is not a valid path within the object graph managed by the receiver. + */ + JsonCache add(JsonPointer ptr, Object value) throws CacheException; + + /** + * Adds a short value to an array. The array is created if it does not already exist. + * + * @param ptr A pointer to the property to set. If the last segment is a positive integer less than the current + * array size, value is inserted at the specified index; otherwise, it is appended to the + * end of the array. + * @param value The value to add. + * @return The receiver, to support chaining. + * @throws CacheException if ptr is not a valid path within the object graph managed by the receiver. + */ + JsonCache add(JsonPointer ptr, short value) throws CacheException; + + /** + * Adds a BigDecimal to an array. The array is created if it does not already exist. + * + * @param path A JSON Pointer expression for the property to set. If the last segment is a positive integer less + * than the current array size, value is inserted at the specified index; otherwise, it is + * appended to the end of the array. + * @param value The value to add. + * @return The receiver, to support chaining. + * @throws IllegalArgumentException if path is not a valid JSON path expression. + * @throws CacheException if path is not a valid path within the object graph managed by the + * receiver. + */ + JsonCache add(String path, BigDecimal value) throws CacheException; + + /** + * Adds a BigInteger to an array. The array is created if it does not already exist. + * + * @param path A JSON Pointer expression for the property to set. If the last segment is a positive integer less + * than the current array size, value is inserted at the specified index; otherwise, it is + * appended to the end of the array. + * @param value The value to add. + * @return The receiver, to support chaining. + * @throws IllegalArgumentException if path is not a valid JSON path expression. + * @throws CacheException if path is not a valid path within the object graph managed by the + * receiver. + */ + JsonCache add(String path, BigInteger value) throws CacheException; + + /** + * Adds a boolean value to an array. The array is created if it does not already exist. + * + * @param path A JSON Pointer expression for the property to set. If the last segment is a positive integer less + * than the current array size, value is inserted at the specified index; otherwise, it is + * appended to the end of the array. + * @param value The value to add. + * @return The receiver, to support chaining. + * @throws IllegalArgumentException if path is not a valid JSON path expression. + * @throws CacheException if path is not a valid path within the object graph managed by the + * receiver. + */ + JsonCache add(String path, boolean value) throws CacheException; + + /** + * Adds a double value to an array. The array is created if it does not already exist. + * + * @param path A JSON Pointer expression for the property to set. If the last segment is a positive integer less + * than the current array size, value is inserted at the specified index; otherwise, it is + * appended to the end of the array. + * @param value The value to add. + * @return The receiver, to support chaining. + * @throws IllegalArgumentException if path is not a valid JSON path expression. + * @throws CacheException if path is not a valid path within the object graph managed by the + * receiver. + */ + JsonCache add(String path, double value) throws CacheException; + + /** + * Adds a float value to an array. The array is created if it does not already exist. + * + * @param path A JSON Pointer expression for the property to set. If the last segment is a positive integer less + * than the current array size, value is inserted at the specified index; otherwise, it is + * appended to the end of the array. + * @param value The value to add. + * @return The receiver, to support chaining. + * @throws IllegalArgumentException if path is not a valid JSON path expression. + * @throws CacheException if path is not a valid path within the object graph managed by the + * receiver. + */ + JsonCache add(String path, float value) throws CacheException; + + /** + * Adds an int value to an array. The array is created if it does not already exist. + * + * @param path A JSON Pointer expression for the property to set. If the last segment is a positive integer less + * than the current array size, value is inserted at the specified index; otherwise, it is + * appended to the end of the array. + * @param value The value to add. + * @return The receiver, to support chaining. + * @throws IllegalArgumentException if path is not a valid JSON path expression. + * @throws CacheException if path is not a valid path within the object graph managed by the + * receiver. + */ + JsonCache add(String path, int value) throws CacheException; + + /** + * Adds a long value to an array. The array is created if it does not already exist. + * + * @param path A JSON Pointer expression for the property to set. If the last segment is a positive integer less + * than the current array size, value is inserted at the specified index; otherwise, it is + * appended to the end of the array. + * @param value The value to add. + * @return The receiver, to support chaining. + * @throws IllegalArgumentException if path is not a valid JSON path expression. + * @throws CacheException if path is not a valid path within the object graph managed by the + * receiver. + */ + JsonCache add(String path, long value) throws CacheException; + + /** + * Adds an object to an array. The array is created if it does not already exist. + * + * @param path A JSON Pointer expression for the property to set. If the last segment is a positive integer less + * than the current array size, value is inserted at the specified index; otherwise, it is + * appended to the end of the array. + * @param value The value to add. + * @return The receiver, to support chaining. + * @throws IllegalArgumentException if path is not a valid JSON path expression. + * @throws CacheException if path is not a valid path within the object graph managed by the + * receiver. + */ + JsonCache add(String path, Object value) throws CacheException; + + /** + * Adds a short value to an array. The array is created if it does not already exist. + * + * @param path A JSON Pointer expression for the property to set. If the last segment is a positive integer less + * than the current array size, value is inserted at the specified index; otherwise, it is + * appended to the end of the array. + * @param value The value to add. + * @return The receiver, to support chaining. + * @throws IllegalArgumentException if path is not a valid JSON path expression. + * @throws CacheException if path is not a valid path within the object graph managed by the + * receiver. + */ + JsonCache add(String path, short value) throws CacheException; + + /** + * Returns a child cache rooted at the given location relative to the receiver's base pointer. + * + * @param ptr A pointer to the subtree managed by the new cache. + * @return The child cache. + * @throws NullPointerException if ptr is null. + */ + JsonCache child(JsonPointer ptr); + + /** + * Returns a child cache rooted at the given location relative to the receiver's base pointer. + * + * @param path A JSON Pointer expression for the subtree managed by the new cache. Note that the expression must + * start with a forward slash character. + * @return The child cache. + * @throws IllegalArgumentException if path is not a valid JSON path expression. + */ + JsonCache child(String path); + + /** + * Deletes a property within the object graph managed by the receiver. + * + * @param ptr A pointer to the property to set. + * @throws CacheException if ptr is not a valid path within the object graph managed by the receiver. + */ + void delete(JsonPointer ptr) throws CacheException; + + /** + * Deletes a property within the object graph managed by the receiver. + * + * @param path A JSON Pointer expression for the property to set. + * @throws IllegalArgumentException if path is not a valid JSON path expression. + * @throws CacheException if ptr is not a valid path within the object graph managed by the + * receiver. + */ + void delete(String path) throws CacheException; + + /** + * Tests for the existence of the specified path within the object graph managed by the receiver. + * + * @param ptr A pointer to the path to test. + * @return true if a JSON node corresponding to ptr exists. + */ + boolean exists(JsonPointer ptr); + + /** + * Tests for the existence of the specified path within the object graph managed by the receiver. + * + * @param path A JSON Pointer expression for the path to test. + * @return true if a JSON node corresponding to ptr exists. + */ + boolean exists(String path); + + /** + * Retrieves an Object value from within the graph. + * + * @param ptr A JSON Pointer expression for the value to return. + * @return the property value or null if not present. + * @throws CacheException if ptr is not a valid path within the object graph managed by the receiver. + */ + Object get(JsonPointer ptr) throws CacheException; + + /** + * Retrieves an Object value from within the graph. If the value is not present, stores + * defaultValue at the specified location and returns this value. + * + * @param ptr A pointer to the value to return. + * @param defaultValue The default value to return if ptr is not present in the graph. + * @return the property value or defaultValue if not present. + * @throws CacheException if ptr is not a valid path within the object graph managed by the receiver. + */ + Object get(JsonPointer ptr, Object defaultValue) throws CacheException; + + /** + * Retrieves an Object value from within the graph. + * + * @param path A pointer to the value to return. + * @return the property value or null if not present. + * @throws CacheException if path is not a valid path within the object graph managed by the + * receiver. + * @throws IllegalArgumentException if path is not a valid JSON path expression. + */ + Object get(String path) throws CacheException; + + /** + * Retrieves an Object value from within the graph. If the value is not present, stores + * defaultValue at the specified location and returns this value. + * + * @param path A JSON Pointer expression for the value to return. + * @param defaultValue The default value to return if path is not present in the graph. + * @return the property value or defaultValue if not present. + * @throws CacheException if path is not a valid path within the object graph managed by the + * receiver. + * @throws IllegalArgumentException if path is not a valid JSON path expression. + */ + Object get(String path, Object defaultValue) throws CacheException; + + /** + * Retrieves a BigDecimal value from within the graph. + * + * @param ptr A pointer to the value to retrieve. + * @return the property value or null if not present. + * @throws CacheException if ptr is not a valid path within the object graph managed by the receiver. + */ + BigDecimal getBigDecimal(JsonPointer ptr) throws CacheException; + + /** + * Retrieves a BigDecimal value from within the graph. If the value is not present, stores + * defaultValue at the specified location and returns this value. + * + * @param ptr A pointer to the value to return. + * @param defaultValue The default value to return if ptr is not present in the graph. + * @return the property value or defaultValue if not present. + * @throws CacheException if ptr is not a valid path within the object graph managed by the receiver. + */ + BigDecimal getBigDecimal(JsonPointer ptr, BigDecimal defaultValue) throws CacheException; + + /** + * Retrieves a BigDecimal value from within the graph. + * + * @param path A JSON Pointer expression for the value to retrieve. + * @return the property value or null if not present. + * @throws CacheException if path is not a valid path within the object graph managed by the + * receiver. + * @throws IllegalArgumentException if path is not a valid JSON path expression. + */ + BigDecimal getBigDecimal(String path) throws CacheException; + + /** + * Retrieves a BigDecimal value from within the graph. If the value is not present, stores + * defaultValue at the specified location and returns this value. + * + * @param path A JSON Pointer expression for the value to return. + * @param defaultValue The default value to return if path is not present in the graph. + * @return the property value or defaultValue if not present. + * @throws CacheException if path is not a valid path within the object graph managed by the + * receiver. + * @throws IllegalArgumentException if path is not a valid JSON path expression. + */ + BigDecimal getBigDecimal(String path, BigDecimal defaultValue) throws CacheException; + + /** + * Retrieves a BigInteger value from within the graph. + * + * @param ptr A pointer to the value to retrieve. + * @return the property value or null if not present. + * @throws CacheException if ptr is not a valid path within the object graph managed by the receiver. + */ + BigInteger getBigInteger(JsonPointer ptr) throws CacheException; + + /** + * Retrieves a BigInteger value from within the graph. If the value is not present, stores + * defaultValue at the specified location and returns this value. + * + * @param ptr A JSON Pointer expression for the value to return. + * @param defaultValue The default value to return if ptr is not present in the graph. + * @return the property value or defaultValue if not present. + * @throws CacheException if ptr is not a valid path within the object graph managed by the receiver. + */ + BigInteger getBigInteger(JsonPointer ptr, BigInteger defaultValue) throws CacheException; + + /** + * Retrieves a BigInteger value from within the graph. + * + * @param path A JSON Pointer expression for the value to retrieve. + * @return the property value or null if not present. + * @throws CacheException if path is not a valid path within the object graph managed by the + * receiver. + * @throws IllegalArgumentException if path is not a valid JSON path expression. + */ + BigInteger getBigInteger(String path) throws CacheException; + + /** + * Retrieves a BigInteger value from within the graph. If the value is not present, stores + * defaultValue at the specified location and returns this value. + * + * @param path A JSON Pointer expression for the value to return. + * @param defaultValue The default value to return if path is not present in the graph. + * @return the property value or defaultValue if not present. + * @throws CacheException if path is not a valid path within the object graph managed by the + * receiver. + * @throws IllegalArgumentException if path is not a valid JSON path expression. + */ + BigInteger getBigInteger(String path, BigInteger defaultValue) throws CacheException; + + /** + * Retrieves a byte[] value from within the graph. + * + * @param ptr A pointer to the value to retrieve. + * @return the property value or null if not present. + * @throws CacheException if ptr is not a valid path within the object graph managed by the receiver. + */ + byte[] getBinary(JsonPointer ptr) throws CacheException; + + /** + * Retrieves a byte[] value from within the graph. If the value is not present, stores + * defaultValue at the specified location and returns this value. + * + * @param ptr A JSON Pointer expression for the value to return. + * @param defaultValue The default value to return if ptr is not present in the graph. + * @return the property value or defaultValue if not present. + * @throws CacheException if ptr is not a valid path within the object graph managed by the receiver. + */ + byte[] getBinary(JsonPointer ptr, byte[] defaultValue) throws CacheException; + + /** + * Retrieves a byte[] value from within the graph. + * + * @param path A JSON Pointer expression for the value to retrieve. + * @return the property value or null if not present. + * @throws CacheException if path is not a valid path within the object graph managed by the + * receiver. + * @throws IllegalArgumentException if path is not a valid JSON path expression. + */ + byte[] getBinary(String path) throws CacheException; + + /** + * Retrieves a byte[] value from within the graph. If the value is not present, stores + * defaultValue at the specified location and returns this value. + * + * @param path A JSON Pointer expression for the value to return. + * @param defaultValue The default value to return if path is not present in the graph. + * @return the property value or defaultValue if not present. + * @throws CacheException if path is not a valid path within the object graph managed by the + * receiver. + * @throws IllegalArgumentException if path is not a valid JSON path expression. + */ + byte[] getBinary(String path, byte[] defaultValue) throws CacheException; + + /** + * Retrieves a boolean value from within the graph. + * + * @param ptr A pointer to the value to retrieve. + * @return the property value or false if not present. + * @throws CacheException if ptr is not a valid path within the object graph managed by the receiver. + */ + boolean getBoolean(JsonPointer ptr) throws CacheException; + + /** + * Retrieves a boolean value from within the graph. If the value is not present, stores + * defaultValue at the specified location and returns this value. + * + * @param ptr A JSON Pointer expression for the value to return. + * @param defaultValue The default value to return if ptr is not present in the graph. + * @return the property value or defaultValue if not present. + * @throws CacheException if ptr is not a valid path within the object graph managed by the receiver. + */ + boolean getBoolean(JsonPointer ptr, boolean defaultValue) throws CacheException; + + /** + * Retrieves a boolean value from within the graph. + * + * @param path A JSON Pointer expression for the value to retrieve. + * @return the property value or false if not present. + * @throws CacheException if path is not a valid path within the object graph managed by the + * receiver. + * @throws IllegalArgumentException if path is not a valid JSON path expression. + */ + boolean getBoolean(String path) throws CacheException; + + /** + * Retrieves a boolean value from within the graph. If the value is not present, stores + * defaultValue at the specified location and returns this value. + * + * @param path A JSON Pointer expression for the value to return. + * @param defaultValue The default value to return if path is not present in the graph. + * @return the property value or defaultValue if not present. + * @throws CacheException if path is not a valid path within the object graph managed by the + * receiver. + * @throws IllegalArgumentException if path is not a valid JSON path expression. + */ + boolean getBoolean(String path, boolean defaultValue) throws CacheException; + + /** + * Retrieves a double value from within the graph. + * + * @param ptr A pointer to the value to retrieve. + * @return the property value or 0.0D if not present. + * @throws CacheException if ptr is not a valid path within the object graph managed by the receiver. + */ + double getDouble(JsonPointer ptr) throws CacheException; + + /** + * Retrieves a double value from within the graph. If the value is not present, stores + * defaultValue at the specified location and returns this value. + * + * @param ptr A JSON Pointer expression for the value to return. + * @param defaultValue The default value to return if ptr is not present in the graph. + * @return the property value or defaultValue if not present. + * @throws CacheException if ptr is not a valid path within the object graph managed by the receiver. + */ + double getDouble(JsonPointer ptr, double defaultValue) throws CacheException; + + /** + * Retrieves a double value from within the graph. + * + * @param path A JSON Pointer expression for the value to retrieve. + * @return the property value or 0.0D if not present. + * @throws CacheException if path is not a valid path within the object graph managed by the + * receiver. + * @throws IllegalArgumentException if path is not a valid JSON path expression. + */ + double getDouble(String path) throws CacheException; + + /** + * Retrieves a double value from within the graph. If the value is not present, stores + * defaultValue at the specified location and returns this value. + * + * @param path A JSON Pointer expression for the value to return. + * @param defaultValue The default value to return if path is not present in the graph. + * @return the property value or defaultValue if not present. + * @throws CacheException if path is not a valid path within the object graph managed by the + * receiver. + * @throws IllegalArgumentException if path is not a valid JSON path expression. + */ + double getDouble(String path, double defaultValue) throws CacheException; + + /** + * Retrieves a float value from within the graph. + * + * @param ptr A pointer to the value to retrieve. + * @return the property value or 0.0F if not present. + * @throws CacheException if ptr is not a valid path within the object graph managed by the receiver. + */ + float getFloat(JsonPointer ptr) throws CacheException; + + /** + * Retrieves a float value from within the graph. If the value is not present, stores + * defaultValue at the specified location and returns this value. + * + * @param ptr A JSON Pointer expression for the value to return. + * @param defaultValue The default value to return if ptr is not present in the graph. + * @return the property value or defaultValue if not present. + * @throws CacheException if ptr is not a valid path within the object graph managed by the receiver. + */ + float getFloat(JsonPointer ptr, float defaultValue) throws CacheException; + + /** + * Retrieves a float value from within the graph. + * + * @param path A JSON Pointer expression for the value to retrieve. + * @return the property value or 0.0F if not present. + * @throws CacheException if path is not a valid path within the object graph managed by the + * receiver. + * @throws IllegalArgumentException if path is not a valid JSON path expression. + */ + float getFloat(String path) throws CacheException; + + /** + * Retrieves a float value from within the graph. If the value is not present, stores + * defaultValue at the specified location and returns this value. + * + * @param path A JSON Pointer expression for the value to return. + * @param defaultValue The default value to return if path is not present in the graph. + * @return the property value or defaultValue if not present. + * @throws CacheException if path is not a valid path within the object graph managed by the + * receiver. + * @throws IllegalArgumentException if path is not a valid JSON path expression. + */ + float getFloat(String path, float defaultValue) throws CacheException; + + /** + * Retrieves an int value from within the graph. + * + * @param ptr A pointer to the value to retrieve. + * @return the property value or 0 if not present. + * @throws CacheException if ptr is not a valid path within the object graph managed by the receiver. + */ + int getInt(JsonPointer ptr) throws CacheException; + + /** + * Retrieves an int value from within the graph. If the value is not present, stores + * defaultValue at the specified location and returns this value. + * + * @param ptr A JSON Pointer expression for the value to return. + * @param defaultValue The default value to return if ptr is not present in the graph. + * @return the property value or defaultValue if not present. + * @throws CacheException if ptr is not a valid path within the object graph managed by the receiver. + */ + int getInt(JsonPointer ptr, int defaultValue) throws CacheException; + + /** + * Retrieves an int value from within the graph. + * + * @param path A JSON Pointer expression for the value to retrieve. + * @return the property value or 0 if not present. + * @throws CacheException if path is not a valid path within the object graph managed by the + * receiver. + * @throws IllegalArgumentException if path is not a valid JSON path expression. + */ + int getInt(String path) throws CacheException; + + /** + * Retrieves an int value from within the graph. If the value is not present, stores + * defaultValue at the specified location and returns this value. + * + * @param path A JSON Pointer expression for the value to return. + * @param defaultValue The default value to return if path is not present in the graph. + * @return the property value or defaultValue if not present. + * @throws CacheException if path is not a valid path within the object graph managed by the + * receiver. + * @throws IllegalArgumentException if path is not a valid JSON path expression. + */ + int getInt(String path, int defaultValue) throws CacheException; + + /** + * Retrieves a long value from within the graph. + * + * @param ptr A pointer to the value to retrieve. + * @return the property value or 0L if not present. + * @throws CacheException if ptr is not a valid path within the object graph managed by the receiver. + */ + long getLong(JsonPointer ptr) throws CacheException; + + /** + * Retrieves a long value from within the graph. If the value is not present, stores + * defaultValue at the specified location and returns this value. + * + * @param ptr A JSON Pointer expression for the value to return. + * @param defaultValue The default value to return if ptr is not present in the graph. + * @return the property value or defaultValue if not present. + * @throws CacheException if ptr is not a valid path within the object graph managed by the receiver. + */ + long getLong(JsonPointer ptr, long defaultValue) throws CacheException; + + /** + * Retrieves a long value from within the graph. + * + * @param path A JSON Pointer expression for the value to retrieve. + * @return the property value or 0L if not present. + * @throws CacheException if path is not a valid path within the object graph managed by the + * receiver. + * @throws IllegalArgumentException if path is not a valid JSON path expression. + */ + long getLong(String path) throws CacheException; + + /** + * Retrieves a long value from within the graph. If the value is not present, stores + * defaultValue at the specified location and returns this value. + * + * @param path A JSON Pointer expression for the value to return. + * @param defaultValue The default value to return if path is not present in the graph. + * @return the property value or defaultValue if not present. + * @throws CacheException if path is not a valid path within the object graph managed by the + * receiver. + * @throws IllegalArgumentException if path is not a valid JSON path expression. + */ + long getLong(String path, long defaultValue) throws CacheException; + + /** + * Returns the node type at the specified location in the object graph. + * + * @param ptr A pointer to the node to test. + * @return The node type. + */ + JsonNodeType getNodeType(JsonPointer ptr); + + /** + * Returns the node type at the specified location in the object graph. + * + * @param path A JSON Pointer expression for the node to test. + * @return The node type. + */ + JsonNodeType getNodeType(String path); + + /** + * Retrieves a Number value from within the graph. + * + * @param ptr A pointer to the value to retrieve. + * @return the property value or null if not present. + * @throws CacheException if ptr is not a valid path within the object graph managed by the receiver. + */ + Number getNumber(JsonPointer ptr) throws CacheException; + + /** + * Retrieves a Number value from within the graph. If the value is not present, stores + * defaultValue at the specified location and returns this value. + * + * @param ptr A JSON Pointer expression for the value to return. + * @param defaultValue The default value to return if ptr is not present in the graph. + * @return the property value or defaultValue if not present. + * @throws CacheException if ptr is not a valid path within the object graph managed by the receiver. + */ + Number getNumber(JsonPointer ptr, Number defaultValue) throws CacheException; + + /** + * Retrieves a Number value from within the graph. + * + * @param path A JSON Pointer expression for the value to retrieve. + * @return the property value or null if not present. + * @throws CacheException if path is not a valid path within the object graph managed by the + * receiver. + * @throws IllegalArgumentException if path is not a valid JSON path expression. + */ + Number getNumber(String path) throws CacheException; + + /** + * Retrieves a Number value from within the graph. If the value is not present, stores + * defaultValue at the specified location and returns this value. + * + * @param path A JSON Pointer expression for the value to return. + * @param defaultValue The default value to return if path is not present in the graph. + * @return the property value or defaultValue if not present. + * @throws CacheException if path is not a valid path within the object graph managed by the + * receiver. + * @throws IllegalArgumentException if path is not a valid JSON path expression. + */ + Number getNumber(String path, Number defaultValue) throws CacheException; + + /** + * Retrieves a typed object value from within the graph. + * + * @param The type of object to return. + * @param ptr A pointer to the value to return. + * @param type The type of object to return. + * @return the property value or null if not present. + * @throws CacheException if ptr is not a valid path within the object graph managed by the receiver or + * if the node could not be converted to the requested type. + */ + T getObject(JsonPointer ptr, Class type) throws CacheException; + + /** + * Retrieves a typed object value from within the graph. If the value is not present, stores + * defaultValue at the specified location and returns this value. + * + * @param The type of the object to return. + * @param ptr A pointer to the value to return. + * @param defaultValue The default value to return if ptr is not present in the graph. + * @return the property value or defaultValue if not present. + * @throws CacheException if ptr is not a valid path within the object graph managed by the receiver or + * if the node could not be converted to the requested type. + */ + T getObject(JsonPointer ptr, T defaultValue) throws CacheException; + + /** + * Retrieves a typed object value from within the graph. + * + * @param The type of object to return. + * @param path A JSON pointer expression for the value to return. + * @param type The type of object to return. + * @return the property value or null if not present. + * @throws CacheException if path is not a valid path within the object graph managed by the + * receiver or if the node could not be converted to the requested type. + * @throws IllegalArgumentException if path is not a valid JSON path expression. + */ + T getObject(String path, Class type) throws CacheException; + + /** + * Retrieves a typed object value from within the graph. If the value is not present, stores + * defaultValue at the specified location and returns this value. + * + * @param The type of the object to return. + * @param path A JSON pointer expression for the value to return. + * @param defaultValue The default value to return if path is not present in the graph. + * @return the property value or defaultValue if not present. + * @throws CacheException if path is not a valid path within the object graph managed by the + * receiver or if the node could not be converted to the requested type. + * @throws IllegalArgumentException if path is not a valid JSON path expression. + */ + T getObject(String path, T defaultValue) throws CacheException; + + /** + * Retrieves a typed list of objects from within the graph. + * + * @param The list element type. + * @param ptr A pointer to the values to return. + * @param type The list element type. + * @return the property values. + * @throws CacheException if ptr is not a valid path within the object graph managed by the receiver or + * if the nodes could not be converted to the requested type. + */ + List getObjects(JsonPointer ptr, Class type) throws CacheException; + + /** + * Retrieves a typed list of objects from within the graph. If the values are not present, stores + * defaultValue at the specified location and returns this value. + * + * @param The list element type. + * @param ptr A pointer to the values to return. + * @param type The list element type. + * @param defaultValue The default values to return if ptr is not present in the graph. + * @return the property values. + * @throws CacheException if ptr is not a valid path within the object graph managed by the receiver or + * if the nodes could not be converted to the requested type. + */ + List getObjects(JsonPointer ptr, Class type, List defaultValue) throws CacheException; + + /** + * Retrieves a typed list of objects from within the graph. + * + * @param The list element type. + * @param path A JSON Pointer expression for the values to return. + * @param type The list element type. + * @return the property values. + * @throws CacheException if path is not a valid path within the object graph managed by the + * receiver or if the nodes could not be converted to the requested type. + * @throws IllegalArgumentException if path is not a valid JSON path expression. + */ + List getObjects(String path, Class type) throws CacheException; + + /** + * Retrieves a typed list of objects from within the graph. If the values are not present, stores + * defaultValue at the specified location and returns this value. + * + * @param The list element type. + * @param path A JSON Pointer expression for the values to return. + * @param type The list element type. + * @param defaultValue The default values to return if path is not present in the graph. + * @return the property values. + * @throws CacheException if ptr is not a valid path within the object graph managed by the + * receiver or if the nodes could not be converted to the requested type. + * @throws IllegalArgumentException if path is not a valid JSON path expression. + */ + List getObjects(String path, Class type, List defaultValue) throws CacheException; + + /** + * Retrieves a short value from within the graph. + * + * @param ptr A pointer to the value to retrieve. + * @return the property value or 0 if not present. + * @throws CacheException if ptr is not a valid path within the object graph managed by the receiver. + */ + short getShort(JsonPointer ptr) throws CacheException; + + /** + * Retrieves a short value from within the graph. If the value is not present, stores + * defaultValue at the specified location and returns this value. + * + * @param ptr A JSON Pointer expression for the value to return. + * @param defaultValue The default value to return if ptr is not present in the graph. + * @return the property value or defaultValue if not present. + * @throws CacheException if ptr is not a valid path within the object graph managed by the receiver. + */ + short getShort(JsonPointer ptr, short defaultValue) throws CacheException; + + /** + * Retrieves a short value from within the graph. + * + * @param path A JSON Pointer expression for the value to retrieve. + * @return the property value or 0 if not present. + * @throws CacheException if path is not a valid path within the object graph managed by the + * receiver. + * @throws IllegalArgumentException if path is not a valid JSON path expression. + */ + short getShort(String path) throws CacheException; + + /** + * Retrieves a short value from within the graph. If the value is not present, stores + * defaultValue at the specified location and returns this value. + * + * @param path A JSON Pointer expression for the value to return. + * @param defaultValue The default value to return if path is not present in the graph. + * @return the property value or defaultValue if not present. + * @throws CacheException if path is not a valid path within the object graph managed by the + * receiver. + * @throws IllegalArgumentException if path is not a valid JSON path expression. + */ + short getShort(String path, short defaultValue) throws CacheException; + + /** + * Retrieves a String value from within the graph. + * + * @param ptr A pointer to the value to retrieve. + * @return the property value or null if not present. + * @throws CacheException if ptr is not a valid path within the object graph managed by the receiver. + */ + String getString(JsonPointer ptr) throws CacheException; + + /** + * Retrieves a String value from within the graph. If the value is not present, stores + * defaultValue at the specified location and returns this value. + * + * @param ptr A pointer to the value to return. + * @param defaultValue The default value to return if ptr is not present in the graph. + * @return the property value or defaultValue if not present. + * @throws CacheException if ptr is not a valid path within the object graph managed by the receiver. + */ + String getString(JsonPointer ptr, String defaultValue) throws CacheException; + + /** + * Retrieves a String value from within the graph. + * + * @param path A JSON Pointer expression for the value to retrieve. + * @return the property value or null if not present. + * @throws CacheException if path is not a valid path within the object graph managed by the + * receiver. + * @throws IllegalArgumentException if path is not a valid JSON path expression. + */ + String getString(String path) throws CacheException; + + /** + * Retrieves a String value from within the graph. If the value is not present, stores + * defaultValue at the specified location and returns this value. + * + * @param path A JSON Pointer expression for the value to return. + * @param defaultValue The default value to return if path is not present in the graph. + * @return the property value or defaultValue if not present. + * @throws CacheException if path is not a valid path within the object graph managed by the + * receiver. + * @throws IllegalArgumentException if path is not a valid JSON path expression. + */ + String getString(String path, String defaultValue) throws CacheException; + + /** + * Returns the parent cache of which this is a descendant. + * + * @return The parent cache, null if the receiver is the root cache. + */ + JsonCache parent(); + + /** + * Returns the root cache of which this is a descendant. + * + * @return The root cache. The root cache returns itself. + */ + Root root(); + + /** + * Sets a BigDecimal property within the object graph managed by the receiver. + * + * @param ptr A pointer to the property to set. + * @param value The value to set (can be null). + * @return The receiver, to allow chaining. + * @throws CacheException if ptr is not a valid path within the object graph managed by the receiver. + * @see #delete(JsonPointer) + */ + JsonCache set(JsonPointer ptr, BigDecimal value) throws CacheException; + + /** + * Sets a BigInteger property within the object graph managed by the receiver. + * + * @param ptr A pointer to the property to set. + * @param value The value to set (can be null). + * @return The receiver, to allow chaining. + * @throws CacheException if ptr is not a valid path within the object graph managed by the receiver. + * @see #delete(JsonPointer) + */ + JsonCache set(JsonPointer ptr, BigInteger value) throws CacheException; + + /** + * Sets a boolean property within the object graph managed by the receiver. + * + * @param ptr A pointer to the property to set. + * @param value The value to set. + * @return The receiver, to allow chaining. + * @throws CacheException if ptr is not a valid path within the object graph managed by the receiver. + * @see #delete(JsonPointer) + */ + JsonCache set(JsonPointer ptr, boolean value) throws CacheException; + + /** + * Sets a double property within the object graph managed by the receiver. + * + * @param ptr A pointer to the property to set. + * @param value The value to set. + * @return The receiver, to allow chaining. + * @throws CacheException if ptr is not a valid path within the object graph managed by the receiver. + * @see #delete(JsonPointer) + */ + JsonCache set(JsonPointer ptr, double value) throws CacheException; + + /** + * Sets a float property within the object graph managed by the receiver. + * + * @param ptr A pointer to the property to set. + * @param value The value to set. + * @return The receiver, to allow chaining. + * @throws CacheException if ptr is not a valid path within the object graph managed by the receiver. + * @see #delete(JsonPointer) + */ + JsonCache set(JsonPointer ptr, float value) throws CacheException; + + /** + * Sets an int property within the object graph managed by the receiver. + * + * @param ptr A pointer to the property to set. + * @param value The value to set. + * @return The receiver, to allow chaining. + * @throws CacheException if ptr is not a valid path within the object graph managed by the receiver. + * @see #delete(JsonPointer) + */ + JsonCache set(JsonPointer ptr, int value) throws CacheException; + + /** + * Sets a List property within the object graph managed by the receiver. + * + * @param ptr A pointer to the property to set. + * @param values The values to set. + * @return The receiver, to allow chaining. + * @throws CacheException if ptr is not a valid path within the object graph managed by the receiver. + * @see #delete(JsonPointer) + */ + JsonCache set(JsonPointer ptr, List values) throws CacheException; + + /** + * Sets a long property within the object graph managed by the receiver. + * + * @param ptr A pointer to the property to set. + * @param value The value to set. + * @return The receiver, to allow chaining. + * @throws CacheException if ptr is not a valid path within the object graph managed by the receiver. + * @see #delete(JsonPointer) + */ + JsonCache set(JsonPointer ptr, long value) throws CacheException; + + /** + * Sets an Object property within the object graph managed by the receiver. + * + * @param ptr A pointer to the property to set. + * @param value The value to set (can be null). + * @return The receiver, to allow chaining. + * @throws CacheException if ptr is not a valid path within the object graph managed by the receiver. + * @see #delete(JsonPointer) + */ + JsonCache set(JsonPointer ptr, Object value) throws CacheException; + + /** + * Sets a short property within the object graph managed by the receiver. + * + * @param ptr A pointer to the property to set. + * @param value The value to set. + * @return The receiver, to allow chaining. + * @throws CacheException if ptr is not a valid path within the object graph managed by the receiver. + * @see #delete(JsonPointer) + */ + JsonCache set(JsonPointer ptr, short value) throws CacheException; + + /** + * Sets a String property within the object graph managed by the receiver. + * + * @param ptr A pointer to the property to set. + * @param value The value to set (can be null). + * @return The receiver, to allow chaining. + * @throws CacheException if ptr is not a valid path within the object graph managed by the receiver. + * @see #delete(JsonPointer) + */ + JsonCache set(JsonPointer ptr, String value) throws CacheException; + + /** + * Sets a BigDecimal property within the object graph managed by the receiver. + * + * @param path A JSON Pointer expression for the property to set. + * @param value The value to set (can be null). + * @return The receiver, to allow chaining. + * @throws IllegalArgumentException if path is not a valid JSON Pointer expression. + * @throws CacheException if path is not a valid path within the object graph managed by the + * receiver. + * @see #delete(String) + */ + JsonCache set(String path, BigDecimal value) throws CacheException; + + /** + * Sets a BigInteger property within the object graph managed by the receiver. + * + * @param path A JSON Pointer expression for the property to set. + * @param value The value to set (can be null). + * @return The receiver, to allow chaining. + * @throws IllegalArgumentException if path is not a valid JSON Pointer expression. + * @throws CacheException if path is not a valid path within the object graph managed by the + * receiver. + * @see #delete(String) + */ + JsonCache set(String path, BigInteger value) throws CacheException; + + /** + * Sets a boolean property within the object graph managed by the receiver. + * + * @param path A JSON Pointer expression for the property to set. + * @param value The value to set. + * @return The receiver, to allow chaining. + * @throws IllegalArgumentException if path is not a valid JSON Pointer expression. + * @throws CacheException if path is not a valid path within the object graph managed by the + * receiver. + * @see #delete(String) + */ + JsonCache set(String path, boolean value) throws CacheException; + + /** + * Sets a double property within the object graph managed by the receiver. + * + * @param path A JSON Pointer expression for the property to set. + * @param value The value to set. + * @return The receiver, to allow chaining. + * @throws IllegalArgumentException if path is not a valid JSON Pointer expression. + * @throws CacheException if path is not a valid path within the object graph managed by the + * receiver. + * @see #delete(String) + */ + JsonCache set(String path, double value) throws CacheException; + + /** + * Sets a float property within the object graph managed by the receiver. + * + * @param path A JSON Pointer expression for the property to set. + * @param value The value to set. + * @return The receiver, to allow chaining. + * @throws IllegalArgumentException if path is not a valid JSON Pointer expression. + * @throws CacheException if path is not a valid path within the object graph managed by the + * receiver. + * @see #delete(String) + */ + JsonCache set(String path, float value) throws CacheException; + + /** + * Sets an int property within the object graph managed by the receiver. + * + * @param path A JSON Pointer expression for the property to set. + * @param value The value to set. + * @return The receiver, to allow chaining. + * @throws IllegalArgumentException if path is not a valid JSON Pointer expression. + * @throws CacheException if path is not a valid path within the object graph managed by the + * receiver. + * @see #delete(String) + */ + JsonCache set(String path, int value) throws CacheException; + + /** + * Sets a List property within the object graph managed by the receiver. + * + * @param path A JSON Pointer expression for the property to set. + * @param values The values to set. + * @return The receiver, to allow chaining. + * @throws IllegalArgumentException if path is not a valid JSON Pointer expression. + * @throws CacheException if path is not a valid path within the object graph managed by the + * receiver. + * @see #delete(String) + */ + JsonCache set(String path, List values) throws CacheException; + + /** + * Sets a long property within the object graph managed by the receiver. + * + * @param path A JSON Pointer expression for the property to set. + * @param value The value to set. + * @return The receiver, to allow chaining. + * @throws IllegalArgumentException if path is not a valid JSON Pointer expression. + * @throws CacheException if path is not a valid path within the object graph managed by the + * receiver. + * @see #delete(String) + */ + JsonCache set(String path, long value) throws CacheException; + + /** + * Sets an Object property within the object graph managed by the receiver. + * + * @param path A JSON Pointer expression for the property to set. + * @param value The value to set (can be null). + * @return The receiver, to allow chaining. + * @throws IllegalArgumentException if path is not a valid JSON Pointer expression. + * @throws CacheException if path is not a valid path within the object graph managed by the + * receiver. + * @see #delete(String) + */ + JsonCache set(String path, Object value) throws CacheException; + + /** + * Sets a short property within the object graph managed by the receiver. + * + * @param path A JSON Pointer expression for the property to set. + * @param value The value to set. + * @return The receiver, to allow chaining. + * @throws IllegalArgumentException if path is not a valid JSON Pointer expression. + * @throws CacheException if path is not a valid path within the object graph managed by the + * receiver. + * @see #delete(String) + */ + JsonCache set(String path, short value) throws CacheException; + + /** + * Sets a String property within the object graph managed by the receiver. + * + * @param path A JSON Pointer expression for the property to set. + * @param value The value to set (can be null). + * @return The receiver, to allow chaining. + * @throws IllegalArgumentException if path is not a valid JSON Pointer expression. + * @throws CacheException if path is not a valid path within the object graph managed by the + * receiver. + * @see #delete(String) + */ + JsonCache set(String path, String value) throws CacheException; + + /** + * Returns the size of a node within the object graph managed by the receiver. For an array node, size is the number + * of elements; for an object node, size is the number of properties; for other node types, size is 0. + * + * @param ptr A pointer to the node. + * @return The size of the node, or 0 if it does not exist. + * @see #delete(String) + */ + int size(JsonPointer ptr); + + /** + * Returns the size of a node within the object graph managed by the receiver. For an array node, size is the number + * of elements; for an object node, size is the number of properties; for other node types, size is 0. + * + * @param path A JSON pointer expression for the node. + * @return The size of the node, or 0 if it does not exist. + * @throws IllegalArgumentException if path is not a valid JSON Pointer expression. + * @see #delete(String) + */ + int size(String path); +} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/utils/JsonCacheImpl.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/utils/JsonCacheImpl.java new file mode 100644 index 00000000000..52bdde3bfb2 --- /dev/null +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/utils/JsonCacheImpl.java @@ -0,0 +1,1950 @@ +/* + * Copyright 2019 OpenAPI-Generator Contributors (https://openapi-generator.tech) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openapitools.codegen.utils; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Deque; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Objects; +import java.util.regex.Pattern; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.fasterxml.jackson.core.JsonPointer; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ContainerNode; +import com.fasterxml.jackson.databind.node.JsonNodeFactory; +import com.fasterxml.jackson.databind.node.JsonNodeType; +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.fasterxml.jackson.databind.node.POJONode; + +/** + * A cache implementation for loading, querying, mutating and saving a JSON object graph. + * + * @author Adrian Price, TIBCO Software Inc. + * @since 4.0.0 + */ +class JsonCacheImpl implements JsonCache.Root { + /** + * Manages a sub-tree of a parent cache, identified by a base pointer rooted. + */ + private static class ChildCacheImpl implements JsonCache { + private final JsonPointer basePtr; + private final JsonCache parent; + + private ChildCacheImpl(JsonCache parent, JsonPointer basePtr) { + this.parent = parent; + this.basePtr = basePtr; + } + + @Override + public JsonCache add(JsonPointer ptr, BigDecimal value) throws CacheException { + parent.add(basePtr.append(ptr), value); + return this; + } + + @Override + public JsonCache add(JsonPointer ptr, BigInteger value) throws CacheException { + parent.add(basePtr.append(ptr), value); + return this; + } + + @Override + public JsonCache add(JsonPointer ptr, boolean value) throws CacheException { + parent.add(basePtr.append(ptr), value); + return this; + } + + @Override + public JsonCache add(JsonPointer ptr, double value) throws CacheException { + parent.add(basePtr.append(ptr), value); + return this; + } + + @Override + public JsonCache add(JsonPointer ptr, float value) throws CacheException { + parent.add(basePtr.append(ptr), value); + return this; + } + + @Override + public JsonCache add(JsonPointer ptr, int value) throws CacheException { + parent.add(basePtr.append(ptr), value); + return this; + } + + @Override + public JsonCache add(JsonPointer ptr, long value) throws CacheException { + parent.add(basePtr.append(ptr), value); + return this; + } + + @Override + public JsonCache add(JsonPointer ptr, Object value) throws CacheException { + parent.add(basePtr.append(ptr), value); + return this; + } + + @Override + public JsonCache add(JsonPointer ptr, short value) throws CacheException { + parent.add(basePtr.append(ptr), value); + return this; + } + + @Override + public JsonCache add(String path, BigDecimal value) throws CacheException { + parent.add(basePtr.append(JsonPointer.compile(path)), value); + return this; + } + + @Override + public JsonCache add(String path, BigInteger value) throws CacheException { + parent.add(basePtr.append(JsonPointer.compile(path)), value); + return this; + } + + @Override + public JsonCache add(String path, boolean value) throws CacheException { + parent.add(basePtr.append(JsonPointer.compile(path)), value); + return this; + } + + @Override + public JsonCache add(String path, double value) throws CacheException { + parent.add(basePtr.append(JsonPointer.compile(path)), value); + return this; + } + + @Override + public JsonCache add(String path, float value) throws CacheException { + parent.add(basePtr.append(JsonPointer.compile(path)), value); + return this; + } + + @Override + public JsonCache add(String path, int value) throws CacheException { + parent.add(basePtr.append(JsonPointer.compile(path)), value); + return this; + } + + @Override + public JsonCache add(String path, long value) throws CacheException { + parent.add(basePtr.append(JsonPointer.compile(path)), value); + return this; + } + + @Override + public JsonCache add(String path, Object value) throws CacheException { + parent.add(basePtr.append(JsonPointer.compile(path)), value); + return this; + } + + @Override + public JsonCache add(String path, short value) throws CacheException { + parent.add(basePtr.append(JsonPointer.compile(path)), value); + return this; + } + + @Override + public JsonCache child(JsonPointer basePtr) { + return new ChildCacheImpl(this, basePtr); + } + + @Override + public JsonCache child(String path) { + return child(JsonPointer.compile(path)); + } + + @Override + public void delete(JsonPointer ptr) throws CacheException { + parent.delete(basePtr.append(ptr)); + } + + @Override + public void delete(String path) throws CacheException { + parent.delete(basePtr.append(JsonPointer.compile(path))); + } + + @Override + public boolean exists(JsonPointer ptr) { + return parent.exists(basePtr.append(ptr)); + } + + @Override + public boolean exists(String path) { + return parent.exists(basePtr.append(JsonPointer.compile(path))); + } + + @Override + public Object get(JsonPointer ptr) throws CacheException { + return parent.get(basePtr.append(ptr)); + } + + @Override + public Object get(JsonPointer ptr, Object defaultValue) throws CacheException { + return parent.get(basePtr.append(ptr), defaultValue); + } + + @Override + public Object get(String path) throws CacheException { + return parent.get(basePtr.append(JsonPointer.compile(path))); + } + + @Override + public Object get(String path, Object defaultValue) throws CacheException { + return parent.get(basePtr.append(JsonPointer.compile(path)), defaultValue); + } + + @Override + public BigDecimal getBigDecimal(JsonPointer ptr) throws CacheException { + return parent.getBigDecimal(basePtr.append(ptr)); + } + + @Override + public BigDecimal getBigDecimal(JsonPointer ptr, BigDecimal defaultValue) throws CacheException { + return parent.getBigDecimal(basePtr.append(ptr), defaultValue); + } + + @Override + public BigDecimal getBigDecimal(String path) throws CacheException { + return parent.getBigDecimal(basePtr.append(JsonPointer.compile(path))); + } + + @Override + public BigDecimal getBigDecimal(String path, BigDecimal defaultValue) throws CacheException { + return parent.getBigDecimal(basePtr.append(JsonPointer.compile(path)), defaultValue); + } + + @Override + public BigInteger getBigInteger(JsonPointer ptr) throws CacheException { + return parent.getBigInteger(basePtr.append(ptr)); + } + + @Override + public BigInteger getBigInteger(JsonPointer ptr, BigInteger defaultValue) throws CacheException { + return parent.getBigInteger(basePtr.append(ptr), defaultValue); + } + + @Override + public BigInteger getBigInteger(String path) throws CacheException { + return parent.getBigInteger(basePtr.append(JsonPointer.compile(path))); + } + + @Override + public BigInteger getBigInteger(String path, BigInteger defaultValue) throws CacheException { + return parent.getBigInteger(basePtr.append(JsonPointer.compile(path)), defaultValue); + } + + @Override + public byte[] getBinary(JsonPointer ptr) throws CacheException { + return parent.getBinary(basePtr.append(ptr)); + } + + @Override + public byte[] getBinary(JsonPointer ptr, byte[] defaultValue) throws CacheException { + return parent.getBinary(basePtr.append(ptr), defaultValue); + } + + @Override + public byte[] getBinary(String path) throws CacheException { + return parent.getBinary(basePtr.append(JsonPointer.compile(path))); + } + + @Override + public byte[] getBinary(String path, byte[] defaultValue) throws CacheException { + return parent.getBinary(basePtr.append(JsonPointer.compile(path)), defaultValue); + } + + @Override + public boolean getBoolean(JsonPointer ptr) throws CacheException { + return parent.getBoolean(basePtr.append(ptr)); + } + + @Override + public boolean getBoolean(JsonPointer ptr, boolean defaultValue) throws CacheException { + return parent.getBoolean(basePtr.append(ptr), defaultValue); + } + + @Override + public boolean getBoolean(String path) throws CacheException { + return parent.getBoolean(basePtr.append(JsonPointer.compile(path))); + } + + @Override + public boolean getBoolean(String path, boolean defaultValue) throws CacheException { + return parent.getBoolean(basePtr.append(JsonPointer.compile(path)), defaultValue); + } + + @Override + public double getDouble(JsonPointer ptr) throws CacheException { + return parent.getDouble(basePtr.append(ptr)); + } + + @Override + public double getDouble(JsonPointer ptr, double defaultValue) throws CacheException { + return parent.getDouble(basePtr.append(ptr), defaultValue); + } + + @Override + public double getDouble(String path) throws CacheException { + return parent.getDouble(basePtr.append(JsonPointer.compile(path))); + } + + @Override + public double getDouble(String path, double defaultValue) throws CacheException { + return parent.getDouble(basePtr.append(JsonPointer.compile(path)), defaultValue); + } + + @Override + public float getFloat(JsonPointer ptr) throws CacheException { + return parent.getFloat(basePtr.append(ptr)); + } + + @Override + public float getFloat(JsonPointer ptr, float defaultValue) throws CacheException { + return parent.getFloat(basePtr.append(ptr), defaultValue); + } + + @Override + public float getFloat(String path) throws CacheException { + return parent.getFloat(basePtr.append(JsonPointer.compile(path))); + } + + @Override + public float getFloat(String path, float defaultValue) throws CacheException { + return parent.getFloat(basePtr.append(JsonPointer.compile(path)), defaultValue); + } + + @Override + public int getInt(JsonPointer ptr) throws CacheException { + return parent.getInt(basePtr.append(ptr)); + } + + @Override + public int getInt(JsonPointer ptr, int defaultValue) throws CacheException { + return parent.getInt(basePtr.append(ptr), defaultValue); + } + + @Override + public int getInt(String path) throws CacheException { + return parent.getInt(basePtr.append(JsonPointer.compile(path))); + } + + @Override + public int getInt(String path, int defaultValue) throws CacheException { + return parent.getInt(basePtr.append(JsonPointer.compile(path)), defaultValue); + } + + @Override + public long getLong(JsonPointer ptr) throws CacheException { + return parent.getLong(basePtr.append(ptr)); + } + + @Override + public long getLong(JsonPointer ptr, long defaultValue) throws CacheException { + return parent.getLong(basePtr.append(ptr), defaultValue); + } + + @Override + public long getLong(String path) throws CacheException { + return parent.getLong(basePtr.append(JsonPointer.compile(path))); + } + + @Override + public long getLong(String path, long defaultValue) throws CacheException { + return parent.getLong(basePtr.append(JsonPointer.compile(path)), defaultValue); + } + + @Override + public JsonNodeType getNodeType(JsonPointer ptr) { + return parent.getNodeType(basePtr.append(ptr)); + } + + @Override + public JsonNodeType getNodeType(String path) { + return parent.getNodeType(basePtr.append(JsonPointer.compile(path))); + } + + @Override + public Number getNumber(JsonPointer ptr) throws CacheException { + return parent.getNumber(basePtr.append(ptr)); + } + + @Override + public Number getNumber(JsonPointer ptr, Number defaultValue) throws CacheException { + return parent.getNumber(basePtr.append(ptr), defaultValue); + } + + @Override + public Number getNumber(String path) throws CacheException { + return parent.getNumber(basePtr.append(JsonPointer.compile(path))); + } + + @Override + public Number getNumber(String path, Number defaultValue) throws CacheException { + return parent.getNumber(basePtr.append(JsonPointer.compile(path)), defaultValue); + } + + @Override + public T getObject(JsonPointer ptr, Class type) throws CacheException { + return parent.getObject(basePtr.append(ptr), type); + } + + @Override + public T getObject(JsonPointer ptr, T defaultValue) throws CacheException { + return parent.getObject(basePtr.append(ptr), defaultValue); + } + + @Override + public T getObject(String path, Class type) throws CacheException { + return parent.getObject(basePtr.append(JsonPointer.compile(path)), type); + } + + @Override + public T getObject(String path, T defaultValue) throws CacheException { + return parent.getObject(basePtr.append(JsonPointer.compile(path)), defaultValue); + } + + @Override + public List getObjects(JsonPointer ptr, Class type) throws CacheException { + return parent.getObjects(basePtr.append(ptr), type); + } + + @Override + public List getObjects(JsonPointer ptr, Class type, List defaultValue) throws CacheException { + return parent.getObjects(basePtr.append(ptr), type, defaultValue); + } + + @Override + public List getObjects(String path, Class type) throws CacheException { + return parent.getObjects(basePtr.append(JsonPointer.compile(path)), type); + } + + @Override + public List getObjects(String path, Class type, List defaultValue) throws CacheException { + return parent.getObjects(basePtr.append(JsonPointer.compile(path)), type, defaultValue); + } + + @Override + public short getShort(JsonPointer ptr) throws CacheException { + return parent.getShort(basePtr.append(ptr)); + } + + @Override + public short getShort(JsonPointer ptr, short defaultValue) throws CacheException { + return parent.getShort(basePtr.append(ptr), defaultValue); + } + + @Override + public short getShort(String path) throws CacheException { + return parent.getShort(basePtr.append(JsonPointer.compile(path))); + } + + @Override + public short getShort(String path, short defaultValue) throws CacheException { + return parent.getShort(basePtr.append(JsonPointer.compile(path)), defaultValue); + } + + @Override + public String getString(JsonPointer ptr) throws CacheException { + return parent.getString(basePtr.append(ptr)); + } + + @Override + public String getString(JsonPointer ptr, String defaultValue) throws CacheException { + return parent.getString(basePtr.append(ptr), defaultValue); + } + + @Override + public String getString(String path) throws CacheException { + return parent.getString(basePtr.append(JsonPointer.compile(path))); + } + + @Override + public String getString(String path, String defaultValue) throws CacheException { + return parent.getString(basePtr.append(JsonPointer.compile(path)), defaultValue); + } + + @Override + public JsonCache parent() { + return parent; + } + + @Override + public Root root() { + return parent.root(); + } + + @Override + public JsonCache set(JsonPointer ptr, BigDecimal value) throws CacheException { + parent.set(basePtr.append(ptr), value); + return this; + } + + @Override + public JsonCache set(JsonPointer ptr, BigInteger value) throws CacheException { + parent.set(basePtr.append(ptr), value); + return this; + } + + @Override + public JsonCache set(JsonPointer ptr, boolean value) throws CacheException { + parent.set(basePtr.append(ptr), value); + return this; + } + + @Override + public JsonCache set(JsonPointer ptr, double value) throws CacheException { + parent.set(basePtr.append(ptr), value); + return this; + } + + @Override + public JsonCache set(JsonPointer ptr, float value) throws CacheException { + parent.set(basePtr.append(ptr), value); + return this; + } + + @Override + public JsonCache set(JsonPointer ptr, int value) throws CacheException { + parent.set(basePtr.append(ptr), value); + return this; + } + + @Override + public JsonCache set(JsonPointer ptr, List values) throws CacheException { + parent.set(basePtr.append(ptr), values); + return this; + } + + @Override + public JsonCache set(JsonPointer ptr, long value) throws CacheException { + parent.set(basePtr.append(ptr), value); + return this; + } + + @Override + public JsonCache set(JsonPointer ptr, Object value) throws CacheException { + parent.set(basePtr.append(ptr), value); + return this; + } + + @Override + public JsonCache set(JsonPointer ptr, short value) throws CacheException { + parent.set(basePtr.append(ptr), value); + return this; + } + + @Override + public JsonCache set(JsonPointer ptr, String value) throws CacheException { + parent.set(basePtr.append(ptr), value); + return this; + } + + @Override + public JsonCache set(String path, BigDecimal value) throws CacheException { + parent.set(basePtr.append(JsonPointer.compile(path)), value); + return this; + } + + @Override + public JsonCache set(String path, BigInteger value) throws CacheException { + parent.set(basePtr.append(JsonPointer.compile(path)), value); + return this; + } + + @Override + public JsonCache set(String path, boolean value) throws CacheException { + parent.set(basePtr.append(JsonPointer.compile(path)), value); + return this; + } + + @Override + public JsonCache set(String path, double value) throws CacheException { + parent.set(basePtr.append(JsonPointer.compile(path)), value); + return this; + } + + @Override + public JsonCache set(String path, float value) throws CacheException { + parent.set(basePtr.append(JsonPointer.compile(path)), value); + return this; + } + + @Override + public JsonCache set(String path, int value) throws CacheException { + parent.set(basePtr.append(JsonPointer.compile(path)), value); + return this; + } + + @Override + public JsonCache set(String path, List values) throws CacheException { + parent.set(basePtr.append(JsonPointer.compile(path)), values); + return this; + } + + @Override + public JsonCache set(String path, long value) throws CacheException { + parent.set(basePtr.append(JsonPointer.compile(path)), value); + return this; + } + + @Override + public JsonCache set(String path, Object value) throws CacheException { + parent.set(basePtr.append(JsonPointer.compile(path)), value); + return this; + } + + @Override + public JsonCache set(String path, short value) throws CacheException { + parent.set(basePtr.append(JsonPointer.compile(path)), value); + return this; + } + + @Override + public JsonCache set(String path, String value) throws CacheException { + parent.set(basePtr.append(JsonPointer.compile(path)), value); + return this; + } + + @Override + public int size(JsonPointer ptr) { + return parent.size(basePtr.append(ptr)); + } + + @Override + public int size(String path) { + return parent.size(basePtr.append(JsonPointer.compile(path))); + } + + @Override + public String toString() { + JsonNode node; + try { + node = getObject(EMPTY_PTR, JsonNode.class); + } catch (CacheException e) { + LOGGER.error("", e); + node = null; + } + return "ChildCacheImpl [basePtr=" + basePtr + ", node=" + node + ']'; + } + } + + static class FactoryImpl implements JsonCache.Factory { + static final JsonCache.Factory instance = new FactoryImpl(); + private final Map instances = new HashMap<>(); + + @Override + public Root create() { + return new JsonCacheImpl(); + } + + @Override + public Root get(String key) { + synchronized (instances) { + JsonCacheImpl instance = instances.get(key); + if (instance == null) { + instance = new JsonCacheImpl(); + instances.put(key, instance); + } + return instance; + } + } + } + + protected static final JsonPointer EMPTY_PTR = JsonPointer.compile("/"); + + private static final Pattern INTEGER = Pattern.compile("^\\d+$"); + + protected static final Logger LOGGER = LoggerFactory.getLogger(JsonCacheImpl.class); + + protected boolean isDirty; + + protected boolean isLoaded; + + protected ObjectMapper mapper; + + protected MergePolicy mergePolicy = MergePolicy.MERGE_RECURSIVE; + + protected ContainerNode root; + + private boolean shutdownHookRegistered; + + protected JsonCacheImpl() { + mapper = new ObjectMapper(); + mapper.enable(SerializationFeature.INDENT_OUTPUT); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + } + + @Override + public JsonCache add(JsonPointer ptr, BigDecimal value) { + return add(ptr, nodeFor(value)); + } + + @Override + public JsonCache add(JsonPointer ptr, BigInteger value) { + return add(ptr, nodeFor(value)); + } + + @Override + public JsonCache add(JsonPointer ptr, boolean value) { + return add(ptr, nodeFor(value)); + } + + @Override + public JsonCache add(JsonPointer ptr, double value) { + return add(ptr, nodeFor(value)); + } + + @Override + public JsonCache add(JsonPointer ptr, float value) { + return add(ptr, nodeFor(value)); + } + + @Override + public JsonCache add(JsonPointer ptr, int value) { + return add(ptr, nodeFor(value)); + } + + protected JsonCache add(JsonPointer ptr, JsonNode node) { + // If ptr ends with an array index, this implies inserting at the specified index. + // If ptr does not end with an array index, this implies appending to the end of the array. + // In both cases the array in question and its ancestors must be created if they do not already exist. + String lastProperty = ptr.last().getMatchingProperty(); + boolean isIndexed = isInteger(lastProperty); + ContainerNode container = ensureContainerExists(ptr, !isIndexed); + switch (container.getNodeType()) { + case ARRAY: + ArrayNode array = (ArrayNode) container; + int index = isIndexed ? Integer.parseInt(lastProperty) : array.size(); + if (index < array.size()) { + array.insert(index, node); + } else { + // Fill any gap between current size and index with nulls (Jackson doesn't support sparse arrays). + for (int i = array.size(); i < index; i++) + array.add(array.nullNode()); + array.add(node); + } + break; + default: + throw new IllegalArgumentException(ptr + " does not identify an array"); + } + setDirty(); + return this; + } + + @Override + public JsonCache add(JsonPointer ptr, long value) { + return add(ptr, nodeFor(value)); + } + + @Override + public JsonCache add(JsonPointer ptr, Object value) { + return add(ptr, nodeFor(value)); + } + + @Override + public JsonCache add(JsonPointer ptr, short value) { + return add(ptr, nodeFor(value)); + } + + @Override + public JsonCache add(String path, BigDecimal value) { + return add(JsonPointer.compile(path), value); + } + + @Override + public JsonCache add(String path, BigInteger value) { + return add(JsonPointer.compile(path), value); + } + + @Override + public JsonCache add(String path, boolean value) { + return add(JsonPointer.compile(path), value); + } + + @Override + public JsonCache add(String path, double value) { + return add(JsonPointer.compile(path), value); + } + + @Override + public JsonCache add(String path, float value) { + return add(JsonPointer.compile(path), value); + } + + @Override + public JsonCache add(String path, int value) { + return add(JsonPointer.compile(path), value); + } + + @Override + public JsonCache add(String path, long value) { + return add(JsonPointer.compile(path), value); + } + + @Override + public JsonCache add(String path, Object value) { + return add(JsonPointer.compile(path), value); + } + + @Override + public JsonCache add(String path, short value) { + return add(JsonPointer.compile(path), value); + } + + @Override + public JsonCache child(JsonPointer basePtr) { + return new ChildCacheImpl(this, basePtr); + } + + @Override + public JsonCache child(String path) { + return child(JsonPointer.compile(path)); + } + + @Override + public void delete(JsonPointer ptr) { + JsonPointer head = ptr.head(); + if (head == null) { + root = null; + } else if (root != null) { + JsonNode parent = root.at(head); + if (parent.isArray()) { + ((ArrayNode) parent).remove(Integer.parseInt(ptr.last().getMatchingProperty())); + } else if (parent.isObject()) { + ((ObjectNode) parent).remove(ptr.last().getMatchingProperty()); + } else { + throw new IllegalArgumentException(ptr + " does not identify a deletable node"); + } + } + setDirty(); + } + + @Override + public void delete(String path) { + delete(JsonPointer.compile(path)); + } + + /** + * Ensures that a suitable container exists for the specified JSON pointer. + * + * @param ptr A {@link https://tools.ietf.org/html/rfc6901 JSON Pointer} to the property to set. + * @return The container that owns the property identified by path. + */ + protected ContainerNode ensureContainerExists(JsonPointer ptr) { + return ensureContainerExists(ptr, false); + } + + /** + * Ensures that all ancestor containers exist for the specified JSON pointer. + * + * @param ptr A {@link https://tools.ietf.org/html/rfc6901 JSON Pointer} to the property to set. + * @param forceArray true to create an array for the last segment of the pointer if it is non-integral. + * @return The container that owns the property identified by path. + */ + protected ContainerNode ensureContainerExists(JsonPointer ptr, boolean forceArray) { + if (root == null) { + root = isInteger(ptr.getMatchingProperty()) // split + ? JsonNodeFactory.instance.arrayNode() + : JsonNodeFactory.instance.objectNode(); + } + String lastProperty = ptr.last().getMatchingProperty(); + Deque stack = new ArrayDeque<>(); + JsonPointer ancestorPtr = forceArray && !isInteger(lastProperty) ? ptr : ptr.head(); + JsonNode ancestor = root.at(ancestorPtr); + while (ancestor.isMissingNode()) { + stack.push(ancestorPtr.last().getMatchingProperty()); + ancestorPtr = ancestorPtr.head(); + ancestor = root.at(ancestorPtr); + } + if (!ancestor.isContainerNode()) + throw new IllegalArgumentException(ancestorPtr + " does not identify a container node"); + + while (!stack.isEmpty()) { + String ancestorProperty = stack.pop(); + String childProperty = stack.isEmpty() // split + ? forceArray && !isInteger(lastProperty) // split + ? "0" // split + : lastProperty // split + : stack.peek(); + // Parent can be array or object; child can be array or object - that's four possible combinations. + // Infer the child container type from the child property name: an integer pattern implies an array node. + if (isInteger(childProperty)) { + switch (ancestor.getNodeType()) { + case ARRAY: + // ARRAY/ARRAY + ancestor = ((ArrayNode) ancestor).insertArray(Integer.parseInt(ancestorProperty)); + break; + case OBJECT: + // OBJECT/ARRAY + ancestor = ((ObjectNode) ancestor).putArray(ancestorProperty); + break; + default: + throw new IllegalArgumentException(ancestorProperty + " does not identify an array node"); + } + } else { + switch (ancestor.getNodeType()) { + case ARRAY: + // ARRAY/OBJECT + ancestor = ((ArrayNode) ancestor).insertObject(Integer.parseInt(ancestorProperty)); + break; + case OBJECT: + // OBJECT/OBJECT + ancestor = ((ObjectNode) ancestor).putObject(ancestorProperty); + break; + default: + throw new IllegalArgumentException(ancestorProperty + " does not identify an array node"); + } + } + setDirty(); + } + + return (ContainerNode) ancestor; + } + + @Override + public boolean exists(JsonPointer ptr) { + return root != null && !root.at(ptr).isMissingNode(); + } + + @Override + public boolean exists(String path) { + return exists(JsonPointer.compile(path)); + } + + @Override + public Root flush(File file) throws CacheException { + if (isDirty) + save(file); + return this; + } + + @Override + public Root flush(OutputStream out) throws CacheException { + if (isDirty) + save(out); + return this; + } + + @Override + public Root flushOnShutdown(final File file) { + if (!shutdownHookRegistered) { + Runtime.getRuntime().addShutdownHook(new Thread() { + @Override + public void run() { + try { + flush(file); + } catch (CacheException e) { + e.printStackTrace(); + } + } + }); + shutdownHookRegistered = true; + } + return this; + } + + @Override + public Root flushOnShutdown(final OutputStream out) { + if (!shutdownHookRegistered) { + Runtime.getRuntime().addShutdownHook(new Thread() { + @Override + public void run() { + try { + flush(out); + } catch (CacheException e) { + e.printStackTrace(); + } + } + }); + shutdownHookRegistered = true; + } + return this; + } + + @Override + public Object get(JsonPointer ptr) throws CacheException { + Object result; + if (root == null) { + result = null; + } else { + try { + JsonNode node = root.at(ptr); + switch (node.getNodeType()) { + case ARRAY: + case OBJECT: + result = node; + break; + case BINARY: + result = node.binaryValue(); + break; + case BOOLEAN: + result = node.booleanValue(); + break; + case NUMBER: + result = node.numberValue(); + break; + case POJO: + result = ((POJONode) node).getPojo(); + break; + case STRING: + result = node.textValue(); + break; + default: + result = null; + break; + } + } catch (IOException e) { + throw new CacheException(e); + } + } + return result; + } + + @Override + public Object get(JsonPointer ptr, Object defaultValue) throws CacheException { + Objects.requireNonNull(defaultValue, "defaultValue is required"); + Object result; + if (exists(ptr)) { + result = get(ptr); + } else { + set(ptr, defaultValue); + result = defaultValue; + } + return result; + } + + @Override + public Object get(String path) throws CacheException { + return get(JsonPointer.compile(path)); + } + + @Override + public Object get(String path, Object defaultValue) throws CacheException { + return get(JsonPointer.compile(path), defaultValue); + } + + @Override + public BigDecimal getBigDecimal(JsonPointer ptr) { + return root == null ? null : root.at(ptr).decimalValue(); + } + + @Override + public BigDecimal getBigDecimal(JsonPointer ptr, BigDecimal defaultValue) throws CacheException { + Objects.requireNonNull(defaultValue, "defaultValue is required"); + BigDecimal result; + if (exists(ptr)) { + result = getBigDecimal(ptr); + } else { + set(ptr, defaultValue); + result = defaultValue; + } + return result; + } + + @Override + public BigDecimal getBigDecimal(String path) { + return getBigDecimal(JsonPointer.compile(path)); + } + + @Override + public BigDecimal getBigDecimal(String path, BigDecimal defaultValue) throws CacheException { + + return getBigDecimal(JsonPointer.compile(path), defaultValue); + } + + @Override + public BigInteger getBigInteger(JsonPointer ptr) { + return root == null ? null : root.at(ptr).bigIntegerValue(); + } + + @Override + public BigInteger getBigInteger(JsonPointer ptr, BigInteger defaultValue) throws CacheException { + Objects.requireNonNull(defaultValue, "defaultValue is required"); + BigInteger result; + if (exists(ptr)) { + result = getBigInteger(ptr); + } else { + set(ptr, defaultValue); + result = defaultValue; + } + return result; + } + + @Override + public BigInteger getBigInteger(String path) { + return getBigInteger(JsonPointer.compile(path)); + } + + @Override + public BigInteger getBigInteger(String path, BigInteger defaultValue) throws CacheException { + return getBigInteger(JsonPointer.compile(path), defaultValue); + } + + @Override + public byte[] getBinary(JsonPointer ptr) throws CacheException { + try { + return root == null ? null : root.at(ptr).binaryValue(); + } catch (IOException e) { + throw new CacheException(e); + } + } + + @Override + public byte[] getBinary(JsonPointer ptr, byte[] defaultValue) throws CacheException { + Objects.requireNonNull(defaultValue, "defaultValue is required"); + byte[] result; + if (exists(ptr)) { + result = getBinary(ptr); + } else { + set(ptr, defaultValue); + result = defaultValue; + } + return result; + } + + @Override + public byte[] getBinary(String path) throws CacheException { + return getBinary(JsonPointer.compile(path)); + } + + @Override + public byte[] getBinary(String path, byte[] defaultValue) throws CacheException { + return getBinary(JsonPointer.compile(path), defaultValue); + } + + @Override + public boolean getBoolean(JsonPointer ptr) { + return root != null && root.at(ptr).booleanValue(); + } + + @Override + public boolean getBoolean(JsonPointer ptr, boolean defaultValue) throws CacheException { + boolean result; + if (exists(ptr)) { + result = getBoolean(ptr); + } else { + set(ptr, defaultValue); + result = defaultValue; + } + return result; + } + + @Override + public boolean getBoolean(String path) { + return getBoolean(JsonPointer.compile(path)); + } + + @Override + public boolean getBoolean(String path, boolean defaultValue) throws CacheException { + return getBoolean(JsonPointer.compile(path), defaultValue); + } + + @Override + public double getDouble(JsonPointer ptr) { + return root == null ? 0.0D : root.at(ptr).doubleValue(); + } + + @Override + public double getDouble(JsonPointer ptr, double defaultValue) throws CacheException { + Objects.requireNonNull(defaultValue, "defaultValue is required"); + double result; + if (exists(ptr)) { + result = getDouble(ptr); + } else { + set(ptr, defaultValue); + result = defaultValue; + } + return result; + } + + @Override + public double getDouble(String path) { + return getDouble(JsonPointer.compile(path)); + } + + @Override + public double getDouble(String path, double defaultValue) throws CacheException { + return getDouble(JsonPointer.compile(path), defaultValue); + } + + @Override + public float getFloat(JsonPointer ptr) { + return root == null ? 0.0F : root.at(ptr).floatValue(); + } + + @Override + public float getFloat(JsonPointer ptr, float defaultValue) throws CacheException { + float result; + if (exists(ptr)) { + result = getFloat(ptr); + } else { + set(ptr, defaultValue); + result = defaultValue; + } + return result; + } + + @Override + public float getFloat(String path) { + return getFloat(JsonPointer.compile(path)); + } + + @Override + public float getFloat(String path, float defaultValue) throws CacheException { + return getFloat(JsonPointer.compile(path), defaultValue); + } + + @Override + public int getInt(JsonPointer ptr) { + return root == null ? 0 : root.at(ptr).intValue(); + } + + @Override + public int getInt(JsonPointer ptr, int defaultValue) throws CacheException { + int result; + if (exists(ptr)) { + result = getInt(ptr); + } else { + set(ptr, defaultValue); + result = defaultValue; + } + return result; + } + + @Override + public int getInt(String path) { + return getInt(JsonPointer.compile(path)); + } + + @Override + public int getInt(String path, int defaultValue) throws CacheException { + return getInt(JsonPointer.compile(path), defaultValue); + } + + @Override + public long getLong(JsonPointer ptr) { + return root == null ? 0L : root.at(ptr).longValue(); + } + + @Override + public long getLong(JsonPointer ptr, long defaultValue) throws CacheException { + long result; + if (exists(ptr)) { + result = getLong(ptr); + } else { + set(ptr, defaultValue); + result = defaultValue; + } + return result; + } + + @Override + public long getLong(String path) { + return getLong(JsonPointer.compile(path)); + } + + @Override + public long getLong(String path, long defaultValue) throws CacheException { + return getLong(JsonPointer.compile(path), defaultValue); + } + + @Override + public ObjectMapper getMapper() { + return mapper; + } + + @Override + public MergePolicy getMergePolicy() { + return mergePolicy; + } + + @Override + public JsonNodeType getNodeType(JsonPointer ptr) { + return root.at(ptr).getNodeType(); + } + + @Override + public JsonNodeType getNodeType(String path) { + return getNodeType(JsonPointer.compile(path)); + } + + @Override + public int hashCode() { + // TODO Auto-generated method stub + return super.hashCode(); + } + + @Override + public boolean equals(Object obj) { + // TODO Auto-generated method stub + return super.equals(obj); + } + + @Override + protected Object clone() throws CloneNotSupportedException { + // TODO Auto-generated method stub + return super.clone(); + } + + @Override + protected void finalize() throws Throwable { + // TODO Auto-generated method stub + super.finalize(); + } + + @Override + public Number getNumber(JsonPointer ptr) { + return root == null ? null : root.at(ptr).numberValue(); + } + + @Override + public Number getNumber(JsonPointer ptr, Number defaultValue) throws CacheException { + Objects.requireNonNull(defaultValue, "defaultValue is required"); + Number result; + if (exists(ptr)) { + result = getNumber(ptr); + } else { + set(ptr, defaultValue); + result = defaultValue; + } + return result; + } + + @Override + public Number getNumber(String path) { + return getNumber(JsonPointer.compile(path)); + } + + @Override + public Number getNumber(String path, Number defaultValue) throws CacheException { + return getNumber(JsonPointer.compile(path), defaultValue); + } + + @Override + public T getObject(JsonPointer ptr, Class type) throws CacheException { + T result; + if (root == null) { + result = null; + } else { + JsonNode node = root.at(ptr); + Object value = node.isPojo() && !JsonNode.class.isAssignableFrom(type) ? ((POJONode) node).getPojo() : node; + result = mapper.convertValue(value, type); + } + return result; + } + + @Override + @SuppressWarnings("unchecked") + public T getObject(JsonPointer ptr, T defaultValue) throws CacheException { + Objects.requireNonNull(defaultValue, "defaultValue is required"); + T result; + if (exists(ptr)) { + result = (T) getObject(ptr, defaultValue.getClass()); + } else { + set(ptr, defaultValue); + result = defaultValue; + } + return result; + } + + @Override + public T getObject(String path, Class type) throws CacheException { + return getObject(JsonPointer.compile(path), type); + } + + @Override + public T getObject(String path, T defaultValue) throws CacheException { + return getObject(JsonPointer.compile(path), defaultValue); + } + + @Override + public List getObjects(JsonPointer ptr, Class type) throws CacheException { + List result; + + if (root == null) { + result = null; + } else { + JsonNode node = root.at(ptr); + switch (node.getNodeType()) { + case ARRAY: + case OBJECT: + result = new ArrayList(node.size()); + Iterator elements = node.elements(); + while (elements.hasNext()) + result.add(mapper.convertValue(elements.next(), type)); + break; + default: + result = Collections.emptyList(); + break; + } + } + + return result; + } + + @Override + public List getObjects(JsonPointer ptr, Class type, List defaultValue) throws CacheException { + Objects.requireNonNull(defaultValue, "defaultValue is required"); + List result; + if (exists(ptr)) { + result = getObjects(ptr, type); + } else { + set(ptr, defaultValue); + result = defaultValue; + } + return result; + } + + @Override + public List getObjects(String path, Class type) throws CacheException { + return getObjects(JsonPointer.compile(path), type); + } + + @Override + public List getObjects(String path, Class type, List defaultValue) throws CacheException { + return getObjects(JsonPointer.compile(path), type, defaultValue); + } + + @Override + public short getShort(JsonPointer ptr) { + return root == null ? (short) 0 : root.at(ptr).shortValue(); + } + + @Override + public short getShort(JsonPointer ptr, short defaultValue) { + short result; + if (exists(ptr)) { + result = getShort(ptr); + } else { + set(ptr, defaultValue); + result = defaultValue; + } + return result; + } + + @Override + public short getShort(String path) { + return getShort(JsonPointer.compile(path)); + } + + @Override + public short getShort(String path, short defaultValue) { + return getShort(JsonPointer.compile(path), defaultValue); + } + + @Override + public String getString(JsonPointer ptr) { + return root == null ? null : root.at(ptr).textValue(); + } + + @Override + public String getString(JsonPointer ptr, String defaultValue) { + Objects.requireNonNull(defaultValue, "defaultValue is required"); + String result; + if (exists(ptr)) { + result = getString(ptr); + } else { + set(ptr, defaultValue); + result = defaultValue; + } + return result; + } + + @Override + public String getString(String path) { + return getString(JsonPointer.compile(path)); + } + + @Override + public String getString(String path, String defaultValue) { + return getString(JsonPointer.compile(path), defaultValue); + } + + protected void insertNumber(ArrayNode array, int index, Number value) { + if (value instanceof Short) { + array.insert(index, (Short) value); + } else if (value instanceof Integer) { + array.insert(index, (Integer) value); + } else if (value instanceof Long) { + array.insert(index, (Long) value); + } else if (value instanceof Float) { + array.insert(index, (Float) value); + } else if (value instanceof Double) { + array.insert(index, (Double) value); + } else if (value instanceof BigInteger) { + array.insert(index, (BigInteger) value); + } else if (value instanceof BigDecimal) { + array.insert(index, (BigDecimal) value); + } else { + throw new IllegalArgumentException( + "unsupported numeric value: " + value + " (" + value.getClass().getSimpleName() + ')'); + } + } + + @Override + public boolean isDirty() { + return isDirty; + } + + protected boolean isInteger(String s) { + return INTEGER.matcher(s).matches(); + } + + @Override + public Root load(File file) throws CacheException { + Objects.requireNonNull(file, "file is required"); + if (file.exists()) { + try (InputStream in = new FileInputStream(file)) { + load(in); + } catch (IOException e) { + throw new CacheException(e); + } + } + return this; + } + + @Override + public Root load(InputStream in) throws CacheException { + Objects.requireNonNull(in, "in is required"); + try (InputStream is = in) { + if (isLoaded) { + if (mergePolicy != MergePolicy.NO_MERGE) { + ContainerNode tree = (ContainerNode) mapper.readTree(in); + + // The cache is already loaded, so merge the incoming object tree into the existing root. + merge(root, tree); + } + } else { + root = (ContainerNode) mapper.readTree(in); + isDirty = false; + isLoaded = true; + } + } catch (IOException e) { + throw new CacheException(e); + } + return this; + } + + @Override + public Root mapper(ObjectMapper mapper) { + Objects.requireNonNull(mapper, "mapper is required"); + this.mapper = mapper; + return this; + } + + protected void merge(ContainerNode dest, ContainerNode src) { + if (dest.getNodeType() == src.getNodeType()) { + if (dest.isArray()) { + ArrayNode destArray = (ArrayNode) dest; + ArrayNode srcArray = (ArrayNode) src; + outer: + for (int i = 0; i < srcArray.size(); i++) { + // Only add a source element if it is not already present in the destination array. + JsonNode srcElem = srcArray.get(i); + for (int j = 0; j < destArray.size(); j++) { + if (destArray.get(j).equals(srcElem)) + continue outer; + } + destArray.add(srcElem); + } + } else if (dest.isObject()) { + ObjectNode destObject = (ObjectNode) dest; + ObjectNode srcObject = (ObjectNode) src; + Iterator> fields = srcObject.fields(); + while (fields.hasNext()) { + Entry field = fields.next(); + String fieldName = field.getKey(); + JsonNode srcChild = field.getValue(); + if (destObject.has(fieldName)) { + JsonNode destChild = destObject.get(fieldName); + switch (mergePolicy) { + case OVERWRITE_EXISTING: + destObject.set(fieldName, srcChild); + // Mark the cache as dirty as we've added items from another file. + isDirty = true; + LOGGER.info("Existing root property '" + fieldName + + "' has been overwritten by incoming data"); + break; + case MERGE_RECURSIVE: + if (destChild.isContainerNode() && srcChild.isContainerNode()) + merge((ContainerNode) destChild, (ContainerNode) srcChild); + break; + case KEEP_EXISTING: + LOGGER.info("Existing root property '" + fieldName + + "' will not be overwritten by incoming data"); + default: + // Nothing to do. + break; + } + } else { + destObject.set(fieldName, srcChild); + LOGGER.info("New property '" + fieldName + "' has been added from incoming data"); + // Mark the cache as dirty as we've added items from another file. + isDirty = true; + } + } + } + } else { + LOGGER.warn("Cannot merge containers of differing types"); + } + } + + @Override + public Root mergePolicy(MergePolicy policy) { + Objects.requireNonNull(policy, "policy is required"); + this.mergePolicy = policy; + return this; + } + + // @Override + @SuppressWarnings("unchecked") + protected JsonNode nodeFor(Object value) { + JsonNode node; + if (value == null) { + node = root.nullNode(); + } else if (value instanceof JsonNode) { + node = (JsonNode) value; + } else if (value instanceof Boolean) { + node = root.booleanNode((Boolean) value); + } else if (value instanceof List) { + node = root.arrayNode(); + for (Object element : (List) value) + ((ArrayNode) node).add(nodeFor(element)); + } else if (value instanceof Map) { + node = root.objectNode(); + for (Entry entry : ((Map) value).entrySet()) + ((ObjectNode) node).set(entry.getKey(), nodeFor(entry.getValue())); + } else if (value instanceof Number) { + if (value instanceof Byte) + node = root.numberNode((Byte) value); + else if (value instanceof Short) + node = root.numberNode((Short) value); + else if (value instanceof Integer) + node = root.numberNode((Integer) value); + else if (value instanceof Long) + node = root.numberNode((Long) value); + else if (value instanceof Float) + node = root.numberNode((Float) value); + else if (value instanceof Double) + node = root.numberNode((Double) value); + else if (value instanceof BigInteger) + node = root.numberNode((BigInteger) value); + else if (value instanceof BigDecimal) + node = root.numberNode((BigDecimal) value); + else + throw new IllegalArgumentException("unsupported number type: " + value.getClass().getSimpleName()); + } else if (value instanceof String) { + node = root.textNode((String) value); + } else if (value instanceof byte[]) { + node = root.binaryNode((byte[]) value); + } else { + node = root.pojoNode(value); + } + return node; + } + + protected JsonNodeType nodeTypeFor(Object value) { + JsonNodeType type; + if (value == null) { + type = JsonNodeType.NULL; + } else if (value instanceof Boolean) { + type = JsonNodeType.BOOLEAN; + } else if (value instanceof Number) { + type = JsonNodeType.NUMBER; + } else if (value instanceof String) { + type = JsonNodeType.STRING; + } else if (value instanceof ArrayNode || value instanceof List) { + type = JsonNodeType.ARRAY; + } else if (value instanceof byte[]) { + type = JsonNodeType.BINARY; + } else if (value instanceof ObjectNode || value instanceof Map) { + type = JsonNodeType.OBJECT; + } else { + type = JsonNodeType.POJO; + } + return type; + } + + @Override + public JsonCache parent() { + return null; + } + + protected void putNumber(ObjectNode object, String property, Number value) { + if (value instanceof Short) { + object.put(property, (Short) value); + } else if (value instanceof Integer) { + object.put(property, (Integer) value); + } else if (value instanceof Long) { + object.put(property, (Long) value); + } else if (value instanceof Float) { + object.put(property, (Float) value); + } else if (value instanceof Double) { + object.put(property, (Double) value); + } else if (value instanceof BigInteger) { + object.put(property, (BigInteger) value); + } else if (value instanceof BigDecimal) { + object.put(property, (BigDecimal) value); + } else { + throw new IllegalArgumentException( + "unsupported numeric value: " + value + " (" + value.getClass().getSimpleName() + ')'); + } + } + + @Override + public Root root() { + return this; + } + + @Override + public Root save(File file) throws CacheException { + Objects.requireNonNull(file, "file is required"); + file.getParentFile().mkdirs(); + try { + save(new FileOutputStream(file)); + } catch (FileNotFoundException e) { + throw new CacheException(e); + } + return this; + } + + @Override + public Root save(OutputStream out) throws CacheException { + if (root == null || root.isMissingNode()) + throw new CacheException("null or missing root node"); + Objects.requireNonNull(out, "out is required"); + try (OutputStream o = out) { + mapper.writeValue(o, root); + } catch (IOException e) { + throw new CacheException(e); + } + isDirty = false; + return this; + } + + @Override + public JsonCache set(JsonPointer ptr, BigDecimal value) { + return set(ptr, (Object) value); + } + + @Override + public JsonCache set(JsonPointer ptr, BigInteger value) { + return set(ptr, (Object) value); + } + + @Override + public JsonCache set(JsonPointer ptr, boolean value) { + return set(ptr, (Object) value); + } + + @Override + public JsonCache set(JsonPointer ptr, double value) { + return set(ptr, (Object) value); + } + + @Override + public JsonCache set(JsonPointer ptr, float value) { + return set(ptr, (Object) value); + } + + @Override + public JsonCache set(JsonPointer ptr, int value) { + return set(ptr, (Object) value); + } + + @Override + public JsonCache set(JsonPointer ptr, List values) throws CacheException { + // Note: if the node identified by ptr is not an array, we must create one before populating it. + ArrayNode array; + ContainerNode container = ensureContainerExists(ptr); + JsonNode target = container.at(ptr.last()); + if (target.isArray()) { + array = (ArrayNode) target; + } else { + String property = ptr.last().getMatchingProperty(); + array = container.arrayNode(); + switch (container.getNodeType()) { + case ARRAY: + int index = Integer.parseInt(property); + ((ArrayNode) container).set(index, array); + break; + case OBJECT: + ((ObjectNode) container).set(property, array); + break; + default: + throw new CacheException(ptr + " does not identify an array"); + } + } + + // Now that the target array exists, we can populate it. + array.removeAll(); + for (Object value : values) { + JsonNode node = nodeFor(value); + array.add(node); + } + setDirty(); + return this; + } + + @Override + public JsonCache set(JsonPointer ptr, long value) { + return set(ptr, (Object) value); + } + + @Override + public JsonCache set(JsonPointer ptr, Object value) { + String property = ptr.last().getMatchingProperty(); + ContainerNode container = ensureContainerExists(ptr); + JsonNode node = nodeFor(value); + switch (container.getNodeType()) { + case ARRAY: + ArrayNode array = (ArrayNode) container; + int index = Integer.parseInt(property); + if (index < array.size()) { + array.set(index, node); + } else { + // Fill any gap between current size and index with nulls (Jackson doesn't support sparse arrays). + for (int i = array.size(); i < index; i++) + array.add(array.nullNode()); + array.add(node); + } + break; + case OBJECT: + ((ObjectNode) container).set(property, node); + break; + default: + throw new IllegalArgumentException(ptr + " does not identify a settable container"); + } + setDirty(); + return this; + } + + @Override + public JsonCache set(JsonPointer ptr, short value) { + return set(ptr, (Object) value); + } + + @Override + public JsonCache set(JsonPointer ptr, String value) { + return set(ptr, (Object) value); + } + + @Override + public JsonCache set(String path, BigDecimal value) { + return set(JsonPointer.compile(path), value); + } + + @Override + public JsonCache set(String path, BigInteger value) { + return set(JsonPointer.compile(path), value); + } + + @Override + public JsonCache set(String path, boolean value) { + return set(JsonPointer.compile(path), value); + } + + @Override + public JsonCache set(String path, double value) { + return set(JsonPointer.compile(path), value); + } + + @Override + public JsonCache set(String path, float value) { + return set(JsonPointer.compile(path), value); + } + + @Override + public JsonCache set(String path, int value) { + return set(JsonPointer.compile(path), value); + } + + @Override + public JsonCache set(String path, List values) throws CacheException { + return set(JsonPointer.compile(path), values); + } + + @Override + public JsonCache set(String path, long value) { + return set(JsonPointer.compile(path), value); + } + + @Override + public JsonCache set(String path, Object value) { + return set(JsonPointer.compile(path), value); + } + + @Override + public JsonCache set(String path, short value) { + return set(JsonPointer.compile(path), value); + } + + @Override + public JsonCache set(String path, String value) { + return set(JsonPointer.compile(path), value); + } + + protected void setDirty() { + isDirty = true; + isLoaded = true; + } + + @Override + public int size(JsonPointer ptr) { + return root == null ? 0 : root.at(ptr).size(); + } + + @Override + public int size(String path) { + return size(JsonPointer.compile(path)); + } + + @Override + public String toString() { + return "JsonCacheImpl [root=" + root + ']'; + } + + @Override + public Root unload() { + isLoaded = false; + isDirty = false; + root = null; + return this; + } +} diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/CXF2InterfaceComparator.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/CXF2InterfaceComparator.mustache new file mode 100644 index 00000000000..d1fd0bf82c8 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/CXF2InterfaceComparator.mustache @@ -0,0 +1,120 @@ +package {{package}}; + + +import java.lang.reflect.Method; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import javax.ws.rs.HttpMethod; +import javax.ws.rs.Path; + +import org.apache.cxf.jaxrs.ext.ResourceComparator; +import org.apache.cxf.jaxrs.model.ClassResourceInfo; +import org.apache.cxf.jaxrs.model.OperationResourceInfo; +import org.apache.cxf.message.Message; + +/** + * This class only help CXF to decide which resource interface is more suitable. It used Java reflexion to iterate over Java methods but it *DO NOT* select the target method. + */ +public class CXFInterfaceComparator implements ResourceComparator { + + private static final Logger LOGGER = LoggerFactory.getLogger(CXFInterfaceComparator.class); + + @Override + public int compare(ClassResourceInfo cri1, ClassResourceInfo cri2, Message message) { + String requestVerb = (String) message.get(Message.HTTP_REQUEST_METHOD); + String requestURI = (String) message.get(Message.REQUEST_URI); + String requestPath = requestURI.replace((String) message.get(Message.BASE_PATH), ""); + + // remove "/"at the end of requestPath if present + if (requestPath.endsWith("/")){ + requestPath = requestPath.substring(0, requestPath.length()-1); + } + + if (analyseInterface(cri1, requestPath, requestVerb)) { + return -1; // Indicate that 'cri1' interface should be preferred + } else if (analyseInterface(cri2, requestPath, requestVerb)) { + return 1; // Indicate that 'cri2' interface should be preferred + } else { + return 0; // Nothing match, leave CXF decision + } + } + + /** + * Analyse each methods provided to check if there is a match with the + * message request path and request HTTP verb. + * + * @param cri + * the interface to be analysed + * @param requestPath + * the path of the request. Do not contains the host and base + * path + * @return true if a method match the request, false otherwise + */ + private static boolean analyseInterface(ClassResourceInfo cri, String requestPath, String requestVerb) { + assert cri.getServiceClass() != null; + assert cri.getServiceClass().getInterfaces() != null; + assert cri.getServiceClass().getInterfaces()[0] != null; + assert cri.getServiceClass().getInterfaces()[0].getMethods().length > 0; + + Method[] methods = cri.getServiceClass().getInterfaces()[0].getMethods(); + // Java reflexion. Check all the methods of an interface. + for (Method method : methods) { + Path pathAnnotation = method.getAnnotation(javax.ws.rs.Path.class); + if (pathAnnotation != null && pathAnnotation.value() != null) { + String pathValue = pathAnnotation.value(); + String methodHttpVerb = getMethodHttpVerb(method); + + // Always authorize OPTIONS request if the path is matching a method declaration + if (requestVerb.equals(HttpMethod.OPTIONS) && match(pathValue,requestPath)) { + return true; + } + // Also check the HTTP verb since a single path can be match do multiple request, depending of the HTTP request verb. + if (requestVerb.equals(methodHttpVerb) && match(pathValue, requestPath)) { + return true; + } + } + } + return false; + } + + private static String getMethodHttpVerb(Method method) { + if (method.getAnnotation(javax.ws.rs.POST.class) != null) { + return HttpMethod.POST; + } else if (method.getAnnotation(javax.ws.rs.GET.class) != null) { + return HttpMethod.GET; + } else if (method.getAnnotation(javax.ws.rs.PUT.class) != null) { + return HttpMethod.PUT; + } else if (method.getAnnotation(javax.ws.rs.OPTIONS.class) != null) { + return HttpMethod.OPTIONS; + } else if (method.getAnnotation(javax.ws.rs.DELETE.class) != null) { + return HttpMethod.DELETE; + } else if (method.getAnnotation(javax.ws.rs.HEAD.class) != null) { + return HttpMethod.HEAD; + } + assert false; + return null; + } + + /** + * Check whether if the pathValue match with the requestPath parameter. + * Every path params are considered to be declared as '{param}'. The tokens to start and close path params declaration are '{' and '}'. + * + * @param valueFromAnnotation + * @param valueFromRequest + * @return true if there is a match, false otherwise + */ + private static boolean match(String valueFromAnnotation, String valueFromRequest) { + String patternFinal = valueFromAnnotation.replaceAll("\\{(.*?)\\}", "([^/]*)").replace("/", "\\/"); + Matcher matcher = Pattern.compile(patternFinal).matcher(valueFromRequest); + if (matcher.matches()) { + return true; + } + return false; + } + + @Override + public int compare(OperationResourceInfo ori1, OperationResourceInfo ori2, Message message) { + return 0; // Leave CXF decision + } +} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/allowableValues.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/allowableValues.mustache new file mode 100644 index 00000000000..a48256d027a --- /dev/null +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/allowableValues.mustache @@ -0,0 +1 @@ +{{#allowableValues}}allowableValues="{{#values}}{{{.}}}{{^-last}}, {{/-last}}{{/values}}{{^values}}range=[{{#min}}{{.}}{{/min}}{{^min}}-infinity{{/min}}, {{#max}}{{.}}{{/max}}{{^max}}infinity{{/max}}]{{/values}}"{{/allowableValues}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/api.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/api.mustache new file mode 100644 index 00000000000..514f9093715 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/api.mustache @@ -0,0 +1,70 @@ +package {{package}}; + +{{#imports}}import {{import}}; +{{/imports}} + +import java.io.InputStream; +import java.io.OutputStream; +import java.util.List; +import java.util.Map; +import javax.ws.rs.*; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.MediaType; +import org.apache.cxf.jaxrs.ext.multipart.*; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiResponses; +import io.swagger.annotations.ApiResponse; +import io.swagger.jaxrs.PATCH; +{{#useBeanValidation}} +import javax.validation.constraints.*; +import javax.validation.Valid; +{{/useBeanValidation}} + +{{#appName}} +/** + * {{{appName}}} + * + {{#appDescription}} + *

{{{appDescription}}} + * + {{/appDescription}} + */ +{{/appName}} +@Path("{{^useAnnotatedBasePath}}/{{/useAnnotatedBasePath}}{{#useAnnotatedBasePath}}{{contextPath}}{{/useAnnotatedBasePath}}") +@Api(value = "/", description = "{{description}}") +{{#addConsumesProducesJson}} +@Consumes(MediaType.APPLICATION_JSON) +@Produces(MediaType.APPLICATION_JSON) +{{/addConsumesProducesJson}} +public interface {{classname}} { +{{#operations}} +{{#operation}} + + {{#summary}} + /** + * {{summary}} + * + {{#notes}} + * {{notes}} + * + {{/notes}} + */ + {{/summary}} + @{{httpMethod}} + {{#subresourceOperation}}@Path("{{{path}}}"){{/subresourceOperation}} +{{#hasConsumes}} + @Consumes({ {{#consumes}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} }) +{{/hasConsumes}} +{{#hasProduces}} + @Produces({ {{#produces}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }) +{{/hasProduces}} + @ApiOperation(value = "{{{summary}}}", tags={ {{#vendorExtensions.x-tags}}"{{tag}}"{{#hasMore}}, {{/hasMore}}{{/vendorExtensions.x-tags}} }) + @ApiResponses(value = { {{#responses}} + @ApiResponse(code = {{{code}}}, message = "{{{message}}}"{{^vendorExtensions.x-java-is-response-void}}, response = {{{baseType}}}.class{{#containerType}}, responseContainer = "{{{containerType}}}"{{/containerType}}{{/vendorExtensions.x-java-is-response-void}}){{#hasMore}},{{/hasMore}}{{/responses}} }) + public {{>returnTypes}} {{operationId}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); +{{/operation}} +} +{{/operations}} + diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/apiServiceImpl.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/apiServiceImpl.mustache new file mode 100644 index 00000000000..aa92850c125 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/apiServiceImpl.mustache @@ -0,0 +1,93 @@ +package {{package}}.impl; + +import {{package}}.*; +{{#imports}}import {{import}}; +{{/imports}} + +import java.io.InputStream; +import java.io.OutputStream; +import java.util.List; +import java.util.Map; +{{#generateOperationBody}} +import java.io.File; +import com.fasterxml.jackson.databind.node.JsonNodeFactory; +import com.fasterxml.jackson.databind.node.ObjectNode; +{{#loadTestDataFromFile}} +import org.openapitools.codegen.utils.JsonCache; +import org.openapitools.codegen.utils.JsonCache.CacheException; +{{/loadTestDataFromFile}} +{{/generateOperationBody}} +import javax.ws.rs.*; +import javax.ws.rs.core.Response; +import org.apache.cxf.jaxrs.model.wadl.Description; +import org.apache.cxf.jaxrs.model.wadl.DocTarget; + +import org.apache.cxf.jaxrs.ext.multipart.*; + +import io.swagger.annotations.Api; +{{#useSpringAnnotationConfig}} +import org.springframework.stereotype.Service; +{{/useSpringAnnotationConfig}} + +{{#useSpringAnnotationConfig}} +@Service("{{classname}}") +{{/useSpringAnnotationConfig}} +{{#description}} +{{/description}} +{{#appName}} +/** + * {{{appName}}} + * + {{#appDescription}} + *

{{{appDescription}}} + {{/appDescription}} + * + */ +{{/appName}} +public class {{classname}}ServiceImpl implements {{classname}} { +{{#generateOperationBody}} +{{#loadTestDataFromFile}} + private JsonCache cache; + + { + try { + File cacheFile = new File(System.getProperty("jaxrs.test.server.json", + "{{testDataFile}}")); + cache = JsonCache.Factory.instance.get("test-data").load(cacheFile).child("/{{invokerPackage}}/{{classname}}"); + } catch (CacheException e) { + e.printStackTrace(); + } + } + +{{/loadTestDataFromFile}} +{{/generateOperationBody}} +{{#operations}} +{{#operation}} + {{#summary}} + /** + * {{summary}} + * + {{#notes}} + * {{notes}} + * + {{/notes}} + */ + {{/summary}} + @Override + public {{>returnTypes}} {{operationId}}({{#allParams}}{{>queryParamsImpl}}{{>pathParamsImpl}}{{>headerParamsImpl}}{{>bodyParamsImpl}}{{>formParamsImpl}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { + {{^loadTestDataFromFile}} + // TODO: Implement... + {{/loadTestDataFromFile}} +{{! generic response: + }}{{#useGenericResponse}}return Response.ok().entity("magic!").build();{{/useGenericResponse}}{{! +non-generic response: }}{{^useGenericResponse}}{{! +non-void response: }}{{^vendorExtensions.x-java-is-response-void}}{{! +pre-populated operation body: }}{{#generateOperationBody}}{{{vendorExtensions.x-java-operation-body}}}{{/generateOperationBody}}{{! +null response: }}{{^generateOperationBody}} return null;{{/generateOperationBody}}{{! +}}{{/vendorExtensions.x-java-is-response-void}}{{! +}}{{/useGenericResponse}} + } + +{{/operation}} +} +{{/operations}} diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/api_test.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/api_test.mustache new file mode 100644 index 00000000000..c268314c97e --- /dev/null +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/api_test.mustache @@ -0,0 +1,197 @@ +{{>licenseInfo}} + +package {{package}}; + +{{#imports}}import {{import}}; +{{/imports}} +import org.junit.Test; +import org.junit.Before; +import static org.junit.Assert.*; + +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import org.apache.cxf.jaxrs.client.JAXRSClientFactory; +import org.apache.cxf.jaxrs.client.ClientConfiguration; +import org.apache.cxf.jaxrs.client.WebClient; +import org.apache.cxf.jaxrs.ext.multipart.Attachment; +{{#useGzipFeature}} +import org.apache.cxf.transport.common.gzip.GZIPInInterceptor; +import org.apache.cxf.transport.common.gzip.GZIPOutInterceptor; +{{/useGzipFeature}} + +{{#useLoggingFeature}} +import org.apache.cxf.interceptor.LoggingOutInterceptor; +{{/useLoggingFeature}} + +import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider; +import com.fasterxml.jackson.jaxrs.xml.JacksonXMLProvider; +import org.apache.cxf.jaxrs.provider.MultipartProvider; + +{{^fullJavaUtil}} +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +{{/fullJavaUtil}} + +{{#generateSpringBootApplication}} +import org.junit.runner.RunWith; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.boot.web.server.LocalServerPort; +{{/generateSpringBootApplication}} +{{#generateOperationBody}} +import java.io.File; +{{^fullJavaUtil}} +import java.util.Set; +{{/fullJavaUtil}} +import javax.validation.ConstraintViolation; +import javax.validation.Validation; +import javax.validation.Validator; +import javax.validation.ValidatorFactory; +import com.fasterxml.jackson.databind.node.JsonNodeFactory; +import com.fasterxml.jackson.databind.node.ObjectNode; +import org.junit.BeforeClass; +{{#loadTestDataFromFile}} +import org.openapitools.codegen.utils.JsonCache; +{{/loadTestDataFromFile}} +{{/generateOperationBody}} + +/** + {{#appName}} + * {{{appName}}} + * + {{/appName}} + {{#appDescription}} + *

{{{appDescription}}} + * + {{/appDescription}} + * API tests for {{classname}}. + */ +{{#generateSpringBootApplication}} +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) +{{/generateSpringBootApplication}} +public class {{classname}}Test { +{{#generateOperationBody}} + private static Validator validator; +{{#loadTestDataFromFile}} + private static JsonCache cache; +{{/loadTestDataFromFile}} + + @BeforeClass + public static void beforeClass() throws Exception { +{{#loadTestDataFromFile}} + File cacheFile = new File(System.getProperty("jaxrs.test.client.json", + "{{testDataFile}}")); + cache = JsonCache.Factory.instance.get("test-data").load(cacheFile).child("/{{invokerPackage}}/{{classname}}"); + +{{/loadTestDataFromFile}} + validator = Validation.buildDefaultValidatorFactory().getValidator(); + } + +{{/generateOperationBody}} +{{#generateSpringBootApplication}} + @LocalServerPort + private int serverPort; +{{/generateSpringBootApplication}} + + private {{classname}} api; + + @Before + public void setup() { + List providers = Arrays.asList(new JacksonJsonProvider(), new JacksonXMLProvider(), new MultipartProvider()); + +{{#generateSpringBootApplication}} + api = JAXRSClientFactory.create("http://localhost:" + serverPort + "/services", {{classname}}.class, providers); +{{/generateSpringBootApplication}} +{{^generateSpringBootApplication}} + api = JAXRSClientFactory.create("{{{basePath}}}", {{classname}}.class, providers); +{{/generateSpringBootApplication}} + org.apache.cxf.jaxrs.client.Client client = WebClient.client(api); + + ClientConfiguration config = WebClient.getConfig(client); +{{#useGzipFeatureForTests}} + // Example for using Gzipping + GZIPOutInterceptor gzipOutInterceptor = new GZIPOutInterceptor(); + // use Gzipping for first request sent to server + //gzipOutInterceptor.setForce(true); + config.getOutInterceptors().add(gzipOutInterceptor); + + config.getInInterceptors().add(new GZIPInInterceptor()); +{{/useGzipFeatureForTests}} +{{#useLoggingFeatureForTests}} + LoggingOutInterceptor loggingOutInterceptor = new LoggingOutInterceptor(); + config.getOutInterceptors().add(loggingOutInterceptor); +{{/useLoggingFeatureForTests}} + } + +{{#generateOperationBody}} + private void validate(Object o) { + assertNotNull(o); + Set> violations = validator.validate(o); + if (!violations.isEmpty()) { + StringBuilder message = new StringBuilder("Validation failed"); + for (ConstraintViolation violation : violations) + message.append("; ").append(violation.getPropertyPath()).append(": ").append(violation.getMessage()); + fail(message.toString()); + } + } + +{{/generateOperationBody}} + {{#operations}}{{#operation}} + /** + {{#summary}} + * {{summary}} + * + {{#notes}} + * {{notes}} + * + {{/notes}} + {{/summary}} + * @throws ApiException if the API call fails + */ + @Test + public void {{operationId}}Test() throws Exception { + {{#hasParams}} + {{^loadTestDataFromFile}} + // TODO: assign appropriate parameter values + {{/loadTestDataFromFile}} + {{/hasParams}} + {{#allParams}} + {{^isFile}} + {{#generateOperationBody}} +{{{vendorExtensions.x-java-param-decl}}}{{! + }}{{/generateOperationBody}}{{! + }}{{^generateOperationBody}}{{! +}} {{{dataType}}} {{paramName}} = null; + {{/generateOperationBody}} + {{/isFile}} + {{#isFile}} + {{#generateOperationBody}} + + {{/generateOperationBody}} + Attachment {{paramName}} = new Attachment("{{paramName}}", MediaType.TEXT_PLAIN, "Dummy attachment content");{{! + }}{{^generateOperationBody}} + {{/generateOperationBody}} + {{/isFile}} + {{/allParams}} + {{^loadTestDataFromFile}} + + // TODO: delete this line and uncomment the next + {{/loadTestDataFromFile}} + {{#loadTestDataFromFile}} + + {{/loadTestDataFromFile}} + {{^loadTestDataFromFile}}// {{/loadTestDataFromFile}}{{^vendorExtensions.x-java-is-response-void}}{{>returnTypes}} response = {{/vendorExtensions.x-java-is-response-void}}api.{{operationId}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); + {{^vendorExtensions.x-java-is-response-void}} + // TODO: complete test assertions + {{#generateOperationBody}} + {{^loadTestDataFromFile}}// {{/loadTestDataFromFile}}validate(response); + {{/generateOperationBody}} + {{/vendorExtensions.x-java-is-response-void}} + } + {{/operation}}{{/operations}} +} diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/beanValidation.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/beanValidation.mustache new file mode 100644 index 00000000000..c8c6946fef6 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/beanValidation.mustache @@ -0,0 +1,4 @@ +{{#required}} + @NotNull +{{/required}} +{{>beanValidationCore}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/beanValidationCore.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/beanValidationCore.mustache new file mode 100644 index 00000000000..8bcdce3df16 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/beanValidationCore.mustache @@ -0,0 +1,20 @@ +{{#pattern}} @Pattern(regexp="{{{pattern}}}"){{/pattern}}{{! +minLength && maxLength set +}}{{#minLength}}{{#maxLength}} @Size(min={{minLength}},max={{maxLength}}){{/maxLength}}{{/minLength}}{{! +minLength set, maxLength not +}}{{#minLength}}{{^maxLength}} @Size(min={{minLength}}){{/maxLength}}{{/minLength}}{{! +minLength not set, maxLength set +}}{{^minLength}}{{#maxLength}} @Size(max={{maxLength}}){{/maxLength}}{{/minLength}}{{! +@Size: minItems && maxItems set +}}{{#minItems}}{{#maxItems}} @Size(min={{minItems}},max={{maxItems}}){{/maxItems}}{{/minItems}}{{! +@Size: minItems set, maxItems not +}}{{#minItems}}{{^maxItems}} @Size(min={{minItems}}){{/maxItems}}{{/minItems}}{{! +@Size: minItems not set && maxItems set +}}{{^minItems}}{{#maxItems}} @Size(max={{maxItems}}){{/maxItems}}{{/minItems}}{{! +check for integer or long / all others=decimal type with @Decimal* +isInteger set +}}{{#isInteger}}{{#minimum}} @Min({{minimum}}){{/minimum}}{{#maximum}} @Max({{maximum}}){{/maximum}}{{/isInteger}}{{! +isLong set +}}{{#isLong}}{{#minimum}} @Min({{minimum}}L){{/minimum}}{{#maximum}} @Max({{maximum}}L){{/maximum}}{{/isLong}}{{! +Not Integer, not Long => we have a decimal value! +}}{{^isInteger}}{{^isLong}}{{#minimum}} @DecimalMin("{{minimum}}"){{/minimum}}{{#maximum}} @DecimalMax("{{maximum}}"){{/maximum}}{{/isLong}}{{/isInteger}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/beanValidationHeaderParams.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/beanValidationHeaderParams.mustache new file mode 100644 index 00000000000..f8eef8f94c7 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/beanValidationHeaderParams.mustache @@ -0,0 +1 @@ +{{#required}} @NotNull{{/required}}{{>beanValidationCore}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/beanValidationPathParams.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/beanValidationPathParams.mustache new file mode 100644 index 00000000000..051bd53c0a5 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/beanValidationPathParams.mustache @@ -0,0 +1 @@ +{{! PathParam is always required, no @NotNull necessary }}{{>beanValidationCore}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/beanValidationQueryParams.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/beanValidationQueryParams.mustache new file mode 100644 index 00000000000..f8eef8f94c7 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/beanValidationQueryParams.mustache @@ -0,0 +1 @@ +{{#required}} @NotNull{{/required}}{{>beanValidationCore}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/bodyParams.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/bodyParams.mustache new file mode 100644 index 00000000000..be56da7535b --- /dev/null +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/bodyParams.mustache @@ -0,0 +1 @@ +{{#isBodyParam}}{{#useBeanValidation}}@Valid {{/useBeanValidation}}{{{dataType}}} {{paramName}}{{/isBodyParam}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/bodyParamsImpl.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/bodyParamsImpl.mustache new file mode 100644 index 00000000000..c7d1abfe527 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/bodyParamsImpl.mustache @@ -0,0 +1 @@ +{{#isBodyParam}}{{{dataType}}} {{paramName}}{{/isBodyParam}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/enumClass.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/enumClass.mustache new file mode 100644 index 00000000000..39d7e42df3d --- /dev/null +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/enumClass.mustache @@ -0,0 +1,33 @@ +@XmlType(name="{{datatypeWithEnum}}") +@XmlEnum({{dataType}}.class) +public enum {{datatypeWithEnum}} { + + {{#allowableValues}} + {{#enumVars}}@XmlEnumValue({{#isInteger}}"{{/isInteger}}{{#isDouble}}"{{/isDouble}}{{#isLong}}"{{/isLong}}{{#isFloat}}"{{/isFloat}}{{{value}}}{{#isInteger}}"{{/isInteger}}{{#isDouble}}"{{/isDouble}}{{#isLong}}"{{/isLong}}{{#isFloat}}"{{/isFloat}}) @JsonProperty({{#isInteger}}"{{/isInteger}}{{#isDouble}}"{{/isDouble}}{{#isLong}}"{{/isLong}}{{#isFloat}}"{{/isFloat}}{{{value}}}{{#isInteger}}"{{/isInteger}}{{#isDouble}}"{{/isDouble}}{{#isLong}}"{{/isLong}}{{#isFloat}}"{{/isFloat}}) {{name}}({{dataType}}.valueOf({{{value}}})){{^-last}}, + {{/-last}}{{#-last}};{{/-last}}{{/enumVars}} + {{/allowableValues}} + + private {{dataType}} value; + + {{datatypeWithEnum}} ({{dataType}} v) { + value = v; + } + + public {{dataType}} value() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static {{datatypeWithEnum}} fromValue(String v) { + for ({{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} b : {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}.values()) { + if (String.valueOf(b.value).equals(v)) { + return b; + } + } + {{#useNullForUnknownEnumValue}}return null;{{/useNullForUnknownEnumValue}}{{^useNullForUnknownEnumValue}}throw new IllegalArgumentException("Unexpected value '" + v + "'");{{/useNullForUnknownEnumValue}} + } +} diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/enumOuterClass.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/enumOuterClass.mustache new file mode 100644 index 00000000000..df2c7287396 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/enumOuterClass.mustache @@ -0,0 +1,48 @@ +{{#jackson}} +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +{{/jackson}} + +/** + * {{^description}}Gets or Sets {{{name}}}{{/description}}{{#description}}{{description}}{{/description}} + */ +public enum {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} { + {{#gson}} + {{#allowableValues}}{{#enumVars}} + @SerializedName({{#isInteger}}"{{/isInteger}}{{#isDouble}}"{{/isDouble}}{{#isLong}}"{{/isLong}}{{#isFloat}}"{{/isFloat}}{{{value}}}{{#isInteger}}"{{/isInteger}}{{#isDouble}}"{{/isDouble}}{{#isLong}}"{{/isLong}}{{#isFloat}}"{{/isFloat}}) + {{{name}}}({{{value}}}){{^-last}}, + {{/-last}}{{#-last}};{{/-last}}{{/enumVars}}{{/allowableValues}} + {{/gson}} + {{^gson}} + {{#allowableValues}}{{#enumVars}} + {{{name}}}({{{value}}}){{^-last}}, + {{/-last}}{{#-last}};{{/-last}}{{/enumVars}}{{/allowableValues}} + {{/gson}} + + private {{{dataType}}} value; + + {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}({{{dataType}}} value) { + this.value = value; + } + + @Override +{{#jackson}} + @JsonValue +{{/jackson}} + public String toString() { + return String.valueOf(value); + } + +{{#jackson}} + @JsonCreator +{{/jackson}} + public static {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} fromValue(String text) { + for ({{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} b : {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + {{#useNullForUnknownEnumValue}}return null;{{/useNullForUnknownEnumValue}}{{^useNullForUnknownEnumValue}}throw new IllegalArgumentException("Unexpected value '" + text + "'");{{/useNullForUnknownEnumValue}} + } + +} diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/formParams.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/formParams.mustache new file mode 100644 index 00000000000..97216dc1806 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/formParams.mustache @@ -0,0 +1 @@ +{{#isFormParam}}{{^isFile}}@Multipart(value = "{{baseName}}"{{^required}}, required = false{{/required}}) {{{dataType}}} {{paramName}}{{/isFile}}{{#isFile}} @Multipart(value = "{{baseName}}" {{^required}}, required = false{{/required}}) Attachment {{paramName}}Detail{{/isFile}}{{/isFormParam}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/formParamsImpl.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/formParamsImpl.mustache new file mode 100644 index 00000000000..2be40e1ddd3 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/formParamsImpl.mustache @@ -0,0 +1 @@ +{{#isFormParam}}{{^isFile}}{{{dataType}}} {{paramName}}{{/isFile}}{{#isFile}} Attachment {{paramName}}Detail{{/isFile}}{{/isFormParam}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/generatedAnnotation.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/generatedAnnotation.mustache new file mode 100644 index 00000000000..49110fc1ad9 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/generatedAnnotation.mustache @@ -0,0 +1 @@ +@javax.annotation.Generated(value = "{{generatorClass}}", date = "{{generatedDate}}") \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/headerParams.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/headerParams.mustache new file mode 100644 index 00000000000..4a9009e76a2 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/headerParams.mustache @@ -0,0 +1 @@ +{{#isHeaderParam}}@HeaderParam("{{baseName}}") {{#useBeanValidation}}{{>beanValidationHeaderParams}}{{/useBeanValidation}} {{{dataType}}} {{paramName}}{{/isHeaderParam}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/headerParamsImpl.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/headerParamsImpl.mustache new file mode 100644 index 00000000000..bd03573d196 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/headerParamsImpl.mustache @@ -0,0 +1 @@ +{{#isHeaderParam}}{{{dataType}}} {{paramName}}{{/isHeaderParam}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/licenseInfo.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/licenseInfo.mustache new file mode 100644 index 00000000000..bc4442af17e --- /dev/null +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/licenseInfo.mustache @@ -0,0 +1,23 @@ +/** + * {{{appName}}} + * {{{appDescription}}} + * + * {{#version}}OpenAPI spec version: {{{version}}}{{/version}} + * {{#infoEmail}}Contact: {{{infoEmail}}}{{/infoEmail}} + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/model.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/model.mustache new file mode 100644 index 00000000000..ee1912f51ff --- /dev/null +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/model.mustache @@ -0,0 +1,22 @@ +package {{package}}; + +{{#imports}}import {{import}}; +{{/imports}} +{{#serializableModel}} +import java.io.Serializable; +{{/serializableModel}} +{{#useBeanValidation}} +import javax.validation.constraints.*; +import javax.validation.Valid; +{{/useBeanValidation}} + +{{#models}} +{{#model}} +{{#isEnum}} +{{>enumOuterClass}} +{{/isEnum}} +{{^isEnum}} +{{>pojo}} +{{/isEnum}} +{{/model}} +{{/models}} diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/pathParams.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/pathParams.mustache new file mode 100644 index 00000000000..9e8455d5ac7 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/pathParams.mustache @@ -0,0 +1 @@ +{{#isPathParam}}@PathParam("{{baseName}}"){{#useBeanValidation}}{{>beanValidationPathParams}}{{/useBeanValidation}} {{{dataType}}} {{paramName}}{{/isPathParam}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/pathParamsImpl.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/pathParamsImpl.mustache new file mode 100644 index 00000000000..6829cf8c7a6 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/pathParamsImpl.mustache @@ -0,0 +1 @@ +{{#isPathParam}}{{{dataType}}} {{paramName}}{{/isPathParam}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/pojo.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/pojo.mustache new file mode 100644 index 00000000000..b88e241cce4 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/pojo.mustache @@ -0,0 +1,152 @@ +import io.swagger.annotations.ApiModelProperty; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; +import com.fasterxml.jackson.annotation.JsonFormat; +import com.fasterxml.jackson.annotation.JsonProperty; + +{{#withXml}} +@XmlAccessorType(XmlAccessType.FIELD) +{{#hasVars}} @XmlType(name = "{{classname}}", propOrder = + { {{#vars}}"{{name}}"{{^-last}}, {{/-last}}{{/vars}} +}){{/hasVars}} +{{^hasVars}}@XmlType(name = "{{classname}}"){{/hasVars}} +{{^parent}}@XmlRootElement(name="{{classname}}"){{/parent}} +{{/withXml}} +{{#description}} +/** + * {{{description}}} + */ +@ApiModel(description="{{{description}}}") +{{/description}} +public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}}{{#serializableModel}} implements Serializable{{/serializableModel}} { + {{#vars}}{{#isEnum}}{{^isContainer}} +{{>enumClass}}{{/isContainer}}{{#isContainer}}{{#mostInnerItems}} +{{>enumClass}}{{/mostInnerItems}}{{/isContainer}}{{/isEnum}} +{{#description}} + /** + * {{{description}}} + */ +{{/description}} +{{#withXml}} + @XmlElement(name="{{baseName}}"{{#required}}, required = {{required}}{{/required}}) +{{/withXml}} + @ApiModelProperty({{#example}}example = "{{{example}}}", {{/example}}{{#required}}required = {{required}}, {{/required}}value = "{{{description}}}"){{^isPrimitiveType}}{{^isDate}}{{^isDateTime}}{{^isString}}{{^isFile}}{{#useBeanValidation}} + @Valid{{/useBeanValidation}}{{/isFile}}{{/isString}}{{/isDateTime}}{{/isDate}}{{/isPrimitiveType}} +{{#isDate}} + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd") +{{/isDate}} +{{#isDateTime}} + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'hh:mm:ss.SSSX") +{{/isDateTime}} +{{#isContainer}} + private {{{datatypeWithEnum}}} {{name}}{{#required}} = {{{defaultValue}}}{{/required}}{{^required}} = null{{/required}}; +{{/isContainer}} +{{^isContainer}} + private {{{datatypeWithEnum}}} {{name}}{{#defaultValue}} = {{{.}}}{{/defaultValue}}; +{{/isContainer}} + {{/vars}} + {{#vars}} + /** + {{#description}} + * {{description}} + {{/description}} + {{^description}} + * Get {{name}} + {{/description}} + {{#minimum}} + * minimum: {{minimum}} + {{/minimum}} + {{#maximum}} + * maximum: {{maximum}} + {{/maximum}} + * @return {{name}} + */ + @JsonProperty("{{baseName}}") +{{#vendorExtensions.extraAnnotation}} + {{{vendorExtensions.extraAnnotation}}} +{{/vendorExtensions.extraAnnotation}} +{{#useBeanValidation}}{{>beanValidation}}{{/useBeanValidation}} {{#isEnum}}{{^isListContainer}}{{^isMapContainer}}public {{dataType}} {{getter}}() { + return {{name}} == null ? null : {{name}}.value(); + }{{/isMapContainer}}{{/isListContainer}}{{/isEnum}}{{#isEnum}}{{#isListContainer}}public {{{datatypeWithEnum}}} {{getter}}() { + return {{name}}; + }{{/isListContainer}}{{/isEnum}}{{#isEnum}}{{#isMapContainer}}public {{{datatypeWithEnum}}} {{getter}}() { + return {{name}}; + }{{/isMapContainer}}{{/isEnum}}{{^isEnum}}public {{{datatypeWithEnum}}} {{getter}}() { + return {{name}}; + }{{/isEnum}} + + /** + * Sets the {{name}} property. +{{#isReadOnly}} + *
N.B. {{name}} is read only; client code should not call this method. +{{/isReadOnly}} + */ + public void {{setter}}({{{datatypeWithEnum}}} {{name}}) { + this.{{name}} = {{name}}; + } + + /** + * Sets the {{name}} property. +{{#isReadOnly}} + *
N.B. {{name}} is read only; client code should not call this method. +{{/isReadOnly}} + */ + public {{classname}} {{name}}({{{datatypeWithEnum}}} {{name}}) { + this.{{name}} = {{name}}; + return this; + } + {{#isListContainer}} + + /** + * Adds a new item to the {{name}} list. +{{#isReadOnly}} + *
N.B. {{name}} is read only; client code should not call this method. +{{/isReadOnly}} + */ + public {{classname}} add{{nameInCamelCase}}Item({{{items.datatypeWithEnum}}} {{name}}Item) { + this.{{name}}.add({{name}}Item); + return this; + } + {{/isListContainer}} + {{#isMapContainer}} + + /** + * Puts a new item into the {{name}} map. +{{#isReadOnly}} + *
N.B. {{name}} is read only; client code should not call this method. +{{/isReadOnly}} + */ + public {{classname}} put{{nameInCamelCase}}Item(String key, {{{items.datatypeWithEnum}}} {{name}}Item) { + this.{{name}}.put(key, {{name}}Item); + return this; + } + {{/isMapContainer}} + + {{/vars}} + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class {{classname}} {\n"); + {{#parent}}sb.append(" ").append(toIndentedString(super.toString())).append("\n");{{/parent}} + {{#vars}}sb.append(" {{name}}: ").append(toIndentedString({{name}})).append("\n"); + {{/vars}}sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/pom.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/pom.mustache new file mode 100644 index 00000000000..40de23abd33 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/pom.mustache @@ -0,0 +1,219 @@ + + 4.0.0 + {{groupId}} + {{artifactId}} + jar + {{artifactId}} + {{#appDescription}} + {{appDescription}} + {{/appDescription}} + {{artifactVersion}} + + src/main/java + + + maven-failsafe-plugin + 2.6 + + + + integration-test + verify + + + + + + + org.codehaus.mojo + build-helper-maven-plugin + 1.9.1 + + + add-source + generate-sources + + add-source + + + + src/gen/java + + + + + + + + + + io.swagger + swagger-jaxrs + compile + ${swagger-core-version} + + + ch.qos.logback + logback-classic + ${logback-version} + compile + + + ch.qos.logback + logback-core + ${logback-version} + compile + + + junit + junit + ${junit-version} + test + +{{#useBeanValidation}} + + + javax.validation + validation-api + ${beanvalidation-version} + provided + +{{/useBeanValidation}} + + + org.apache.cxf + cxf-rt-rs-client + ${cxf-version} + test + + + + + org.apache.cxf + cxf-rt-frontend-jaxrs + ${cxf-version} + compile + + + org.apache.cxf + cxf-rt-rs-service-description + ${cxf-version} + compile + + + org.apache.cxf + cxf-rt-ws-policy + ${cxf-version} + compile + + + org.apache.cxf + cxf-rt-wsdl + ${cxf-version} + compile + + + com.fasterxml.jackson.jaxrs + jackson-jaxrs-json-provider + ${jackson-jaxrs-version} + compile + + + com.fasterxml.jackson.jaxrs + jackson-jaxrs-xml-provider + ${jackson-jaxrs-version} + compile + +{{#java8}} + + com.fasterxml.jackson.datatype + jackson-datatype-jsr310 + ${jackson-jaxrs-version} + +{{/java8}} +{{^java8}} + + com.fasterxml.jackson.datatype + jackson-datatype-joda + ${jackson-jaxrs-version} + +{{/java8}} +{{#useBeanValidationFeature}} + + org.hibernate + hibernate-validator + 5.2.2.Final + +{{/useBeanValidationFeature}} + + + + sonatype-snapshots + https://oss.sonatype.org/content/repositories/snapshots + + true + + + + + {{#java8}}1.8{{/java8}}{{^java8}}1.7{{/java8}} + ${java.version} + ${java.version} + 1.5.18 + 9.2.9.v20150224 + 4.12 + 1.1.7 + 2.5 +{{#useBeanValidation}} + 1.1.0.Final +{{/useBeanValidation}} + 3.3.0 + 2.9.8 + UTF-8 + + diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/queryParams.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/queryParams.mustache new file mode 100644 index 00000000000..ca2c6e106f7 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/queryParams.mustache @@ -0,0 +1 @@ +{{#isQueryParam}}@QueryParam("{{baseName}}"){{#useBeanValidation}}{{>beanValidationQueryParams}}{{/useBeanValidation}} {{^isContainer}}{{#defaultValue}}@DefaultValue({{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}{{{defaultValue}}}{{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}) {{/defaultValue}}{{/isContainer}}{{{dataType}}} {{paramName}}{{/isQueryParam}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/queryParamsImpl.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/queryParamsImpl.mustache new file mode 100644 index 00000000000..ff79730471d --- /dev/null +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/queryParamsImpl.mustache @@ -0,0 +1 @@ +{{#isQueryParam}}{{{dataType}}} {{paramName}}{{/isQueryParam}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/returnTypes.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/returnTypes.mustache new file mode 100644 index 00000000000..6af86ffe4e4 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/returnTypes.mustache @@ -0,0 +1,4 @@ +{{#useGenericResponse}}Response{{/useGenericResponse}}{{! non-generic response: +}}{{^useGenericResponse}}{{! +}}{{{returnType}}}{{! +}}{{/useGenericResponse}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/server/ApplicationContext.xml.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/server/ApplicationContext.xml.mustache new file mode 100644 index 00000000000..b911475e293 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/server/ApplicationContext.xml.mustache @@ -0,0 +1,148 @@ + + + + + + + + + + + + +{{#useSpringAnnotationConfig}} + + +{{/useSpringAnnotationConfig}} +{{^useSpringAnnotationConfig}} +{{#apiInfo}} +{{#apis}} + +{{/apis}} +{{/apiInfo}} + +{{/useSpringAnnotationConfig}} +{{#useSwaggerFeature}} + + {{! http://cxf.apache.org/docs/swagger2feature.html }} + + +{{#useSwaggerUI}} + +{{/useSwaggerUI}} + + + +{{/useSwaggerFeature}} + + +{{#useGzipFeature}} + +{{/useGzipFeature}} +{{#useBeanValidationFeature}} + + +{{/useBeanValidationFeature}} + + +{{#useGzipFeature}} + +{{/useGzipFeature}} +{{#useBeanValidationFeature}} + + +{{/useBeanValidationFeature}} + + +{{#useLoggingFeature}} + +{{/useLoggingFeature}} +{{#useGzipFeature}} + +{{/useGzipFeature}} + + + + + + +{{#useWadlFeature}} + + + + +{{/useWadlFeature}} +{{#useGzipFeature}} + + + + + + + + +{{/useGzipFeature}} +{{#useBeanValidationFeature}} + + + + + + + + + + + +{{/useBeanValidationFeature}} +{{^useBeanValidationFeature}} + + + +{{/useBeanValidationFeature}} + + + + +{{#apiInfo}} +{{#apis}} + +{{/apis}} +{{/apiInfo}} + + + + + + +{{#useWadlFeature}} + +{{/useWadlFeature}} + + +{{#useSwaggerFeature}} + +{{/useSwaggerFeature}} +{{#useBeanValidationFeature}} + +{{/useBeanValidationFeature}} + + + + diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/server/SpringBootApplication.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/server/SpringBootApplication.mustache new file mode 100644 index 00000000000..a65a60f3ec2 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/server/SpringBootApplication.mustache @@ -0,0 +1,25 @@ +package {{apiPackage}}; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.SpringBootConfiguration; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; +import org.springframework.context.annotation.ImportResource; + +@ImportResource({"classpath:/ApplicationContext{{#supportMultipleSpringServices}}-{{invokerPackage}}{{/supportMultipleSpringServices}}.xml"}) +@EnableAutoConfiguration +@SpringBootConfiguration +public class SpringBootApplication extends SpringBootServletInitializer { + + @Override + protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { + return application.sources(SpringBootApplication.class); + } + + public static void main(String[] args) { + SpringApplication.run(SpringBootApplication.class, args); + } + + +} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/server/application.properties.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/server/application.properties.mustache new file mode 100644 index 00000000000..dae57151736 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/server/application.properties.mustache @@ -0,0 +1 @@ +cxf.path=/ \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/server/context.xml.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/server/context.xml.mustache new file mode 100644 index 00000000000..a14b9a13d01 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/server/context.xml.mustache @@ -0,0 +1,18 @@ + + + + + + + + diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/server/jboss-web.xml.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/server/jboss-web.xml.mustache new file mode 100644 index 00000000000..ef688c10e91 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/server/jboss-web.xml.mustache @@ -0,0 +1,7 @@ + + + + + swagger-cxf-server + + diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/server/nonspring-web.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/server/nonspring-web.mustache new file mode 100644 index 00000000000..4542e024b87 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/server/nonspring-web.mustache @@ -0,0 +1,26 @@ + + + + + CXF Non-Spring Jaxrs Servlet + CXFNonSpringJaxrsServlet + org.apache.cxf.jaxrs.servlet.CXFNonSpringJaxrsServlet +{{#apiInfo}} + + jaxrs.serviceClasses + {{#apis}}{{package}}.impl.{{classname}}ServiceImpl{{^-last}},{{/-last}}{{/apis}} + +{{/apiInfo}} + + jaxrs.providers + com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider + + + + + CXFNonSpringJaxrsServlet + /rest/* + + + diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/server/openapi-generator-ignore.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/server/openapi-generator-ignore.mustache new file mode 100644 index 00000000000..d6fa6d5a2ac --- /dev/null +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/server/openapi-generator-ignore.mustache @@ -0,0 +1,25 @@ +# 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 + +{{#loadTestDataFromFile}}#{{/loadTestDataFromFile}}**/impl/* diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/server/pom.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/server/pom.mustache new file mode 100644 index 00000000000..6d16df1fd37 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/server/pom.mustache @@ -0,0 +1,347 @@ + + 4.0.0 + {{groupId}} + {{artifactId}} + war + {{artifactId}} + {{#appDescription}} + {{appDescription}} + {{/appDescription}} + {{artifactVersion}} +{{#generateSpringBootApplication}} + + org.springframework.boot + spring-boot-starter-parent + 2.0.4.RELEASE + +{{/generateSpringBootApplication}} + + src/main/java + + + maven-failsafe-plugin + + + + integration-test + verify + + + + + + + org.codehaus.mojo + build-helper-maven-plugin +{{^generateSpringBootApplication}} + 1.9.1 +{{/generateSpringBootApplication}} + + + add-source + generate-sources + + add-source + + + + src/gen/java + + + + + + + + + maven-war-plugin + + false + + + + + + + io.swagger + swagger-jaxrs + compile + ${swagger-core-version} + + + javax.ws.rs + jsr311-api + + + + + ch.qos.logback + logback-classic +{{^generateSpringBootApplication}} + ${logback-version} +{{/generateSpringBootApplication}} + compile + + + ch.qos.logback + logback-core +{{^generateSpringBootApplication}} + ${logback-version} +{{/generateSpringBootApplication}} + compile + + + junit + junit +{{^generateSpringBootApplication}} + ${junit-version} +{{/generateSpringBootApplication}} + test + +{{#useBeanValidation}} + + + javax.validation + validation-api +{{^generateSpringBootApplication}} + ${beanvalidation-version} +{{/generateSpringBootApplication}} + provided + +{{/useBeanValidation}} + + + org.apache.cxf + cxf-rt-rs-client + ${cxf-version} + test + + + + org.apache.cxf + cxf-rt-frontend-jaxrs + ${cxf-version} + compile + + + org.apache.cxf + cxf-rt-rs-service-description + ${cxf-version} + compile + + + org.apache.cxf + cxf-rt-rs-service-description-swagger + ${cxf-version} + compile + + + org.apache.cxf + cxf-rt-ws-policy + ${cxf-version} + compile + + + org.apache.cxf + cxf-rt-wsdl + ${cxf-version} + compile + + + + com.fasterxml.jackson.jaxrs + jackson-jaxrs-json-provider +{{^generateSpringBootApplication}} + ${jackson-jaxrs-version} +{{/generateSpringBootApplication}} + compile + + + com.fasterxml.jackson.jaxrs + jackson-jaxrs-xml-provider +{{^generateSpringBootApplication}} + ${jackson-jaxrs-version} +{{/generateSpringBootApplication}} + compile + +{{#java8}} + + com.fasterxml.jackson.datatype + jackson-datatype-jsr310 +{{^generateSpringBootApplication}} + ${jackson-jaxrs-version} +{{/generateSpringBootApplication}} + +{{/java8}} +{{^java8}} + + com.fasterxml.jackson.datatype + jackson-datatype-joda +{{^generateSpringBootApplication}} + ${jackson-jaxrs-version} +{{/generateSpringBootApplication}} + +{{/java8}} +{{#generateSpringApplication}} + + + org.springframework + spring-core +{{^generateSpringBootApplication}} + ${spring-version} +{{/generateSpringBootApplication}} + + + org.springframework + spring-aop +{{^generateSpringBootApplication}} + ${spring-version} +{{/generateSpringBootApplication}} + + + org.springframework + spring-context +{{^generateSpringBootApplication}} + ${spring-version} +{{/generateSpringBootApplication}} + + + org.springframework + spring-web +{{^generateSpringBootApplication}} + ${spring-version} +{{/generateSpringBootApplication}} + +{{/generateSpringApplication}} +{{#generateSpringBootApplication}} + + + + org.springframework.boot + spring-boot + + + org.springframework.boot + spring-boot-autoconfigure + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-test + test + + + org.apache.cxf + cxf-spring-boot-starter-jaxrs + ${cxf-version} + provided + +{{/generateSpringBootApplication}} +{{#useSwaggerUI}} + + org.webjars + swagger-ui + 3.6.1 + +{{/useSwaggerUI}} +{{#generateOperationBody}} +{{#loadTestDataFromFile}} + + org.openapitools + openapi-generator + {{{generatorVersion}}} + +{{/loadTestDataFromFile}} +{{/generateOperationBody}} + + + + sonatype-snapshots + https://oss.sonatype.org/content/repositories/snapshots + + true + + + + sonatype-releases + https://oss.sonatype.org/content/repositories/releases + + false + + + + + {{#supportJava6}}1.6{{/supportJava6}}{{^supportJava6}}{{^java8}}1.7{{/java8}}{{#java8}}1.8{{/java8}}{{/supportJava6}} + ${java.version} + ${java.version} + 1.5.18 + 9.2.9.v20150224 +{{#useBeanValidation}} + 1.1.0.Final +{{/useBeanValidation}} +{{#generateSpringApplication}} + {{^generateSpringBootApplication}} + 5.0.8.RELEASE + {{/generateSpringBootApplication}} +{{/generateSpringApplication}} +{{^generateSpringBootApplication}} + 4.12 + 1.1.7 +{{/generateSpringBootApplication}} + 3.3.0 + 2.9.8 + UTF-8 + + diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/server/readme.md b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/server/readme.md new file mode 100644 index 00000000000..fdd92b91bf1 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/server/readme.md @@ -0,0 +1,33 @@ +# JAX-RS CXF 3 server application + +## Supported features +* Bean-Validation-API support +* Spring-configuration of Swagger, WADL and Endpoints +* Swagger-API is accessible (CXF3 Swagger2Feature) +* Swagger-UI can be included as Web-Jar automatically +* WADL is accessible (CXF WADL-Generator) +* Unit-tests include Gzip-Interceptors for demonstration +* Options for generating a functional mock server returning static responses + +## URLs to access the REST API +### URLs for Spring Boot + +* Available services listing + http://localhost:8080/ + +* OpenAPI + http://localhost:8080/services/openapi.json + +* CXF WADL + http://localhost:8080/services?_wadl + + +### URLs if deployed to an Application Server +* Available services listing + http://localhost:8080/swagger-cxf-server/rest/services/ + +* OpenAPI + http://localhost:8080/swagger-cxf-server/rest/services/swagger.json + +* CXF WADL + http://localhost:8080/swagger-cxf-server/rest/services?_wadl diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/server/web.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/server/web.mustache new file mode 100644 index 00000000000..9d905ae076b --- /dev/null +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/server/web.mustache @@ -0,0 +1,23 @@ + + + + + contextConfigLocation + WEB-INF/context.xml + + + org.springframework.web.context.ContextLoaderListener + + + CXF Service Servlet + CXFServiceServlet + org.apache.cxf.transport.servlet.CXFServlet + 1 + + + CXFServiceServlet + /rest/* + + + diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/testData.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/testData.mustache new file mode 100644 index 00000000000..ae8e4320a19 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/testData.mustache @@ -0,0 +1 @@ +{{{test-data.json}}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/testDataControl.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/testDataControl.mustache new file mode 100644 index 00000000000..acb07e74a8a --- /dev/null +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/testDataControl.mustache @@ -0,0 +1 @@ +{{{test-data-control.json}}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/META-INF/services/org.openapitools.codegen.CodegenConfig b/modules/openapi-generator/src/main/resources/META-INF/services/org.openapitools.codegen.CodegenConfig index c5e74173631..4632160959c 100644 --- a/modules/openapi-generator/src/main/resources/META-INF/services/org.openapitools.codegen.CodegenConfig +++ b/modules/openapi-generator/src/main/resources/META-INF/services/org.openapitools.codegen.CodegenConfig @@ -48,6 +48,7 @@ org.openapitools.codegen.languages.JavaPlayFrameworkCodegen org.openapitools.codegen.languages.JavaUndertowServerCodegen org.openapitools.codegen.languages.JavaVertXServerCodegen org.openapitools.codegen.languages.JavaCXFServerCodegen +org.openapitools.codegen.languages.JavaCXFExtServerCodegen org.openapitools.codegen.languages.JavaJAXRSCXFCDIServerCodegen org.openapitools.codegen.languages.JavaJerseyServerCodegen org.openapitools.codegen.languages.JavaResteasyServerCodegen diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/jaxrs/JavaJAXRSCXFExtServerCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/jaxrs/JavaJAXRSCXFExtServerCodegenTest.java new file mode 100644 index 00000000000..fb6d42c5479 --- /dev/null +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/jaxrs/JavaJAXRSCXFExtServerCodegenTest.java @@ -0,0 +1,837 @@ +package org.openapitools.codegen.java.jaxrs; + +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertNull; +import static org.testng.Assert.assertTrue; + +import java.io.File; +import java.nio.file.Files; +import java.util.List; +import java.util.Map; +import java.util.regex.Pattern; + +import org.openapitools.codegen.ClientOptInput; +import org.openapitools.codegen.ClientOpts; +import org.openapitools.codegen.CodegenConstants; +import org.openapitools.codegen.CodegenOperation; +import org.openapitools.codegen.MockDefaultGenerator; +import org.openapitools.codegen.MockDefaultGenerator.WrittenTemplateBasedFile; +import org.openapitools.codegen.TestUtils; +import org.openapitools.codegen.languages.AbstractJavaCodegen; +import org.openapitools.codegen.languages.AbstractJavaJAXRSServerCodegen; +import org.openapitools.codegen.languages.JavaCXFExtServerCodegen; +import org.openapitools.codegen.languages.features.BeanValidationExtendedFeatures; +import org.openapitools.codegen.languages.features.BeanValidationFeatures; +import org.openapitools.codegen.languages.features.CXFExtServerFeatures; +import org.openapitools.codegen.languages.features.CXFServerFeatures; +import org.openapitools.codegen.languages.features.GzipFeatures; +import org.openapitools.codegen.languages.features.GzipTestFeatures; +import org.openapitools.codegen.languages.features.JbossFeature; +import org.openapitools.codegen.languages.features.LoggingFeatures; +import org.openapitools.codegen.languages.features.LoggingTestFeatures; +import org.openapitools.codegen.languages.features.SpringFeatures; +import org.openapitools.codegen.languages.features.SwaggerFeatures; +import org.openapitools.codegen.languages.features.SwaggerUIFeatures; +import org.openapitools.codegen.languages.features.UseGenericResponseFeatures; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import io.swagger.parser.OpenAPIParser; +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.servers.Server; +import io.swagger.v3.parser.core.models.ParseOptions; + +public class JavaJAXRSCXFExtServerCodegenTest { + @SuppressWarnings("unused") + private static class JavaCXFExtServerCodegenTester extends JavaCXFExtServerCodegen { + /* Options processed by DefaultCodegen */ + + // CodegenConstants.ALLOW_UNICODE_IDENTIFIERS + public Boolean getAllowUnicodeIdentifiers() { + return allowUnicodeIdentifiers; + } + + // CodegenConstants.API_PACKAGE + public String getApiPackage() { + return apiPackage; + } + + // CodegenConstants.DOCEXTENSION +// String getDocExtension(); + + // CodegenConstants.ARTIFACT_DESCRIPTION + public String getArtifactDescription() { + return artifactDescription; + } + + // CodegenConstants.ARTIFACT_ID + public String getArtifactId() { + return artifactId; + } + + // CodegenConstants.ARTIFACT_URL + public String getArtifactUrl() { + return artifactUrl; + } + + // CodegenConstants.ARTIFACT_VERSION + public String getArtifactVersion() { + return artifactVersion; + } + + // AbstractJavaCodegen.BOOLEAN_GETTER_PREFIX + public String getBooleanGetterPrefix() { + return booleanGetterPrefix; + } + + // AbstractJavaCodegen.DATE_LIBRARY + public String getDateLibrary() { + return dateLibrary; + } + + // CodegenConstants.DEVELOPER_EMAIL + public String getDeveloperEmail() { + return developerEmail; + } + + // CodegenConstants.DEVELOPER_NAME + public String getDeveloperName() { + return developerName; + } + + // CodegenConstants.DEVELOPER_ORGANIZATION + public String getDeveloperOrganization() { + return developerOrganization; + } + + // CodegenConstants.DEVELOPER_ORGANIZATION_URL + public String getDeveloperOrganizationUrl() { + return developerOrganizationUrl; + } + + /* Options processed by AbstractJavaCodegen */ + + // CodegenConstants.ENSURE_UNIQUE_PARAMS + public Boolean getEnsureUniqueParams() { + return ensureUniqueParams; + } + + // CodegenConstants.GROUP_ID + public String getGroupId() { + return groupId; + } + + // CodegenConstants.HIDE_GENERATION_TIMESTAMP + public Boolean getHideGenerationTimestamp() { + return hideGenerationTimestamp; + } + + // CodegenConstants.IMPL_FOLDER + public String getImplFolder() { + return implFolder; + } + + // CodegenConstants.INVOKER_PACKAGE + public String getInvokerPackage() { + return invokerPackage; + } + + // CodegenConstants.LICENSE_NAME + public String getLicenseName() { + return licenseName; + } + + // CodegenConstants.LICENSE_URL + public String getLicenseUrl() { + return licenseUrl; + } + + // CodegenConstants.LOCAL_VARIABLE_PREFIX + public String getLocalVariablePrefix() { + return localVariablePrefix; + } + + // CodegenConstants.MODEL_NAME_PREFIX + public String getModelNamePrefix() { + return modelNamePrefix; + } + + // CodegenConstants.MODEL_NAME_SUFFIX + public String getModelNameSuffix() { + return modelNameSuffix; + } + + // CodegenConstants.MODEL_PACKAGE + public String getModelPackage() { + return modelPackage; + } + + // CodegenConstants.PREPEND_FORM_OR_BODY_PARAMETERS + public Boolean getPrependFormOrBodyParameters() { + return prependFormOrBodyParameters; + } + + // CodegenConstants.REMOVE_OPERATION_ID_PREFIX + boolean getRemoveOperationIdPrefix() { + return removeOperationIdPrefix; + } + + // CodegenConstants.SCM_CONNECTION + public String getScmConnection() { + return scmConnection; + } + + // CodegenConstants.SCM_DEVELOPER_CONNECTION + public String getScmDeveloperConnection() { + return scmDeveloperConnection; + } + + // CodegenConstants.SCM_URL + public String getScmUrl() { + return scmUrl; + } + + // CodegenConstants.SERIALIZABLE_MODEL + public Boolean getSerializableModel() { + return serializableModel; + } + + // CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG + public Boolean getSortParamsByRequiredFlag() { + return sortParamsByRequiredFlag; + } + + // CodegenConstants.SOURCE_FOLDER + public String getSourceFolder() { + return sourceFolder; + } + + // AbstractJavaCodegen.BOOLEAN_GETTER_PREFIX_DEFAULT (UNUSED) + + // CodegenConstants.TEMPLATE_DIR + public String getTemplateDir() { + return templateDir; + } + + // AbstractJavaCodegen.DEFAULT_LIBRARY (UNUSED) + + // CXFServerFeatures.TEST_DATA_CONTROL_FILE + public File getTestDataControlFile() { + return testDataControlFile; + } + + // CXFServerFeatures.ADD_CONSUMES_PRODUCES_JSON + public boolean isAddConsumesProducesJson() { + return addConsumesProducesJson; + } + + // AbstractJavaCodegen.DISABLE_HTML_ESCAPING + public boolean isDisableHtmlEscaping() { + return disableHtmlEscaping; + } + + // AbstractJavaCodegen.FULL_JAVA_UTIL + public boolean isFullJavaUtil() { + return fullJavaUtil; + } + + // JbossFeature.GENERATE_JBOSS_DEPLOYMENT_DESCRIPTOR + public boolean isGenerateJbossDeploymentDescriptor() { + return generateJbossDeploymentDescriptor; + } + + // CXFServerFeatures.GENERATE_NON_SPRING_APPLICATION + public boolean isGenerateNonSpringApplication() { + return generateNonSpringApplication; + } + + /* Options processed by AbstractJavaJAXRSServerCodegen */ + + // SpringFeatures.GENERATE_SPRING_APPLICATION + public boolean isGenerateSpringApplication() { + return generateSpringApplication; + } + + // AbstractJavaJAXRSServerCodegen.SERVER_PORT (no corresponding field) + + /* Options processed by JavaCXFServerCodegen */ + + // SpringFeatures.GENERATE_SPRING_BOOT_APPLICATION + public boolean isGenerateSpringBootApplication() { + return generateSpringBootApplication; + } + + // AbstractJavaCodegen.JAVA8_MODE + public boolean isJava8Mode() { + return java8Mode; + } + + // CodegenConstants.SERIALIZE_BIG_DECIMAL_AS_STRING + public boolean isSerializeBigDecimalAsString() { + return serializeBigDecimalAsString; + } + + // AbstractJavaCodegen.SUPPORT_ASYNC + public boolean isSupportAsync() { + return supportAsync; + } + + // AbstractJavaCodegen.SUPPORT_JAVA6 + public boolean isSupportJava6() { + return supportJava6; + } + + // CXFServerFeatures.USE_ANNOTATED_BASE_PATH + public boolean isUseAnnotatedBasePath() { + return useAnnotatedBasePath; + } + + // BeanValidationFeatures.USE_BEANVALIDATION + public boolean isUseBeanValidation() { + return useBeanValidation; + } + + // BeanValidationExtendedFeatures.USE_BEANVALIDATION_FEATURE + public boolean isUseBeanValidationFeature() { + return useBeanValidationFeature; + } + + // UseGenericResponseFeatures.USE_GENERIC_RESPONSE + public boolean isUseGenericResponse() { + return useGenericResponse; + } + + // GzipFeatures.USE_GZIP_FEATURE + public boolean isUseGzipFeature() { + return useGzipFeature; + } + + // GzipTestFeatures.USE_GZIP_FEATURE_FOR_TESTS + public boolean isUseGzipFeatureForTests() { + return useGzipFeatureForTests; + } + + // LoggingFeatures.USE_LOGGING_FEATURE + public boolean isUseLoggingFeature() { + return useLoggingFeature; + } + + // LoggingTestFeatures.USE_LOGGING_FEATURE_FOR_TESTS + public boolean isUseLoggingFeatureForTests() { + return useLoggingFeatureForTests; + } + + // CXFServerFeatures.USE_MULTIPART_FEATURE + public boolean isUseMultipartFeature() { + return useMultipartFeature; + } + + // AbstractJavaCodegen.USE_NULL_FOR_UNKNOWN_ENUM_VALUE + public boolean isUseNullForUnknownEnumValue() { + return useNullForUnknownEnumValue; + } + + // SpringFeatures.USE_SPRING_ANNOTATION_CONFIG + public boolean isUseSpringAnnotationConfig() { + return useSpringAnnotationConfig; + } + + // SwaggerFeatures.USE_SWAGGER_FEATURE + public boolean isUseSwaggerFeature() { + return useSwaggerFeature; + } + + // SwaggerUIFeatures.USE_SWAGGER_UI + public boolean isUseSwaggerUI() { + return useSwaggerUI; + } + + // CXFServerFeatures.USE_WADL_FEATURE + public boolean isUseWadlFeature() { + return useWadlFeature; + } + + // AbstractJavaCodegen.WITH_XML + public boolean isWithXml() { + return withXml; + } + + /* Options processed by JavaCXFExtServerCodegen */ + + // CXFExtServerFeatures.GENERATE_OPERATION_BODY + public boolean isGenerateOperationBody() { + return generateOperationBody; + } + + // CXFExtServerFeatures.TEST_DATA_FILE + public File getTestDataFile() { + return testDataFile; + } + + // CXFExtServerFeatures.LOAD_TEST_DATA_FROM_FILE + public boolean isLoadTestDataFromFile() { + return loadTestDataFromFile; + } + + // CXFExtServerFeatures.SUPPORT_MULTIPLE_SPRING_SERVICES + public boolean isSupportMultipleSpringServices() { + return supportMultipleSpringServices; + } + } + + private JavaCXFExtServerCodegenTester codegen; + + @BeforeMethod + public void beforeMethod() { + codegen = new JavaCXFExtServerCodegenTester(); + } + + private void checkFile(MockDefaultGenerator generator, String path, boolean fileShouldExist, String... regexes) { + String file = generator.getFiles().get(path); + if (fileShouldExist) + assertNotNull(file); + else + assertNull(file); + for (String regex : regexes) + assertTrue(Pattern.compile(regex).matcher(file).find()); + } + + @SuppressWarnings("unchecked") + private List getOperationsList(Map templateData) { + assertTrue(templateData.get("operations") instanceof Map); + Map operations = (Map) templateData.get("operations"); + assertTrue(operations.get("operation") instanceof List); + return (List) operations.get("operation"); + } + + @Test + public void testAdditionalPropertiesPutForConfigValues() throws Exception { + Map additionalProperties = codegen.additionalProperties(); + + // Options processed by DefaultCodegen + additionalProperties.put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, "true"); + additionalProperties.put(CodegenConstants.API_PACKAGE, "xyz.yyyyy.aaaaa.api"); + additionalProperties.put(CodegenConstants.DOCEXTENSION, "doc"); + additionalProperties.put(CodegenConstants.ENSURE_UNIQUE_PARAMS, "true"); + additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "true"); + additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, "xyz.yyyyy.iiii.invoker"); + additionalProperties.put(CodegenConstants.MODEL_NAME_PREFIX, "MyPrefix"); + additionalProperties.put(CodegenConstants.MODEL_NAME_SUFFIX, "MySuffix"); + additionalProperties.put(CodegenConstants.MODEL_PACKAGE, "xyz.yyyyy.mmmmm.model"); + additionalProperties.put(CodegenConstants.PREPEND_FORM_OR_BODY_PARAMETERS, "true"); + additionalProperties.put(CodegenConstants.REMOVE_OPERATION_ID_PREFIX, "true"); + additionalProperties.put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, "true"); + additionalProperties.put(CodegenConstants.TEMPLATE_DIR, "MyTemplates"); + // Options processed by AbstractJavaCodegen + additionalProperties.put(CodegenConstants.ARTIFACT_DESCRIPTION, "My description"); + additionalProperties.put(CodegenConstants.ARTIFACT_ID, "my-artifact"); + additionalProperties.put(CodegenConstants.ARTIFACT_VERSION, "9.9.9"); + additionalProperties.put(CodegenConstants.ARTIFACT_URL, "http://organisation.org/group/artifact"); + additionalProperties.put(CodegenConstants.DEVELOPER_EMAIL, "dchappie@organisation.org"); + additionalProperties.put(CodegenConstants.DEVELOPER_NAME, "Developer Chappie"); + additionalProperties.put(CodegenConstants.DEVELOPER_ORGANIZATION, "My Organisation"); + additionalProperties.put(CodegenConstants.DEVELOPER_ORGANIZATION_URL, "http://www.organisation.org/"); + additionalProperties.put(CodegenConstants.GROUP_ID, "org.organisation.group.id"); + additionalProperties.put(CodegenConstants.LICENSE_NAME, "Apache 2.0"); + additionalProperties.put(CodegenConstants.LICENSE_URL, "https://www.apache.org/licenses/LICENSE-2.0"); + additionalProperties.put(CodegenConstants.SCM_CONNECTION, "http://svn.organisation.org/group/"); + additionalProperties.put(CodegenConstants.SCM_DEVELOPER_CONNECTION, "http://svn.organisation.org/dev/group/"); + additionalProperties.put(CodegenConstants.SCM_URL, "http://svn.organisation.org/group/"); + additionalProperties.put(CodegenConstants.SERIALIZE_BIG_DECIMAL_AS_STRING, "true"); + additionalProperties.put(CodegenConstants.SERIALIZABLE_MODEL, "true"); + additionalProperties.put(CodegenConstants.SOURCE_FOLDER, "src/main/java"); + additionalProperties.put(AbstractJavaCodegen.BOOLEAN_GETTER_PREFIX, "isIt"); + additionalProperties.put(AbstractJavaCodegen.DATE_LIBRARY, "MyDateLibrary"); + additionalProperties.put(AbstractJavaCodegen.DISABLE_HTML_ESCAPING, "true"); + additionalProperties.put(AbstractJavaCodegen.FULL_JAVA_UTIL, "true"); + additionalProperties.put(AbstractJavaCodegen.JAVA8_MODE, "true"); + additionalProperties.put(AbstractJavaCodegen.SUPPORT_ASYNC, "true"); + additionalProperties.put(AbstractJavaCodegen.SUPPORT_JAVA6, "false"); + additionalProperties.put(AbstractJavaCodegen.USE_NULL_FOR_UNKNOWN_ENUM_VALUE, "true"); + additionalProperties.put(AbstractJavaCodegen.WITH_XML, "true"); + // Options processed by AbstractJavaJAXRSServerCodegen + additionalProperties.put(CodegenConstants.IMPL_FOLDER, "myimpl"); + additionalProperties.put(BeanValidationFeatures.USE_BEANVALIDATION, "true"); + additionalProperties.put(AbstractJavaJAXRSServerCodegen.SERVER_PORT, "8088"); + // Options processed by JavaCXFServerCodegen + additionalProperties.put(BeanValidationExtendedFeatures.USE_BEANVALIDATION_FEATURE, Boolean.TRUE); + additionalProperties.put(GzipFeatures.USE_GZIP_FEATURE, Boolean.TRUE); + additionalProperties.put(GzipTestFeatures.USE_GZIP_FEATURE_FOR_TESTS, "true"); + additionalProperties.put(JbossFeature.GENERATE_JBOSS_DEPLOYMENT_DESCRIPTOR, Boolean.TRUE); + additionalProperties.put(LoggingFeatures.USE_LOGGING_FEATURE, Boolean.TRUE); + additionalProperties.put(LoggingTestFeatures.USE_LOGGING_FEATURE_FOR_TESTS, "true"); + additionalProperties.put(SpringFeatures.GENERATE_SPRING_APPLICATION, Boolean.TRUE); + additionalProperties.put(SpringFeatures.GENERATE_SPRING_BOOT_APPLICATION, Boolean.TRUE); + additionalProperties.put(SpringFeatures.USE_SPRING_ANNOTATION_CONFIG, Boolean.TRUE); + additionalProperties.put(SwaggerFeatures.USE_SWAGGER_FEATURE, Boolean.TRUE); + additionalProperties.put(SwaggerUIFeatures.USE_SWAGGER_UI, Boolean.TRUE); + additionalProperties.put(UseGenericResponseFeatures.USE_GENERIC_RESPONSE, "true"); + additionalProperties.put(CXFServerFeatures.ADD_CONSUMES_PRODUCES_JSON, Boolean.TRUE); + additionalProperties.put(CXFServerFeatures.GENERATE_NON_SPRING_APPLICATION, Boolean.FALSE); + additionalProperties.put(CXFServerFeatures.LOAD_TEST_DATA_FROM_FILE, Boolean.TRUE); + additionalProperties.put(CXFServerFeatures.USE_ANNOTATED_BASE_PATH, Boolean.TRUE); + additionalProperties.put(CXFServerFeatures.USE_MULTIPART_FEATURE, Boolean.TRUE); + additionalProperties.put(CXFServerFeatures.USE_WADL_FEATURE, Boolean.TRUE); + // Options processed by JavaCXFExtServerCodegen + additionalProperties.put(CXFExtServerFeatures.GENERATE_OPERATION_BODY, Boolean.TRUE); + additionalProperties.put(CXFExtServerFeatures.SUPPORT_MULTIPLE_SPRING_SERVICES, Boolean.TRUE); + additionalProperties.put(CXFExtServerFeatures.TEST_DATA_FILE, "my/test-data.json"); + additionalProperties.put(CXFExtServerFeatures.TEST_DATA_CONTROL_FILE, "my/test-data-control.json"); + + codegen.processOpts(); + + OpenAPI openAPI = new OpenAPI(); + openAPI.addServersItem(new Server().url("https://api.abcde.xy:8082/v2")); + codegen.preprocessOpenAPI(openAPI); + + // Options processed by DefaultCodegen + assertEquals(codegen.getAllowUnicodeIdentifiers(), Boolean.TRUE); + assertEquals(codegen.apiPackage(), "xyz.yyyyy.aaaaa.api"); + assertEquals(codegen.getDocExtension(), "doc"); + assertEquals(codegen.getEnsureUniqueParams(), Boolean.TRUE); + assertEquals(codegen.isHideGenerationTimestamp(), true); + assertEquals(codegen.getInvokerPackage(), "xyz.yyyyy.iiii.invoker"); + assertEquals(codegen.getModelNamePrefix(), "MyPrefix"); + assertEquals(codegen.getModelNameSuffix(), "MySuffix"); + assertEquals(codegen.getModelPackage(), "xyz.yyyyy.mmmmm.model"); + assertEquals(codegen.getPrependFormOrBodyParameters(), Boolean.TRUE); + assertEquals(codegen.getRemoveOperationIdPrefix(), true); + assertEquals(codegen.getSortParamsByRequiredFlag(), Boolean.TRUE); + assertEquals(codegen.getTemplateDir(), "MyTemplates"); + assertEquals(codegen.getArtifactDescription(), "My description"); + // Options processed by AbstractJavaCodegen + assertEquals(codegen.getArtifactId(), "my-artifact"); + assertEquals(codegen.getArtifactVersion(), "9.9.9"); + assertEquals(codegen.getArtifactUrl(), "http://organisation.org/group/artifact"); + assertEquals(codegen.getDeveloperEmail(), "dchappie@organisation.org"); + assertEquals(codegen.getDeveloperName(), "Developer Chappie"); + assertEquals(codegen.getDeveloperOrganization(), "My Organisation"); + assertEquals(codegen.getDeveloperOrganizationUrl(), "http://www.organisation.org/"); + assertEquals(codegen.getGroupId(), "org.organisation.group.id"); + assertEquals(codegen.getLicenseName(), "Apache 2.0"); + assertEquals(codegen.getLicenseUrl(), "https://www.apache.org/licenses/LICENSE-2.0"); + assertEquals(codegen.getScmConnection(), "http://svn.organisation.org/group/"); + assertEquals(codegen.getScmDeveloperConnection(), "http://svn.organisation.org/dev/group/"); + assertEquals(codegen.getScmUrl(), "http://svn.organisation.org/group/"); + assertEquals(codegen.isSerializeBigDecimalAsString(), true); + assertEquals(codegen.getSerializableModel(), Boolean.TRUE); + assertEquals(codegen.getSourceFolder(), "src/main/java"); + assertEquals(codegen.getBooleanGetterPrefix(), "isIt"); + assertEquals(codegen.getDateLibrary(), "MyDateLibrary"); + assertEquals(codegen.isDisableHtmlEscaping(), true); + assertEquals(codegen.isFullJavaUtil(), true); + assertEquals(codegen.isJava8Mode(), true); + assertEquals(codegen.isSupportAsync(), true); + assertEquals(codegen.isUseNullForUnknownEnumValue(), true); + assertEquals(codegen.isWithXml(), true); + // Options processed by AbstractJavaJAXRSServerCodegen + assertEquals(codegen.getImplFolder(), "myimpl"); + assertEquals(codegen.isUseBeanValidation(), true); +// assertEquals(codegen.getServerPort(), 8088); + // Options processed by JavaCXFServerCodegen + File curdir = new File(System.getProperty("user.dir")); + assertEquals(codegen.isUseBeanValidationFeature(), true); + assertEquals(codegen.isUseGzipFeature(), true); + assertEquals(codegen.isUseGzipFeatureForTests(), true); + assertEquals(codegen.isGenerateJbossDeploymentDescriptor(), true); + assertEquals(codegen.isUseLoggingFeature(), true); + assertEquals(codegen.isUseLoggingFeatureForTests(), true); + assertEquals(codegen.isGenerateSpringApplication(), true); + assertEquals(codegen.isGenerateSpringBootApplication(), true); + assertEquals(codegen.isUseSpringAnnotationConfig(), true); + assertEquals(codegen.isUseSwaggerFeature(), true); + assertEquals(codegen.isUseSwaggerUI(), true); + assertEquals(codegen.isUseGenericResponse(), true); + assertEquals(codegen.isAddConsumesProducesJson(), true); + assertEquals(codegen.isGenerateNonSpringApplication(), false); + assertEquals(codegen.isUseAnnotatedBasePath(), true); + assertEquals(codegen.isUseMultipartFeature(), true); + assertEquals(codegen.isUseWadlFeature(), true); + // Options processed by JavaCXFExtServerCodegen + assertEquals(codegen.isGenerateOperationBody(), true); + assertEquals(codegen.isLoadTestDataFromFile(), true); + assertEquals(codegen.isSupportMultipleSpringServices(), true); + assertEquals(codegen.getTestDataFile(), new File(curdir, "my/test-data.json")); + assertEquals(codegen.getTestDataControlFile(), new File(curdir, "my/test-data-control.json")); + } + + @Test + public void testAddOperationToGroup() throws Exception { + File output = Files.createTempDirectory("test").toFile(); + output.deleteOnExit(); + + OpenAPI openAPI = new OpenAPIParser().readLocation("src/test/resources/3_0/tags.yaml", null, new ParseOptions()) + .getOpenAPI(); + codegen.setOutputDir(output.getAbsolutePath()); + + ClientOpts opts = new ClientOpts(); + ClientOptInput input = new ClientOptInput(); + input.setOpenAPI(openAPI); + input.setConfig(codegen); + input.setOpts(opts); + + MockDefaultGenerator generator = new MockDefaultGenerator(); + generator.opts(input).generate(); + + WrittenTemplateBasedFile tag1File = TestUtils.getTemplateBasedFile(generator, output, + "src/gen/java/org/openapitools/api/Tag1Api.java"); + assertEquals(tag1File.getTemplateData().get("baseName"), "Tag1"); + assertEquals(tag1File.getTemplateData().get("commonPath"), "Tag1"); + List tag1List = getOperationsList(tag1File.getTemplateData()); + assertEquals(tag1List.size(), 1); + assertEquals(tag1List.get(0).path, "/group1/op1"); + assertEquals(tag1List.get(0).baseName, "Tag1"); + assertEquals(tag1List.get(0).subresourceOperation, true); + + WrittenTemplateBasedFile tag2File = TestUtils.getTemplateBasedFile(generator, output, + "src/gen/java/org/openapitools/api/Tag2Api.java"); + assertEquals(tag2File.getTemplateData().get("baseName"), "Tag2"); + assertEquals(tag2File.getTemplateData().get("commonPath"), "Tag2"); + List tag2List = getOperationsList(tag2File.getTemplateData()); + assertEquals(tag2List.size(), 2); + assertEquals(tag2List.get(0).path, "/group1/op2"); + assertEquals(tag2List.get(0).baseName, "Tag2"); + assertEquals(tag2List.get(0).subresourceOperation, true); + assertEquals(tag2List.get(1).path, "/group2/op3"); + assertEquals(tag2List.get(1).baseName, "Tag2"); + assertEquals(tag2List.get(1).subresourceOperation, true); + + WrittenTemplateBasedFile defaultFile = TestUtils.getTemplateBasedFile(generator, output, + "src/gen/java/org/openapitools/api/DefaultApi.java"); + assertEquals(defaultFile.getTemplateData().get("baseName"), "Default"); + assertEquals(defaultFile.getTemplateData().get("commonPath"), "Default"); + List defaultList = getOperationsList(defaultFile.getTemplateData()); + assertEquals(defaultList.size(), 1); + assertEquals(defaultList.get(0).path, "/group3/op4"); + assertEquals(defaultList.get(0).baseName, "Default"); + assertEquals(defaultList.get(0).subresourceOperation, true); + + WrittenTemplateBasedFile group4File = TestUtils.getTemplateBasedFile(generator, output, + "src/gen/java/org/openapitools/api/Group4Api.java"); + assertEquals(group4File.getTemplateData().get("baseName"), "Group4"); + assertEquals(group4File.getTemplateData().get("commonPath"), "Group4"); + List group4List = getOperationsList(group4File.getTemplateData()); + assertEquals(group4List.size(), 2); + assertEquals(group4List.get(0).path, "/group4/op5"); + assertEquals(group4List.get(0).baseName, "Group4"); + assertEquals(group4List.get(0).subresourceOperation, true); + assertEquals(group4List.get(1).path, "/group4/op6"); + assertEquals(group4List.get(1).baseName, "Group4"); + assertEquals(group4List.get(1).subresourceOperation, true); + + WrittenTemplateBasedFile group5File = TestUtils.getTemplateBasedFile(generator, output, + "src/gen/java/org/openapitools/api/Group5Api.java"); + assertEquals(group5File.getTemplateData().get("baseName"), "Group5"); + assertEquals(group5File.getTemplateData().get("commonPath"), "Group5"); + List group5List = getOperationsList(group5File.getTemplateData()); + assertEquals(group5List.size(), 2); + assertEquals(group5List.get(0).path, "/group5/op7"); + assertEquals(group5List.get(0).baseName, "Group5"); + assertEquals(group5List.get(0).subresourceOperation, true); + assertEquals(group5List.get(1).path, "/group6/op8"); + assertEquals(group5List.get(1).baseName, "Group5"); + assertEquals(group5List.get(1).subresourceOperation, true); + } + + @Test + public void testGenerateOperationBodyWithCodedTestData() throws Exception { + File output = Files.createTempDirectory("test").toFile(); + output.deleteOnExit(); + String outputPath = output.getCanonicalPath().replace('\\', '/'); + + OpenAPI openAPI = new OpenAPIParser() + .readLocation("src/test/resources/3_0/petstore.yaml", null, new ParseOptions()).getOpenAPI(); + codegen.setOutputDir(output.getAbsolutePath()); + + ClientOpts opts = new ClientOpts(); + opts.getProperties().put(CXFExtServerFeatures.GENERATE_OPERATION_BODY, "true"); + + ClientOptInput input = new ClientOptInput(); + input.setOpenAPI(openAPI); + input.setConfig(codegen); + input.setOpts(opts); + + MockDefaultGenerator generator = new MockDefaultGenerator(); + generator.opts(input).generate(); + + String reGetPetById = "(?s)(?m)public Pet getPetById\\(Long petId\\) \\{" // split + + ".*" // split + + "Pet response = new Pet\\(\\);" // split + + ".*" // split + + "return response;\\s+" // split + + "\\}"; // split + checkFile(generator, outputPath + "/src/main/java/org/openapitools/api/impl/PetApiServiceImpl.java", true, + reGetPetById); + + String reFindPetsByStatusTest = "(?s)(?m)public void findPetsByStatusTest\\(\\) throws Exception \\{\\s+" + + ".*" // split + + "List status = new ArrayList<>\\(\\);" // split + + ".*" // split + + "List response = api\\.findPetsByStatus\\(status\\);" // split + + ".*" // split + + "validate\\(response\\);\\s+" // split + + "\\}"; + checkFile(generator, outputPath + "/src/test/java/org/openapitools/api/PetApiTest.java", true, + reFindPetsByStatusTest); + + checkFile(generator, outputPath + "/src/main/resources/test-data.json", false); + + checkFile(generator, outputPath + "/test-data-control.json", false); + } + + @Test + public void testGenerateOperationBodyWithJsonTestData() throws Exception { + File output = Files.createTempDirectory("test").toFile(); + output.deleteOnExit(); + String outputPath = output.getCanonicalPath().replace('\\', '/'); + + OpenAPI openAPI = new OpenAPIParser() + .readLocation("src/test/resources/3_0/petstore.yaml", null, new ParseOptions()).getOpenAPI(); + codegen.setOutputDir(output.getAbsolutePath()); + + ClientOpts opts = new ClientOpts(); + opts.getProperties().put(CXFExtServerFeatures.GENERATE_OPERATION_BODY, "true"); + opts.getProperties().put(CXFServerFeatures.LOAD_TEST_DATA_FROM_FILE, "true"); + + ClientOptInput input = new ClientOptInput(); + input.setOpenAPI(openAPI); + input.setConfig(codegen); + input.setOpts(opts); + + MockDefaultGenerator generator = new MockDefaultGenerator(); + generator.opts(input).generate(); + + String reInitCache = "(?s)(?m)\\{\\s+" + "try \\{\\s+" + + "File cacheFile = new File\\(System\\.getProperty\\(\"jaxrs\\.test\\.server\\.json\",\\s+\"(.+)\"\\)\\);\\s+" + + "cache = JsonCache\\.Factory\\.instance\\.get\\(\"test-data\"\\)\\.load\\(cacheFile\\)\\.child\\(\"/org\\.openapitools\\.api/PetApi\"\\);"; + String reGetPetById = "(?s)(?m)public Pet getPetById\\(Long petId\\) \\{.*" // split + + "try \\{\\s*" // split + + "Pet response = cache\\.getObject\\(\"/getPetById/response\", Pet\\.class\\);"; + checkFile(generator, outputPath + "/src/main/java/org/openapitools/api/impl/PetApiServiceImpl.java", true, + reInitCache, reGetPetById); + + reInitCache = "(?s)(?m)public static void beforeClass\\(\\) throws Exception \\{\\s+" + + "File cacheFile = new File\\(System\\.getProperty\\(\"jaxrs\\.test\\.client\\.json\",\\s+" + + "\".*src(?:\\\\\\\\|/)main(?:\\\\\\\\|/)resources(?:\\\\\\\\|/)test-data\\.json\"\\)\\);\\s+" + + "cache = JsonCache\\.Factory\\.instance.get\\(\"test-data\"\\)\\.load\\(cacheFile\\)" + + "\\.child\\(\"/org\\.openapitools\\.api/PetApi\"\\);"; + String reAddPetTest = "public void addPetTest\\(\\) throws Exception \\{\\s+" + + "Pet pet = cache\\.getObject\\(\"/addPet/pet\", Pet\\.class\\);"; + checkFile(generator, outputPath + "/src/test/java/org/openapitools/api/PetApiTest.java", true, reInitCache, + reAddPetTest); + + checkFile(generator, outputPath + "/src/main/resources/test-data.json", true); + + checkFile(generator, outputPath + "/test-data-control.json", true); + } + + @Test + public void testInitialConfigValues() throws Exception { + codegen.processOpts(); + + OpenAPI openAPI = new OpenAPI(); + openAPI.addServersItem(new Server().url("https://api.abcde.xy:8082/v2")); + codegen.preprocessOpenAPI(openAPI); + + Map additionalProperties = codegen.additionalProperties(); + + // Options processed by DefaultCodegen + assertNull(additionalProperties.get(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS)); + assertEquals(additionalProperties.get(CodegenConstants.API_PACKAGE), "org.openapitools.api"); + assertEquals(codegen.apiPackage(), "org.openapitools.api"); + assertNull(additionalProperties.get(CodegenConstants.DOCEXTENSION)); + assertNull(additionalProperties.get(CodegenConstants.ENSURE_UNIQUE_PARAMS)); + assertEquals(additionalProperties.get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.FALSE); + assertEquals(codegen.isHideGenerationTimestamp(), false); + assertEquals(additionalProperties.get(CodegenConstants.INVOKER_PACKAGE), "org.openapitools.api"); + assertEquals(codegen.getInvokerPackage(), "org.openapitools.api"); + assertNull(additionalProperties.get(CodegenConstants.MODEL_NAME_PREFIX)); + assertNull(additionalProperties.get(CodegenConstants.MODEL_NAME_SUFFIX)); + assertEquals(additionalProperties.get(CodegenConstants.MODEL_PACKAGE), "org.openapitools.model"); + assertEquals(codegen.modelPackage(), "org.openapitools.model"); + assertNull(additionalProperties.get(CodegenConstants.PREPEND_FORM_OR_BODY_PARAMETERS)); + assertNull(additionalProperties.get(CodegenConstants.REMOVE_OPERATION_ID_PREFIX)); + assertNull(additionalProperties.get(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG)); + assertNull(additionalProperties.get(CodegenConstants.TEMPLATE_DIR)); + // Options processed by AbstractJavaCodegen + assertEquals(additionalProperties.get(CodegenConstants.ARTIFACT_DESCRIPTION), "OpenAPI Java"); + assertEquals(additionalProperties.get(CodegenConstants.ARTIFACT_ID), "openapi-cxf-server"); + assertEquals(additionalProperties.get(CodegenConstants.ARTIFACT_VERSION), "1.0.0"); + assertEquals(additionalProperties.get(CodegenConstants.ARTIFACT_URL), + "https://github.com/openapitools/openapi-generator"); + assertEquals(additionalProperties.get(CodegenConstants.DEVELOPER_EMAIL), "team@openapitools.org"); + assertEquals(additionalProperties.get(CodegenConstants.DEVELOPER_NAME), "OpenAPI-Generator Contributors"); + assertEquals(additionalProperties.get(CodegenConstants.DEVELOPER_ORGANIZATION), "OpenAPITools.org"); + assertEquals(additionalProperties.get(CodegenConstants.DEVELOPER_ORGANIZATION_URL), "http://openapitools.org"); + assertEquals(additionalProperties.get(CodegenConstants.GROUP_ID), "org.openapitools"); + assertEquals(additionalProperties.get(CodegenConstants.LICENSE_NAME), "Unlicense"); + assertEquals(additionalProperties.get(CodegenConstants.LICENSE_URL), "http://unlicense.org"); + assertEquals(additionalProperties.get(CodegenConstants.SCM_CONNECTION), + "scm:git:git@github.com:openapitools/openapi-generator.git"); + assertEquals(additionalProperties.get(CodegenConstants.SCM_DEVELOPER_CONNECTION), + "scm:git:git@github.com:openapitools/openapi-generator.git"); + assertEquals(additionalProperties.get(CodegenConstants.SCM_URL), + "https://github.com/openapitools/openapi-generator"); + assertNull(additionalProperties.get(CodegenConstants.SERIALIZE_BIG_DECIMAL_AS_STRING)); + assertEquals(additionalProperties.get(CodegenConstants.SERIALIZABLE_MODEL), Boolean.FALSE); + assertEquals(additionalProperties.get(CodegenConstants.SOURCE_FOLDER), "src/gen/java"); + assertEquals(additionalProperties.get(AbstractJavaCodegen.BOOLEAN_GETTER_PREFIX), "get"); + assertNull(additionalProperties.get(AbstractJavaCodegen.DATE_LIBRARY)); + assertEquals(additionalProperties.get(AbstractJavaCodegen.DISABLE_HTML_ESCAPING), Boolean.FALSE); + assertEquals(additionalProperties.get(AbstractJavaCodegen.FULL_JAVA_UTIL), Boolean.FALSE); + assertNull(additionalProperties.get(AbstractJavaCodegen.JAVA8_MODE)); + assertNull(additionalProperties.get(AbstractJavaCodegen.SUPPORT_ASYNC)); + assertEquals(additionalProperties.get(AbstractJavaCodegen.SUPPORT_JAVA6), Boolean.FALSE); + assertEquals(additionalProperties.get(AbstractJavaCodegen.USE_NULL_FOR_UNKNOWN_ENUM_VALUE), false); + assertEquals(additionalProperties.get(AbstractJavaCodegen.WITH_XML), false); + // Options processed by AbstractJavaJAXRSServerCodegen + assertNull(additionalProperties.get(CodegenConstants.IMPL_FOLDER)); + assertEquals(additionalProperties.get(BeanValidationFeatures.USE_BEANVALIDATION), Boolean.TRUE); + assertEquals(additionalProperties.get(AbstractJavaJAXRSServerCodegen.SERVER_PORT), "8082"); + // Options processed by JavaCXFServerCodegen + assertNull(additionalProperties.get(BeanValidationExtendedFeatures.USE_BEANVALIDATION_FEATURE)); + assertNull(additionalProperties.get(GzipFeatures.USE_GZIP_FEATURE)); + assertNull(additionalProperties.get(GzipTestFeatures.USE_GZIP_FEATURE_FOR_TESTS)); + assertNull(additionalProperties.get(JbossFeature.GENERATE_JBOSS_DEPLOYMENT_DESCRIPTOR)); + assertNull(additionalProperties.get(LoggingFeatures.USE_LOGGING_FEATURE)); + assertNull(additionalProperties.get(LoggingTestFeatures.USE_LOGGING_FEATURE_FOR_TESTS)); + assertNull(additionalProperties.get(SpringFeatures.GENERATE_SPRING_APPLICATION)); + assertNull(additionalProperties.get(SpringFeatures.GENERATE_SPRING_BOOT_APPLICATION)); + assertNull(additionalProperties.get(SpringFeatures.USE_SPRING_ANNOTATION_CONFIG)); + assertNull(additionalProperties.get(SwaggerFeatures.USE_SWAGGER_FEATURE)); + assertNull(additionalProperties.get(SwaggerUIFeatures.USE_SWAGGER_UI)); + assertNull(additionalProperties.get(UseGenericResponseFeatures.USE_GENERIC_RESPONSE)); + assertNull(additionalProperties.get(CXFServerFeatures.ADD_CONSUMES_PRODUCES_JSON)); + assertNull(additionalProperties.get(CXFServerFeatures.GENERATE_NON_SPRING_APPLICATION)); + assertNull(additionalProperties.get(CXFExtServerFeatures.GENERATE_OPERATION_BODY)); + assertNull(additionalProperties.get(CXFServerFeatures.LOAD_TEST_DATA_FROM_FILE)); + assertNull(additionalProperties.get(CXFExtServerFeatures.SUPPORT_MULTIPLE_SPRING_SERVICES)); + assertNull(additionalProperties.get(CXFExtServerFeatures.TEST_DATA_FILE)); + assertNull(additionalProperties.get(CXFExtServerFeatures.TEST_DATA_CONTROL_FILE)); + assertNull(additionalProperties.get(CXFServerFeatures.USE_ANNOTATED_BASE_PATH)); + assertNull(additionalProperties.get(CXFServerFeatures.USE_MULTIPART_FEATURE)); + assertNull(additionalProperties.get(CXFServerFeatures.USE_WADL_FEATURE)); + } + + @Test + public void testSettersForConfigValues() throws Exception { + // It's apparent that most of these setters aren't useful to client code, only to the generator itself. The only + // reliable way to set most features is through the additional properties, since CodegenConfig.processOpts() + // overrides are typically coded to set config fields from the additional properties, not the other way round. + codegen.setHideGenerationTimestamp(false); + codegen.setModelPackage("xx.yyyyyyyy.model"); + codegen.setApiPackage("xx.yyyyyyyy.api"); + codegen.setInvokerPackage("xx.yyyyyyyy.invoker"); + codegen.processOpts(); + + Map additionalProperties = codegen.additionalProperties(); + assertEquals(additionalProperties.get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.FALSE); + assertEquals(codegen.isHideGenerationTimestamp(), false); + assertEquals(codegen.modelPackage(), "xx.yyyyyyyy.model"); + assertEquals(additionalProperties.get(CodegenConstants.MODEL_PACKAGE), "xx.yyyyyyyy.model"); + assertEquals(codegen.apiPackage(), "xx.yyyyyyyy.api"); + assertEquals(additionalProperties.get(CodegenConstants.API_PACKAGE), "xx.yyyyyyyy.api"); + assertEquals(codegen.getInvokerPackage(), "xx.yyyyyyyy.invoker"); + } +} diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/utils/JsonCacheTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/utils/JsonCacheTest.java new file mode 100644 index 00000000000..fc8adf20732 --- /dev/null +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/utils/JsonCacheTest.java @@ -0,0 +1,1350 @@ +/* + * Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openapitools.codegen.utils; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.UnsupportedEncodingException; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Arrays; +import java.util.Date; +import java.util.List; +import java.util.Locale; + +import org.junit.Before; +import org.junit.Test; +import org.openapitools.codegen.utils.JsonCache.CacheException; +import org.openapitools.codegen.utils.JsonCache.Root.MergePolicy; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.core.JsonPointer; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.JsonNodeType; +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.fasterxml.jackson.datatype.joda.JodaModule; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; +import com.fasterxml.jackson.datatype.threetenbp.ThreeTenModule; + +/** + * Tests the JsonCache class. + * + * @author aprice + */ +public class JsonCacheTest { + public static class TestObject { + @JsonProperty + public boolean booleanField; + @JsonProperty + public double doubleField; + @JsonProperty + public float floatField; + @JsonProperty + public int intField; + @JsonProperty + public long longField; + @JsonProperty + public short shortField; + @JsonProperty + public String stringField; + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + TestObject other = (TestObject) obj; + if (booleanField != other.booleanField) + return false; + if (Double.doubleToLongBits(doubleField) != Double.doubleToLongBits(other.doubleField)) + return false; + if (Float.floatToIntBits(floatField) != Float.floatToIntBits(other.floatField)) + return false; + if (intField != other.intField) + return false; + if (longField != other.longField) + return false; + if (shortField != other.shortField) + return false; + if (stringField == null) { + if (other.stringField != null) + return false; + } else if (!stringField.equals(other.stringField)) + return false; + return true; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + (booleanField ? 1231 : 1237); + long temp; + temp = Double.doubleToLongBits(doubleField); + result = prime * result + (int) (temp ^ (temp >>> 32)); + result = prime * result + Float.floatToIntBits(floatField); + result = prime * result + intField; + result = prime * result + (int) (longField ^ (longField >>> 32)); + result = prime * result + shortField; + result = prime * result + ((stringField == null) ? 0 : stringField.hashCode()); + return result; + } + + @Override + public String toString() { + return "TestObject [booleanField=" + booleanField + ", doubleField=" + doubleField + ", floatField=" + + floatField + ", intField=" + intField + ", longField=" + longField + ", shortField=" + shortField + + ", stringField=" + stringField + "]"; + } + } + + private static final String JSON = "{\n" // split + + " \"JsonCacheTest\": {\n" // split + + " \"array\": [1, \"2\", 3.0, 4.0],\n" // split + + " \"boolean\": true,\n" // split + + " \"date\": \"2019-01-16\",\n" // split + + " \"dateTimeZ\": \"2019-01-16T14:02:00.000Z\",\n" // split + + " \"number\": 3.14,\n" // split + + " \"string\": \"a string\",\n" // split + + " \"object\": {\n" // split + + " \"nestedArray\": [\"a\", \"b\", \"c\", \"d\"],\n" // split + + " \"nestedBoolean\": true,\n" // split + + " \"nestedDateTimeZ\": \"2019-01-16T14:02:00.000Z\",\n" // split + + " \"nestedNumber\": 2.72,\n" // split + + " \"nestedString\": \"a nested string\",\n" // split + + " \"nestedObject\": {\n" // split + + " \"a\": \"foo\",\n" // split + + " \"b\": \"bar\"\n" // split + + " }\n" // split + + " },\n" // split + + " \"testObjects\": [{\n" // split + + " \"booleanField\": true,\n" // split + + " \"shortField\": 1,\n" // split + + " \"intField\": 2,\n" // split + + " \"longField\": 3,\n" // split + + " \"floatField\": 1.23,\n" // split + + " \"doubleField\": 4.56,\n" // split + + " \"stringField\": \"a test string field\"\n" // split + + " }, {\n" // split + + " \"booleanField\": false,\n" // split + + " \"shortField\": 4,\n" // split + + " \"intField\": 5,\n" // split + + " \"longField\": 6,\n" // split + + " \"floatField\": 8.23,\n" // split + + " \"doubleField\": 9.56,\n" // split + + " \"stringField\": \"another test string field\"\n" // split + + " }\n" // split + + " ]\n" // split + + " }\n" // split + + "}"; + + private static final TestObject TEST_OBJECT_0 = new TestObject(); + + private static final TestObject TEST_OBJECT_1 = new TestObject(); + + private static final Date EXPECTED_DATE_JAVA; + + private static final org.joda.time.LocalDate EXPECTED_DATE_JODA; + + private static final SimpleDateFormat ISO8601_DATETIME_FORMAT_JAVA = new SimpleDateFormat( + "yyyy-MM-dd'T'HH:mm:ss.SSSX", Locale.getDefault()); + + private static final String DATE_STR = "2019-01-21"; + private static final String DATETIME_OFFSET_STR = "2019-01-21T12:28:31.234+00:00"; + + static { + TEST_OBJECT_0.booleanField = true; + TEST_OBJECT_0.shortField = 1; + TEST_OBJECT_0.intField = 2; + TEST_OBJECT_0.longField = 3L; + TEST_OBJECT_0.floatField = 1.23F; + TEST_OBJECT_0.doubleField = 4.56D; + TEST_OBJECT_0.stringField = "a test string field"; + + TEST_OBJECT_1.booleanField = false; + TEST_OBJECT_1.shortField = 4; + TEST_OBJECT_1.intField = 5; + TEST_OBJECT_1.longField = 6L; + TEST_OBJECT_1.floatField = 8.23F; + TEST_OBJECT_1.doubleField = 9.56D; + TEST_OBJECT_1.stringField = "another test string field"; + + try { + EXPECTED_DATE_JAVA = ISO8601_DATETIME_FORMAT_JAVA.parse("2019-01-16T14:02:00.000Z"); + EXPECTED_DATE_JODA = org.joda.time.LocalDate.parse("2019-01-16"); + } catch (ParseException | IllegalArgumentException e) { + IllegalArgumentException t = e instanceof IllegalArgumentException // split + ? (IllegalArgumentException) e + : new IllegalArgumentException("Unable to parse date string", e); + throw t; + } + } + + private JsonCache.Root root; + private JsonCache cache; + + private void reload() throws CacheException, UnsupportedEncodingException { + root.unload(); + root.load(new ByteArrayInputStream(JSON.getBytes("UTF-8"))); + } + + @Before + public void setUp() throws Exception { + // NOTE: we want each test to have its own pristine cache instance. + root = JsonCache.Factory.instance.create(); + ObjectMapper mapper = root.getMapper(); + mapper.registerModule(new JavaTimeModule()); + mapper.registerModule(new JodaModule()); + mapper.registerModule(new ThreeTenModule()); + cache = root.child("/JsonCacheTest"); + reload(); + } + + @Test + public void testAddBigDecimal() throws Exception { + BigDecimal value = new BigDecimal(5.1); + cache.add("/array/1", value); + assertEquals("Array size incorrect after add(path, value)", 5, cache.size("/array")); + assertEquals("Array element at index 0 incorrect after add(path, value);", 1, cache.get("/array/0")); + assertEquals("Array element at index 1 incorrect after add(path, value);", value, + cache.getBigDecimal("/array/1")); + assertEquals("Array element at index 2 incorrect after add(path, value);", "2", cache.get("/array/2")); + + value = new BigDecimal(6.2); + cache.add("/object/nestedArray/5", value); + assertEquals("Array size incorrect after add(path, value)", 6, cache.size("/object/nestedArray")); + assertEquals("Array element at index 4 incorrect after add(path, value);", null, + cache.get("/object/nestedArray/4")); + assertEquals("Array element at index 1 incorrect after add(path, value);", value, + cache.getBigDecimal("/object/nestedArray/5")); + } + + @Test + public void testAddBigInteger() throws Exception { + BigInteger value = new BigInteger("5"); + cache.add("/array/1", value); + assertEquals("Array size incorrect after add(path, value)", 5, cache.size("/array")); + assertEquals("Array element at index 0 incorrect after add(path, value);", 1, cache.get("/array/0")); + assertEquals("Array element at index 1 incorrect after add(path, value);", value, + cache.getBigInteger("/array/1")); + assertEquals("Array element at index 2 incorrect after add(path, value);", "2", cache.get("/array/2")); + + value = new BigInteger("6"); + cache.add("/object/nestedArray/5", value); + assertEquals("Array size incorrect after add(path, value)", 6, cache.size("/object/nestedArray")); + assertEquals("Array element at index 4 incorrect after add(path, value);", null, + cache.get("/object/nestedArray/4")); + assertEquals("Array element at index 1 incorrect after add(path, value);", value, + cache.getBigInteger("/object/nestedArray/5")); + } + + @Test + public void testAddBoolean() throws Exception { + cache.add("/array/1", true); + assertEquals("Array size incorrect after add(path, value)", 5, cache.size("/array")); + assertEquals("Array element at index 0 incorrect after add(path, value);", 1, cache.get("/array/0")); + assertEquals("Array element at index 1 incorrect after add(path, value);", true, cache.getBoolean("/array/1")); + assertEquals("Array element at index 2 incorrect after add(path, value);", "2", cache.get("/array/2")); + + cache.add("/object/nestedArray/5", true); + assertEquals("Array size incorrect after add(path, value)", 6, cache.size("/object/nestedArray")); + assertEquals("Array element at index 4 incorrect after add(path, value);", null, + cache.get("/object/nestedArray/4")); + assertEquals("Array element at index 1 incorrect after add(path, value);", true, + cache.getBoolean("/object/nestedArray/5")); + } + + @Test + public void testAddDate() throws Exception { + testAddDate0(DATETIME_OFFSET_STR, ISO8601_DATETIME_FORMAT_JAVA.parse(DATETIME_OFFSET_STR)); + } + + private void testAddDate0(String dateStr, Object date) throws Exception { + cache.add("/array/1", dateStr); + assertEquals("Array size incorrect after add(path, value)", 5, cache.size("/array")); + assertEquals("Array element at index 0 incorrect after add(path, value);", 1, cache.get("/array/0")); + assertEquals("Array element at index 1 incorrect after add(path, value);", date, + cache.getObject("/array/1", date.getClass())); + assertEquals("Array element at index 2 incorrect after add(path, value);", "2", cache.get("/array/2")); + + cache.add("/object/nestedArray/5", date); + assertEquals("Array size incorrect after add(path, value)", 6, cache.size("/object/nestedArray")); + assertEquals("Array element at index 4 incorrect after add(path, value);", null, + cache.get("/object/nestedArray/4")); + assertEquals("Array element at index 1 incorrect after add(path, value);", date, + cache.getObject("/object/nestedArray/5", date.getClass())); + } + + @Test + public void testAddDateTimeJava8() throws Exception { + testAddDate0(DATETIME_OFFSET_STR, java.time.OffsetDateTime.parse(DATETIME_OFFSET_STR)); + } + + @Test + public void testAddDateTimeJoda() throws Exception { + testAddDate0(DATETIME_OFFSET_STR, org.joda.time.DateTime.parse(DATETIME_OFFSET_STR)); + } + + @Test + public void testAddDateTimeThreeTen() throws Exception { + testAddDate0(DATETIME_OFFSET_STR, org.threeten.bp.OffsetDateTime.parse(DATETIME_OFFSET_STR)); + } + + @Test + public void testAddDouble() throws Exception { + cache.add("/array/1", 5.1D); + assertEquals("Array size incorrect after add(path, value)", 5, cache.size("/array")); + assertEquals("Array element at index 0 incorrect after add(path, value);", 1, cache.get("/array/0")); + assertEquals("Array element at index 1 incorrect after add(path, value);", 5.1D, cache.getDouble("/array/1"), + Double.MIN_VALUE); + assertEquals("Array element at index 2 incorrect after add(path, value);", "2", cache.get("/array/2")); + + cache.add("/object/nestedArray/5", 6.2D); + assertEquals("Array size incorrect after add(path, value)", 6, cache.size("/object/nestedArray")); + assertEquals("Array element at index 4 incorrect after add(path, value);", null, + cache.get("/object/nestedArray/4")); + assertEquals("Array element at index 1 incorrect after add(path, value);", 6.2D, + cache.getDouble("/object/nestedArray/5"), Double.MIN_VALUE); + } + + @Test + public void testAddFloat() throws Exception { + cache.add("/array/1", 5.1F); + assertEquals("Array size incorrect after add(path, value)", 5, cache.size("/array")); + assertEquals("Array element at index 0 incorrect after add(path, value);", 1, cache.get("/array/0")); + assertEquals("Array element at index 1 incorrect after add(path, value);", 5.1F, cache.getFloat("/array/1"), + Float.MIN_VALUE); + assertEquals("Array element at index 2 incorrect after add(path, value);", "2", cache.get("/array/2")); + + cache.add("/object/nestedArray/5", 6.2F); + assertEquals("Array size incorrect after add(path, value)", 6, cache.size("/object/nestedArray")); + assertEquals("Array element at index 4 incorrect after add(path, value);", null, + cache.get("/object/nestedArray/4")); + assertEquals("Array element at index 1 incorrect after add(path, value);", 6.2F, + cache.getFloat("/object/nestedArray/5"), Float.MIN_VALUE); + } + + @Test + public void testAddInt() throws Exception { + cache.add("/array/1", 5); + assertEquals("Array size incorrect after add(path, value)", 5, cache.size("/array")); + assertEquals("Array element at index 0 incorrect after add(path, value);", 1, cache.get("/array/0")); + assertEquals("Array element at index 1 incorrect after add(path, value);", 5, cache.getInt("/array/1")); + assertEquals("Array element at index 2 incorrect after add(path, value);", "2", cache.get("/array/2")); + + cache.add("/object/nestedArray/5", 6); + assertEquals("Array size incorrect after add(path, value)", 6, cache.size("/object/nestedArray")); + assertEquals("Array element at index 4 incorrect after add(path, value);", null, + cache.get("/object/nestedArray/4")); + assertEquals("Array element at index 1 incorrect after add(path, value);", 6, + cache.getInt("/object/nestedArray/5")); + } + + @Test + public void testAddLocalDateJava8() throws Exception { + testAddDate0(DATE_STR, java.time.LocalDate.parse(DATE_STR)); + } + + @Test + public void testAddLocalDateJoda() throws Exception { + testAddDate0(DATE_STR, org.joda.time.LocalDate.parse(DATE_STR)); + } + + @Test + public void testAddLocalDateThreeTen() throws Exception { + testAddDate0(DATE_STR, org.threeten.bp.LocalDate.parse(DATE_STR)); + } + + @Test + public void testAddLong() throws Exception { + cache.add("/array/1", 5L); + assertEquals("Array size incorrect after add(path, value)", 5, cache.size("/array")); + assertEquals("Array element at index 0 incorrect after add(path, value);", 1, cache.get("/array/0")); + assertEquals("Array element at index 1 incorrect after add(path, value);", 5L, cache.getLong("/array/1")); + assertEquals("Array element at index 2 incorrect after add(path, value);", "2", cache.get("/array/2")); + + cache.add("/object/nestedArray/5", 6L); + assertEquals("Array size incorrect after add(path, value)", 6, cache.size("/object/nestedArray")); + assertEquals("Array element at index 4 incorrect after add(path, value);", null, + cache.get("/object/nestedArray/4")); + assertEquals("Array element at index 1 incorrect after add(path, value);", 6L, + cache.getLong("/object/nestedArray/5")); + } + + public void testAddObject() throws Exception { + cache.add("/array/1", TEST_OBJECT_0); + assertEquals("Array size incorrect after add(path, value)", 5, cache.size("/array")); + assertEquals("Array element at index 0 incorrect after add(path, value);", 1, cache.get("/array/0")); + assertEquals("Array element at index 1 incorrect after add(path, value);", TEST_OBJECT_0, + cache.getObject("/array/1", TestObject.class)); + assertEquals("Array element at index 2 incorrect after add(path, value);", "2", cache.get("/array/2")); + + cache.add("/object/nestedArray/5", TEST_OBJECT_1); + assertEquals("Array size incorrect after add(path, value)", 6, cache.size("/object/nestedArray")); + assertEquals("Array element at index 4 incorrect after add(path, value);", null, + cache.get("/object/nestedArray/4")); + assertEquals("Array element at index 1 incorrect after add(path, value);", TEST_OBJECT_1, + cache.getObject("/object/nestedArray/5", TestObject.class)); + } + + @Test + public void testAddShort() throws Exception { + cache.add("/array/1", (short) 5); + assertEquals("Array size incorrect after add(path, value)", 5, cache.size("/array")); + assertEquals("Array element at index 0 incorrect after add(path, value);", 1, cache.get("/array/0")); + assertEquals("Array element at index 1 incorrect after add(path, value);", (short) 5, + cache.getShort("/array/1")); + assertEquals("Array element at index 2 incorrect after add(path, value);", "2", cache.get("/array/2")); + + cache.add("/object/nestedArray/5", (short) 6); + assertEquals("Array size incorrect after add(path, value)", 6, cache.size("/object/nestedArray")); + assertEquals("Array element at index 4 incorrect after add(path, value);", null, + cache.get("/object/nestedArray/4")); + assertEquals("Array element at index 1 incorrect after add(path, value);", (short) 6, + cache.getShort("/object/nestedArray/5")); + } + + @Test + public void testAddString() throws Exception { + cache.add("/array/1", "5"); + assertEquals("Array size incorrect after add(path, value)", 5, cache.size("/array")); + assertEquals("Array element at index 0 incorrect after add(path, value);", 1, cache.get("/array/0")); + assertEquals("Array element at index 1 incorrect after add(path, value);", "5", cache.getString("/array/1")); + assertEquals("Array element at index 2 incorrect after add(path, value);", "2", cache.get("/array/2")); + + cache.add("/object/nestedArray/5", "6"); + assertEquals("Array size incorrect after add(path, value)", 6, cache.size("/object/nestedArray")); + assertEquals("Array element at index 4 incorrect after add(path, value);", null, + cache.get("/object/nestedArray/4")); + assertEquals("Array element at index 1 incorrect after add(path, value);", "6", + cache.getString("/object/nestedArray/5")); + } + + @Test + public void testDelete() throws Exception { + assertTrue("existing root element is not an object;", cache.get("") instanceof ObjectNode); + + cache.delete("/array/2"); + assertEquals("Array size incorrect after delete element;", 3, cache.size("/array")); + assertEquals("Array element at index 1 incorrect after delete;", "2", cache.getString("/array/1")); + assertEquals("Array element at index 2 incorrect after delete;", 4.0D, cache.getDouble("/array/2"), + Double.MIN_VALUE); + + cache.delete("/object/nestedArray/2"); + assertEquals("Array size incorrect after delete element;", 3, cache.size("/object/nestedArray")); + assertEquals("Array element at index 1 incorrect after delete;", "b", cache.getString("/object/nestedArray/1")); + assertEquals("Array element at index 2 incorrect after delete;", "d", cache.getString("/object/nestedArray/2")); + + cache.delete("/object"); + assertFalse("delete object failed;", cache.exists("/object")); + + cache.delete(""); + assertFalse("delete root failed;", cache.exists("")); + + // This call should have reinstated the missing root as an array. + cache.set("/0", true); + assertTrue("new root element is not an array;", cache.get("") instanceof ArrayNode); + assertEquals("Failed to set root array element 0 when root is null;", true, cache.getBoolean("/0")); + + cache.set("/1", 3.14); + assertEquals("Failed to set root array element 1;", 3.14, cache.getDouble("/1"), Double.MIN_VALUE); + + cache.set("/2", "a string element"); + assertEquals("Failed to set root array element 2;", "a string element", cache.getString("/2")); + + // Now that root has been reallocated as an array, try and set a non-integer property on it. + try { + cache.set("/astring", "won't work!"); + fail("attempting to set a non-integer property on an array should have failed"); + } catch (NumberFormatException e) { + assertFalse("setting a non-numeric property on an array worked!;", cache.exists("/astring")); + } + } + + @Test + public void testFlushSaveLoad() throws Exception { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + + root.flush(out); + assertTrue("non-dirty flush() should not have written bytes;", out.size() == 0); + assertFalse("cache should not be dirty after no-op flush();", root.isDirty()); + + root.save(out); + assertTrue("save() wrote no bytes;", out.size() > 0); + assertFalse("cache should not be dirty after save();", root.isDirty()); + + root.delete(""); + assertFalse("cache not empty;", cache.exists("")); + + root.unload(); + assertFalse("cache should not be dirty after unload();", root.isDirty()); + + root.load(new ByteArrayInputStream(out.toByteArray())); + assertFalse("cache should not be dirty after load();", root.isDirty()); + + testGet(); + + assertFalse("cache should not be dirty after reads;", root.isDirty()); + } + + @Test + public void testGet() throws Exception { + assertEquals("boolean get() returned incorrect result;", true, cache.get("/boolean")); + assertEquals("number get() returned incorrect result;", 3.14, cache.get("/number")); + assertEquals("string get() returned incorrect result;", "a string", cache.get("/string")); + Object array = cache.get("/array"); + assertNotNull("array get() returned null;", array); + assertTrue("array get() returned incorrect type;", array instanceof ArrayNode); + assertEquals("array size() returned incorrect result;", 4, cache.size("/array")); + assertEquals("array get element 0 returned incorrect result;", 1, cache.get("/array/0")); + assertEquals("array get element 2 returned incorrect result;", JsonNodeType.NUMBER, + cache.getNodeType("/array/0")); + assertEquals("array get element 1 returned incorrect result;", "2", cache.get("/array/1")); + assertEquals("array get element 2 returned incorrect result;", 3.0, cache.get("/array/2")); + assertEquals("array get element 2 returned incorrect result;", JsonNodeType.NUMBER, + cache.getNodeType("/array/2")); + assertEquals("array get element 3 returned incorrect result;", 4.0D, cache.get("/array/3")); + Object object = cache.get("/object"); + assertNotNull("object get() returned null;", object); + assertTrue("object get() returned incorrect type;", object instanceof ObjectNode); + + assertEquals("nested boolean get() returned incorrect result;", true, cache.get("/object/nestedBoolean")); + assertEquals("nested number get() returned incorrect result;", 2.72, cache.get("/object/nestedNumber")); + assertEquals("nested string get() returned incorrect result;", "a nested string", + cache.get("/object/nestedString")); + Object nestedArray = cache.get("/object/nestedArray"); + assertNotNull("nested array get() returned null;", nestedArray); + assertTrue("nested array get() returned incorrect type;", nestedArray instanceof ArrayNode); + assertEquals("nested array size() returned incorrect result;", 4, cache.size("/object/nestedArray")); + assertEquals("nested array get element returned incorrect result;", "a", cache.get("/object/nestedArray/0")); + assertEquals("nested array get element returned incorrect result;", "d", cache.get("/object/nestedArray/3")); + Object nestedObject = cache.get("/object/nestedObject"); + assertNotNull("object get() returned null;", nestedObject); + assertTrue("object get() returned incorrect type;", nestedObject instanceof ObjectNode); + + assertEquals("test object 0 booleanField is incorrect;", true, cache.get("/testObjects/0/booleanField")); + assertEquals("test object 0 shortField is incorrect;", 1, cache.get("/testObjects/0/shortField")); + assertEquals("test object 0 intField is incorrect;", 2, cache.get("/testObjects/0/intField")); + assertEquals("test object 0 longField is incorrect;", 3, cache.get("/testObjects/0/longField")); + assertEquals("test object 0 floatField is incorrect;", 1.23, cache.get("/testObjects/0/floatField")); + assertEquals("test object 0 doubleField is incorrect;", 4.56, cache.get("/testObjects/0/doubleField")); + assertEquals("test object 0 stringField is incorrect;", "a test string field", + cache.get("/testObjects/0/stringField")); + + assertEquals("test object 1 booleanField is incorrect;", false, cache.get("/testObjects/1/booleanField")); + assertEquals("test object 1 shortField is incorrect;", 4, cache.get("/testObjects/1/shortField")); + assertEquals("test object 1 intField is incorrect;", 5, cache.get("/testObjects/1/intField")); + assertEquals("test object 1 longField is incorrect;", 6, cache.get("/testObjects/1/longField")); + assertEquals("test object 1 floatField is incorrect;", 8.23, cache.get("/testObjects/1/floatField")); + assertEquals("test object 1 doubleField is incorrect;", 9.56, cache.get("/testObjects/1/doubleField")); + assertEquals("test object 1 stringField is incorrect;", "another test string field", + cache.get("/testObjects/1/stringField")); + } + + @Test + public void testGetBigDecimal() throws Exception { + assertEquals("getBigDecimal(path) returned incorrect result;", new BigDecimal("3.14"), + cache.getBigDecimal("/number")); + assertEquals("getBigDecimal(nestedPath) returned incorrect result;", new BigDecimal("2.72"), + cache.getBigDecimal("/object/nestedNumber")); + assertFalse("cache should not be dirty after getBigDecimal(path);", root.isDirty()); + } + + @Test + public void testGetBigDecimalWithDefault() throws Exception { + BigDecimal bd162 = new BigDecimal("1.62"); + BigDecimal bd272 = new BigDecimal("2.72"); + BigDecimal bd314 = new BigDecimal("3.14"); + BigDecimal bd628 = new BigDecimal("3.14"); + + assertEquals("getBigDecimal(path, default) returned incorrect result;", bd314, + cache.getBigDecimal("/number", bd162)); + assertEquals("getBigDecimal(nestedPath, default) returned incorrect result;", bd272, + cache.getBigDecimal("/object/nestedNumber", bd628)); + assertFalse("cache should not be dirty after getBigDecimal(path, default);", root.isDirty()); + + assertEquals("getBigDecimal(nonExistentPath, default) returned incorrect result;", bd162, + cache.getBigDecimal("/nonExistentNumber", bd162)); + assertEquals("nested getBigDecimal(nonExistentNestedPath, default) returned incorrect result;", bd628, + cache.getBigDecimal("/object/nonExistentNestedNumber", bd628)); + assertTrue("cache should be dirty after getBigDecimal(nonExistentPath, default);", root.isDirty()); + + assertEquals("getBigDecimal(path) returned incorrect result after update;", bd162, + cache.getBigDecimal("/nonExistentNumber")); + assertEquals("nested getBigDecimal(path) returned incorrect result after update;", bd628, + cache.getBigDecimal("/object/nonExistentNestedNumber")); + } + + @Test + public void testGetBigInteger() throws Exception { + BigInteger bi2 = new BigInteger("2"); + BigInteger bi3 = new BigInteger("3"); + + assertEquals("getBigInteger(path) returned incorrect result;", bi3, cache.getBigInteger("/number")); + assertEquals("getBigInteger(nestedPath) returned incorrect result;", bi2, + cache.getBigInteger("/object/nestedNumber")); + assertFalse("cache should not be dirty after getBigInteger(path);", root.isDirty()); + } + + @Test + public void testGetBigIntegerWithDefault() throws Exception { + BigInteger bi2 = new BigInteger("2"); + BigInteger bi3 = new BigInteger("3"); + BigInteger bi4 = new BigInteger("4"); + BigInteger bi5 = new BigInteger("5"); + + assertEquals("getBigInteger(path, default) returned incorrect result;", bi3, + cache.getBigInteger("/number", bi4)); + assertEquals("getBigInteger(nestedPath, default) returned incorrect result;", bi2, + cache.getBigInteger("/object/nestedNumber", bi5)); + assertFalse("cache should not be dirty after getBigInteger(path, default);", root.isDirty()); + + assertEquals("getBigInteger(nonExistentPath, default) returned incorrect result;", bi4, + cache.getBigInteger("/nonExistentNumber", bi4)); + assertEquals("getBigInteger(nonExistentNestedPath, default) returned incorrect result;", bi5, + cache.getBigInteger("/object/nonExistentNestedNumber", bi5)); + assertTrue("cache should be dirty after getBigInteger(nonExistentPath, default);", root.isDirty()); + + assertEquals("getBigInteger(path) returned incorrect result after update;", bi4, + cache.getBigInteger("/nonExistentNumber")); + assertEquals("getBigInteger(nestedPath) returned incorrect result after update;", bi5, + cache.getBigInteger("/object/nonExistentNestedNumber")); + } + + @Test + public void testGetBoolean() throws Exception { + assertEquals("getBoolean(path) returned incorrect result;", true, cache.getBoolean("/boolean")); + assertEquals("getBoolean(nestedPath) returned incorrect result;", true, + cache.getBoolean("/object/nestedBoolean")); + assertFalse("cache should not be dirty after getBoolean(path);", root.isDirty()); + } + + @Test + public void testGetBooleanWithDefault() throws Exception { + assertEquals("getBoolean(path, default) returned incorrect result;", true, cache.getBoolean("/boolean", false)); + assertEquals("getBoolean(nestedPath, default) returned incorrect result;", true, + cache.getBoolean("/object/nestedBoolean", false)); + assertFalse("cache should not be dirty after getBoolean(path, default);", root.isDirty()); + + assertEquals("getBoolean(nonExistentPath, default) returned incorrect result;", true, + cache.getBoolean("/nonExistentBoolean", true)); + assertEquals("getBoolean(nonExistentNestedPath, default) returned incorrect result;", true, + cache.getBoolean("/object/nonExistentNestedBoolean", true)); + assertTrue("cache should be dirty after getBoolean(nonExistentPath, default);", root.isDirty()); + + assertEquals("getBoolean(nonExistentPath, default) returned incorrect result;", true, + cache.getBoolean("/nonExistentBoolean")); + assertEquals("getBoolean(nonExistentNestedPath, default) returned incorrect result;", true, + cache.getBoolean("/object/nonExistentNestedBoolean")); + } + + @Test + public void testGetDate() throws Exception { + assertEquals("getDate(path) returned incorrect result;", EXPECTED_DATE_JAVA, + cache.getObject("/dateTimeZ", Date.class)); + assertEquals("getDate(nestedPath) returned incorrect result;", EXPECTED_DATE_JAVA, + cache.getObject("/object/nestedDateTimeZ", Date.class)); + assertFalse("cache should not be dirty after getDate(path);", root.isDirty()); + } + + @Test + public void testGetDateWithDefault() throws Exception { + Date defaultDate = new Date(); + assertEquals("getDate(path, default) returned incorrect result;", EXPECTED_DATE_JAVA, + cache.getObject("/dateTimeZ", defaultDate)); + assertEquals("getDate(nestedPath, default) returned incorrect result;", EXPECTED_DATE_JAVA, + cache.getObject("/object/nestedDateTimeZ", defaultDate)); + assertFalse("cache should not be dirty after getDate(path, default);", root.isDirty()); + + assertEquals("getDate(nonExistentPath, default) returned incorrect result;", defaultDate, + cache.getObject("/nonExistentDate", defaultDate)); + assertEquals("getDate(nonExistentNestedPath, default) returned incorrect result;", defaultDate, + cache.getObject("/object/nonExistentNestedDate", defaultDate)); + assertTrue("cache should be dirty after getDate(nonExistentPath, default);", root.isDirty()); + + assertEquals("getDate(path) returned incorrect result after update;", defaultDate, + cache.getObject("/nonExistentDate", Date.class)); + assertEquals("getDate(nestedPath) returned incorrect result after update;", defaultDate, + cache.getObject("/object/nonExistentNestedDate", Date.class)); + } + + @Test + public void testGetDouble() throws Exception { + assertEquals("getDouble(path) returned incorrect result;", 3.14D, cache.getDouble("/number"), Double.MIN_VALUE); + assertEquals("getDouble(nestedPath) returned incorrect result;", 2.72D, cache.getDouble("/object/nestedNumber"), + Double.MIN_VALUE); + assertFalse("cache should not be dirty after getDouble(path);", root.isDirty()); + } + + @Test + public void testGetDoubleWithDefault() throws Exception { + assertEquals("getDouble(path, default) returned incorrect result;", 3.14D, cache.getDouble("/number", 7.77D), + Double.MIN_VALUE); + assertEquals("getDouble(nestedPath, default) returned incorrect result;", 2.72D, + cache.getDouble("/object/nestedNumber", 8.88D), Double.MIN_VALUE); + assertFalse("cache should not be dirty after getDouble(path, default);", root.isDirty()); + + assertEquals("getDouble(nonExistentPath, default) returned incorrect result;", 7.77D, + cache.getDouble("/nonExistentNumber", 7.77D), Double.MIN_VALUE); + assertEquals("getDouble(nonExistentNestedPath, default) returned incorrect result;", 8.88D, + cache.getDouble("/object/nonExistentNestedNumber", 8.88D), Double.MIN_VALUE); + assertTrue("cache should be dirty after getDouble(nonExistentPath, default);", root.isDirty()); + + assertEquals("getDouble(path) returned incorrect result after update;", 7.77D, + cache.getDouble("/nonExistentNumber"), Double.MIN_VALUE); + assertEquals("getDouble(nestedPath) returned incorrect result after update;", 8.88D, + cache.getDouble("/object/nonExistentNestedNumber"), Double.MIN_VALUE); + } + + @Test + public void testGetFloat() throws Exception { + assertEquals("getFloat(path) returned incorrect result;", 3.14F, cache.getFloat("/number"), Float.MIN_VALUE); + assertEquals("nested getFloat(nestedPath) returned incorrect result;", 2.72F, + cache.getFloat("/object/nestedNumber"), Float.MIN_VALUE); + assertFalse("cache should not be dirty after getFloat(path);", root.isDirty()); + } + + @Test + public void testGetFloatWithDefault() throws Exception { + assertEquals("getFloat(path, default) returned incorrect result;", 3.14F, cache.getFloat("/number", 7.77F), + Float.MIN_VALUE); + assertEquals("nested getFloat(nestedPath, default) returned incorrect result;", 2.72F, + cache.getFloat("/object/nestedNumber", 8.88F), Float.MIN_VALUE); + assertFalse("cache should not be dirty after getFloat(path, default);", root.isDirty()); + + assertEquals("getFloat(nonExistentPath, default) returned incorrect result;", 7.77F, + cache.getFloat("/nonExistentNumber", 7.77F), Float.MIN_VALUE); + assertEquals("nested getFloat(nonExistentNestedPath, default) returned incorrect result;", 8.88F, + cache.getFloat("/object/nonExistentNestedNumber", 8.88F), Float.MIN_VALUE); + assertTrue("cache should be dirty after getFloat(nonExistentPath, default);", root.isDirty()); + + assertEquals("getFloat(path) returned incorrect result after update;", 7.77F, + cache.getFloat("/nonExistentNumber"), Float.MIN_VALUE); + assertEquals("nested getFloat(nestedPath) returned incorrect result after update;", 8.88F, + cache.getFloat("/object/nonExistentNestedNumber"), Float.MIN_VALUE); + } + + @Test + public void testGetInt() throws Exception { + assertEquals("getInt(path) returned incorrect result;", 3, cache.getInt("/number")); + assertEquals("getInt(nestedPath) returned incorrect result;", 2, cache.getInt("/object/nestedNumber")); + assertFalse("cache should not be dirty after getInt(path);", root.isDirty()); + } + + @Test + public void testGetIntWithDefault() throws Exception { + assertEquals("getInt(path, default) returned incorrect result;", 3, cache.getInt("/number", 5)); + assertEquals("getInt(nestedPath, default) returned incorrect result;", 4, cache.getInt("/object/nestedNumber"), + 2); + assertFalse("cache should not be dirty after getInt(path, default);", root.isDirty()); + + assertEquals("getInt(nonExistentPath, default) returned incorrect result;", 5, + cache.getInt("/nonExistentNumber", 5)); + assertEquals("getInt(nonExistentNestedPath, default) returned incorrect result;", 4, + cache.getInt("/object/nonExistentNestedNumber", 4)); + assertTrue("cache should be dirty after getInt(nonExistentPath, default);", root.isDirty()); + + assertEquals("getInt(path) returned incorrect result after update;", 5, cache.getInt("/nonExistentNumber")); + assertEquals("getInt(nestedPath) returned incorrect result after update;", 4, + cache.getInt("/object/nonExistentNestedNumber")); + } + + @Test + public void testGetLocalDate() throws Exception { + assertEquals("getLocalDate(path) returned incorrect result;", EXPECTED_DATE_JODA, + cache.getObject("/date", org.joda.time.LocalDate.class)); + assertFalse("cache should not be dirty after getLocalDate(path);", root.isDirty()); + } + + public void testGetLocalDateWithDefault() throws Exception { + org.joda.time.LocalDate defaultDate = new org.joda.time.LocalDate(); + assertEquals("getLocalDate(path, default) returned incorrect result;", EXPECTED_DATE_JODA, + cache.getObject("/dateTimeZ", defaultDate)); + assertEquals("getLocalDate(nestedPath, default) returned incorrect result;", EXPECTED_DATE_JODA, + cache.getObject("/object/nestedLocalDate", defaultDate)); + assertFalse("cache should not be dirty after getLocalDate(path, default);", root.isDirty()); + + assertEquals("getLocalDate(nonExistentPath, default) returned incorrect result;", defaultDate, + cache.getObject("/nonExistentLocalDate", defaultDate)); + assertEquals("getLocalDate(nonExistentNestedPath, default) returned incorrect result;", defaultDate, + cache.getObject("/object/nonExistentNestedLocalDate", defaultDate)); + assertTrue("cache should be dirty after getLocalDate(nonExistentPath, default);", root.isDirty()); + + assertEquals("getLocalDate(path) returned incorrect result after update;", defaultDate, + cache.getObject("/nonExistentLocalDate", org.joda.time.LocalDate.class)); + assertEquals("getLocalDate(nestedPath) returned incorrect result after update;", defaultDate, + cache.getObject("/object/nonExistentNestedLocalDate", org.joda.time.LocalDate.class)); + } + + @Test + public void testGetLong() throws Exception { + assertEquals("getLong(path) returned incorrect result;", 3L, cache.getLong("/number")); + assertEquals("getLong(nestedPath) returned incorrect result;", 2L, cache.getLong("/object/nestedNumber")); + assertFalse("cache should not be dirty after getLong(path);", root.isDirty()); + } + + @Test + public void testGetLongWithDefault() throws Exception { + assertEquals("getLong(path, default) returned incorrect result;", 3L, cache.getLong("/number", 5L)); + assertEquals("getLong(nestedPath, default) returned incorrect result;", 2L, + cache.getLong("/object/nestedNumber", 4L)); + assertFalse("cache should not be dirty after getLong(path, default);", root.isDirty()); + + assertEquals("getLong(nonExistentPath, default) returned incorrect result;", 5L, + cache.getLong("/nonExistentNumber", 5L)); + assertEquals("getLong(nonExistentNestedPath, default) returned incorrect result;", 4L, + cache.getLong("/object/nonExistentNestedNumber", 4L)); + assertTrue("cache should be dirty after getLong(nonExistentPath, default);", root.isDirty()); + + assertEquals("getLong(path, default) returned incorrect result after update;", 5L, + cache.getLong("/nonExistentNumber")); + assertEquals("getLong(nestedPath, default) returned incorrect result after update;", 4L, + cache.getLong("/object/nonExistentNestedNumber")); + } + + @Test + public void testGetNumber() throws Exception { + Number number = cache.getNumber("/number"); + assertTrue("getNumber(path) returned incorrect type;", number instanceof Double); + assertEquals("getNumber(path) returned incorrect result;", 3.14D, number); + Number nestedNumber = cache.getNumber("/object/nestedNumber"); + assertTrue("getNumber(nestedPath) returned incorrect type;", nestedNumber instanceof Double); + assertEquals("nested getNumber(nestedPath) returned incorrect result;", 2.72D, nestedNumber); + assertFalse("cache should not be dirty after getNumber(path);", root.isDirty()); + } + + @Test + public void testGetNumberWithDefault() throws Exception { + assertEquals("getNumber(path, default) returned incorrect result;", 3.14D, cache.getNumber("/number", 7.77D)); + assertEquals("getNumber(nestedPath, default) returned incorrect result;", 2.72D, + cache.getNumber("/object/nestedNumber", 8.88D)); + assertFalse("cache should not be dirty after getNumber(path, default);", root.isDirty()); + + assertEquals("getNumber(nonExistentPath, default) returned incorrect result;", 7.77D, + cache.getNumber("/nonExistentNumber", 7.77D)); + assertEquals("getNumber(nonExistentNestedPath, default) returned incorrect result;", 8.88D, + cache.getNumber("/object/nonExistentNestedNumber", 8.88D)); + assertTrue("cache should be dirty after getNumber(nonExistentPath, default);", root.isDirty()); + + assertEquals("getNumber(path, default) returned incorrect result after update;", 7.77D, + cache.getNumber("/nonExistentNumber")); + assertEquals("getNumber(nestedPath, default) returned incorrect result after update;", 8.88D, + cache.getNumber("/object/nonExistentNestedNumber")); + } + + @Test + public void testGetObject() throws Exception { + TestObject testObject0 = cache.getObject("/testObjects/0", TestObject.class); + assertEquals("getObject(path) returned incorrect result;", TEST_OBJECT_0, testObject0); + TestObject testObject1 = cache.getObject("/testObjects/1", TestObject.class); + assertEquals("getObject(path) returned incorrect result;", TEST_OBJECT_1, testObject1); + assertFalse("cache should not be dirty after getObject(path, type);", root.isDirty()); + } + + @Test + public void testGetObjects() throws Exception { + List testObjects = cache.getObjects("/testObjects", TestObject.class); + assertEquals("getObjects(path, type) returned incorrect result;", TEST_OBJECT_0, testObjects.get(0)); + assertEquals("getObjects(path, type) returned incorrect result;", TEST_OBJECT_1, testObjects.get(1)); + assertFalse("cache should not be dirty after getObjects(path, type);", root.isDirty()); + } + + @Test + public void testGetObjectsWithDefault() throws Exception { + List defaultValue = Arrays.asList(TEST_OBJECT_1, TEST_OBJECT_0); + List testObjects = cache.getObjects("/testObjects", TestObject.class, defaultValue); + assertEquals("getObjects(path, type, defaultValue) returned incorrect result;", TEST_OBJECT_0, + testObjects.get(0)); + assertEquals("getObjects(path, type, defaultValue) returned incorrect result;", TEST_OBJECT_1, + testObjects.get(1)); + assertFalse("cache should not be dirty after getObjects(path, type, defaultValue);", root.isDirty()); + + testObjects = cache.getObjects("/nonExistentTestObjects", TestObject.class, defaultValue); + assertEquals("getObjects(nonExistentPath, type, defaultValue) returned incorrect result;", TEST_OBJECT_1, + testObjects.get(0)); + assertEquals("getObjects(nonExistentPath, type, defaultValue) returned incorrect result;", TEST_OBJECT_0, + testObjects.get(1)); + assertTrue("cache should be dirty after getObjects(nonExistentPath, type, defaultValue);", root.isDirty()); + + testObjects = cache.getObjects("/nonExistentTestObjects", TestObject.class); + assertEquals("getObjects(path, type) returned incorrect result after update;", TEST_OBJECT_1, + testObjects.get(0)); + assertEquals("getObjects(path, type) returned incorrect result after update;", TEST_OBJECT_0, + testObjects.get(1)); + } + + @Test + public void testGetObjectWithDefault() throws Exception { + assertEquals("getObject(path, default) returned incorrect result;", TEST_OBJECT_0, + cache.getObject("/testObjects/0", TEST_OBJECT_1)); + assertFalse("cache should not be dirty after getObject(path, default);", root.isDirty()); + + assertSame("getObject(nonExistentPath, default) returned incorrect result;", TEST_OBJECT_1, + cache.getObject("/testObjects/2", TEST_OBJECT_1)); + assertTrue("cache should be dirty after getObject(nonExistentPath, default);", root.isDirty()); + + assertSame("getObject(path, type) returned incorrect result after update;", TEST_OBJECT_1, + cache.getObject("/testObjects/2", TestObject.class)); + } + + @Test + public void testGetShort() throws Exception { + assertEquals("getShort(path) returned incorrect result;", 3, cache.getShort("/number")); + assertEquals("nested getShort(nestedPath) returned incorrect result;", 2, + cache.getShort("/object/nestedNumber")); + assertFalse("cache should not be dirty after getShort(path);", root.isDirty()); + } + + @Test + public void testGetShortWithDefault() throws Exception { + assertEquals("getShort(path, default) returned incorrect result;", 3, cache.getShort("/number", (short) 5)); + assertEquals("nested getShort(nestedPath, default) returned incorrect result;", 2, + cache.getShort("/object/nestedNumber", (short) 4)); + assertFalse("cache should not be dirty after getShort(path, default);", root.isDirty()); + + assertEquals("getShort(nonExistentPath, default) returned incorrect result;", 5, + cache.getShort("/nonExistentNumber", (short) 5)); + assertEquals("nested getShort(nonExistentPathNestedPath, default) returned incorrect result;", 4, + cache.getShort("/object/nonExistentNestedNumber", (short) 4)); + assertTrue("cache should be dirty after getShort(nonExistentPath, default);", root.isDirty()); + + assertEquals("getShort(path) returned incorrect result after update;", 5, cache.getShort("/nonExistentNumber")); + assertEquals("nested getShort(nestedPath) returned incorrect result after update;", 4, + cache.getShort("/object/nonExistentNestedNumber")); + } + + @Test + public void testGetString() throws Exception { + assertEquals("getString(path) returned incorrect result;", "a string", cache.getString("/string")); + assertEquals("getString(nestedPath) returned incorrect result;", "a nested string", + cache.getString("/object/nestedString")); + assertFalse("cache should not be dirty after getString(path);", root.isDirty()); + } + + @Test + public void testGetStringWithDefault() throws Exception { + assertEquals("getString(path, default) returned incorrect result;", "a string", + cache.getString("/string", "a different string")); + assertEquals("getString(nestedPath, default) returned incorrect result;", "a nested string", + cache.getString("/object/nestedString", "a different nested string")); + assertFalse("cache should not be dirty after getString(path, default);", root.isDirty()); + + assertEquals("getString(nonExistentPath, default) returned incorrect result;", "a different string", + cache.getString("/nonExistentString", "a different string")); + assertEquals("getString(nonExistentNestedPath, default) returned incorrect result;", + "a different nested string", + cache.getString("/object/nonExistentNestedString", "a different nested string")); + assertTrue("cache should be dirty after getString(nonExistentPath, default);", root.isDirty()); + + assertEquals("getString(path) returned incorrect result after update;", "a different string", + cache.getString("/nonExistentString")); + assertEquals("getString(nestedPath) returned incorrect result after update;", "a different nested string", + cache.getString("/object/nonExistentNestedString")); + } + + @Test + public void testMerge() throws Exception { + String incoming = "{\n" // split + + " \"JsonCacheTest\": {\n" // split + + " \"boolean\": false,\n" // modified + + " \"string\": \"a different string\",\n" // modified + + " \"anotherString\": \"another string\",\n" // added + + " \"array\": [1, \"2\", 3.0, 4.0, true, {}, []],\n" // elements added + + " \"object\": {\n" // split + + " \"nestedString\": \"a different nested string\",\n" // modified + + " \"nestedArray\": [\"a\", \"b\", \"e\", \"f\", \"g\"],\n" // elements modified & added + + " \"nestedObject\": {\n" // split + + " \"b\": \"baz\",\n" // modified + + " \"nestedNested\": {\"d\": \"waz\"}\n" // added + + " }\n" // split + + " }\n" // split + + " },\n" // split + + " \"JsonCacheMerge\": {" // added + + " \"number\": 10" // split + + " }" // split + + "}"; + ByteArrayInputStream in = new ByteArrayInputStream(incoming.getBytes("UTF-8")); + + root.mergePolicy(MergePolicy.NO_MERGE).load(in); + assertFalse("cache should not be dirty after second load() in NO_MERGE mode", root.isDirty()); + assertEquals("root size incorrect after second load() in NO_MERGE mode;", 1, root.size("")); + assertEquals("cache size incorrect after second load() in NO_MERGE mode;", 8, cache.size("")); + testGet(); + + in.reset(); + root.mergePolicy(MergePolicy.KEEP_EXISTING).load(in); + assertTrue("cache should be dirty after second load() in KEEP_EXISTING mode", root.isDirty()); + assertEquals("root size incorrect after second load() in KEEP_EXISTING mode;", 2, root.size("")); + assertEquals("cache size incorrect after second load() in KEEP_EXISTING mode;", 8, cache.size("")); + assertFalse("descendent elements should not be merged in KEEP_EXISTING mode", cache.exists("/anotherString")); + assertFalse("descendent elements should not be merged in KEEP_EXISTING mode", + cache.exists("/object/nestedObject/nestedNested")); + assertEquals("added root property not merged in KEEP_EXISTING mode", 10, root.get("/JsonCacheMerge/number")); + assertEquals("added array elements merged in KEEP_EXISTING mode", 4, cache.size("/array")); + assertEquals("added array elements merged in KEEP_EXISTING mode", 4, cache.size("/object/nestedArray")); + testGet(); + + reload(); + in.reset(); + root.mergePolicy(MergePolicy.MERGE_RECURSIVE).load(in); + assertTrue("cache should be dirty after second load() in MERGE_RECURSIVE mode", root.isDirty()); + assertEquals("root size incorrect after second load() in MERGE_RECURSIVE mode;", 2, root.size("")); + assertEquals("added root property not merged in MERGE_RECURSIVE mode", 10, root.get("/JsonCacheMerge/number")); + assertEquals("added string property not merged in MERGE_RECURSIVE mode", "another string", + cache.get("/anotherString")); + assertEquals("added child array elements not merged in MERGE_RECURSIVE mode", 7, cache.size("/array")); + assertEquals("added child array element 4 not merged in MERGE_RECURSIVE mode", JsonNodeType.BOOLEAN, + cache.getNodeType("/array/4")); + assertEquals("added child array element 5 not merged in MERGE_RECURSIVE mode", JsonNodeType.OBJECT, + cache.getNodeType("/array/5")); + assertEquals("added child array element 6 not merged in MERGE_RECURSIVE mode", JsonNodeType.ARRAY, + cache.getNodeType("/array/6")); + assertEquals("array not merged correctly in MERGE_RECURSIVE mode", + Arrays.asList("a", "b", "c", "d", "e", "f", "g"), + cache.getObjects("/object/nestedArray", String.class)); + assertEquals("nested object not merged correctly in MERGE_RECURSIVE mode", "waz", + cache.get("/object/nestedObject/nestedNested/d")); + + reload(); + in.reset(); + root.mergePolicy(MergePolicy.OVERWRITE_EXISTING).load(in); + assertTrue("cache should be dirty after second load() in OVERWRITE_EXISTING mode", root.isDirty()); + assertEquals("existing boolean not overwritten by load() in OVERWRITE_EXISTING mode;", false, + cache.get("/boolean")); + assertFalse("existing number not deleted by load() in OVERWRITE_EXISTING mode;", cache.exists("/number")); + assertEquals("existing string not overwritten by load() in OVERWRITE_EXISTING mode;", "a different string", + cache.get("/string")); + assertEquals("added string not merged in OVERWRITE_EXISTING mode;", "another string", + cache.get("/anotherString")); + assertEquals("added array size incorrect in OVERWRITE_EXISTING mode;", 7, cache.size("/array")); + assertEquals("added object size incorrect in OVERWRITE_EXISTING mode;", 3, cache.size("/object")); + assertEquals("added nested string incorrect in OVERWRITE_EXISTING mode;", "a different nested string", + cache.get("/object/nestedString")); + assertEquals("added nested array size incorrect in OVERWRITE_EXISTING mode;", 5, + cache.size("/object/nestedArray")); + assertFalse("added nested string incorrect in OVERWRITE_EXISTING mode;", + cache.exists("/object/nestedObject/a")); + assertEquals("added nested string incorrect in OVERWRITE_EXISTING mode;", "baz", + cache.get("/object/nestedObject/b")); + assertEquals("added deep nested string incorrect in OVERWRITE_EXISTING mode;", "waz", + cache.get("/object/nestedObject/nestedNested/d")); + assertEquals("added root property not merged in OVERWRITE_EXISTING mode", 10, + root.get("/JsonCacheMerge/number")); + } + + @Test + public void testPojoSerialization() throws Exception { + cache.set("/testObjects/0", TEST_OBJECT_0); + cache.set("/testObjects/1", TEST_OBJECT_1); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + root.save(out); + cache.delete(""); + assertNull("root is not null;", cache.get("")); + + root.unload(); + root.load(new ByteArrayInputStream(out.toByteArray())); + + testGet(); + + assertFalse("cache should not be dirty after reads;", root.isDirty()); + } + + @Test + public void testSet() throws Exception { + cache.set("/boolean", false); + assertEquals("boolean get() returned incorrect result;", false, cache.get("/boolean")); + + cache.set("/number", 6.28); + assertEquals("number get() returned incorrect result;", 6.28, cache.get("/number")); + + cache.set("/string", "another string"); + assertEquals("string get() returned incorrect result;", "another string", cache.get("/string")); + + Object array = cache.get("/array"); + assertNotNull("array get() returned null;", array); + assertTrue("array get() returned incorrect type;", array instanceof ArrayNode); + + cache.set("/array/0", 2); + assertEquals("array get element returned incorrect result;", 2, cache.get("/array/0")); + cache.set("/array/3", 8.0D); + assertEquals("array get element returned incorrect result;", 8.0D, cache.get("/array/3")); + + Object object = cache.get("/object"); + assertNotNull("object get() returned null;", object); + assertTrue("object get() returned incorrect type;", object instanceof ObjectNode); + + cache.set("/object/nestedBoolean", false); + assertEquals("nested boolean get() returned incorrect result;", false, cache.get("/object/nestedBoolean")); + + cache.set("/object/nestedNumber", 1.618); + assertEquals("nested number get() returned incorrect result;", 1.618, cache.get("/object/nestedNumber")); + + cache.set("/object/nestedString", "another nested string"); + assertEquals("nested string get() returned incorrect result;", "another nested string", + cache.get("/object/nestedString")); + + Object nestedArray = cache.get("/object/nestedArray"); + assertNotNull("nested array get() returned null;", nestedArray); + assertTrue("nested array get() returned incorrect type;", nestedArray instanceof ArrayNode); + + cache.set("/object/nestedArray/0", "x"); + assertEquals("nested array get element returned incorrect result;", "x", cache.get("/object/nestedArray/0")); + cache.set("/object/nestedArray/3", "y"); + assertEquals("nested array get element returned incorrect result;", "y", cache.get("/object/nestedArray/3")); + + Object nestedObject = cache.get("/object/nestedObject"); + assertNotNull("object get() returned null;", nestedObject); + assertTrue("object get() returned incorrect type;", nestedObject instanceof ObjectNode); + + assertTrue("cache should be dirty after writes;", root.isDirty()); + } + + @Test + public void testSetBigDecimal() throws Exception { + BigDecimal bd628 = new BigDecimal("6.28"); + cache.set("/number", bd628); + assertEquals("getBigInteger() returned incorrect result;", bd628, cache.getBigDecimal("/number")); + + BigDecimal bd1618 = new BigDecimal("1.618"); + cache.set("/object/nestedNumber", bd1618); + assertEquals("nested getBigInteger() returned incorrect result;", bd1618, + cache.getBigDecimal("/object/nestedNumber")); + + assertTrue("cache should be dirty after BigDecimal writes;", root.isDirty()); + } + + @Test + public void testSetBigInteger() throws Exception { + BigInteger bi4 = new BigInteger("4"); + cache.set("/number", bi4); + assertEquals("getBigInteger() returned incorrect result;", bi4, cache.getBigInteger("/number")); + + BigInteger bi6 = new BigInteger("6"); + cache.set("/object/nestedNumber", bi6); + assertEquals("nested getBigInteger() returned incorrect result;", bi6, + cache.getBigInteger("/object/nestedNumber")); + + assertTrue("cache should be dirty after BigInteger writes;", root.isDirty()); + } + + @Test + public void testSetBoolean() throws Exception { + cache.set("/boolean", false); + assertEquals("getBoolean returned incorrect result;", false, cache.getBoolean("/boolean")); + + cache.set("/object/nestedBoolean", false); + assertEquals("nested getBoolean returned incorrect result;", false, cache.getBoolean("/object/nestedBoolean")); + + assertTrue("cache should be dirty after boolean writes;", root.isDirty()); + } + + @Test + public void testSetDate() throws Exception { + Date date = new Date(); + cache.set("/dateTimeZ", date); + assertEquals("getDate() returned incorrect result;", date, cache.getObject("/dateTimeZ", Date.class)); + + cache.set("/object/nestedDateTimeZ", date); + assertEquals("nested getDate() returned incorrect result;", date, + cache.getObject("/object/nestedDateTimeZ", Date.class)); + + assertTrue("cache should be dirty after date writes;", root.isDirty()); + } + + private void testSetDate0(String dateStr, Object date) throws CacheException { + cache.set("/dateStr", dateStr); + assertEquals("getObject(\"/dateStr\", " + date.getClass().getName() + ".class) returned incorrect result;", + date, cache.getObject("/dateStr", date.getClass())); + cache.set("/date", date); + assertEquals("getObject(\"/date\", " + date.getClass().getName() + ".class) returned incorrect result;", + date, cache.getObject("/dateStr", date.getClass())); + assertTrue("cache should be dirty after date writes;", root.isDirty()); + } + + @Test + public void testSetDateTime310() throws Exception { + testSetDate0(DATETIME_OFFSET_STR, org.threeten.bp.OffsetDateTime.parse(DATETIME_OFFSET_STR)); + } + + @Test + public void testSetDateTimeJava8() throws Exception { + testSetDate0(DATETIME_OFFSET_STR, java.time.OffsetDateTime.parse(DATETIME_OFFSET_STR)); + } + + @Test + public void testSetDateTimeJoda() throws Exception { + testSetDate0(DATETIME_OFFSET_STR, org.joda.time.DateTime.parse(DATETIME_OFFSET_STR)); + } + + @Test + public void testSetDouble() throws Exception { + cache.set("/number", 6.28D); + assertEquals("getDouble() returned incorrect result;", 6.28D, cache.getDouble("/number"), Double.MIN_VALUE); + + cache.set("/object/nestedNumber", 1.618D); + assertEquals("nested getDouble() returned incorrect result;", 1.618D, cache.getDouble("/object/nestedNumber"), + Double.MIN_VALUE); + + assertTrue("cache should be dirty after double writes;", root.isDirty()); + } + + @Test + public void testSetFloat() throws Exception { + cache.set("/number", 6.28F); + assertEquals("getFloat() returned incorrect result;", 6.28F, cache.getFloat("/number"), Float.MIN_VALUE); + + cache.set("/object/nestedNumber", 1.618F); + assertEquals("nested getFloat() returned incorrect result;", 1.618F, cache.getFloat("/object/nestedNumber"), + Float.MIN_VALUE); + + assertTrue("cache should be dirty after float writes;", root.isDirty()); + } + + @Test + public void testSetInt() throws Exception { + cache.set("/number", 23); + assertEquals("getInt() returned incorrect result;", 23, cache.getInt("/number")); + + cache.set("/object/nestedNumber", 22); + assertEquals("nested getInt() returned incorrect result;", 22, cache.getInt("/object/nestedNumber")); + + assertTrue("cache should be dirty after integer writes;", root.isDirty()); + } + + @Test + public void testSetLocalDate310() throws Exception { + testSetDate0(DATE_STR, org.threeten.bp.LocalDate.parse(DATE_STR)); + } + + @Test + public void testSetLocalDateJava8() throws Exception { + testSetDate0(DATE_STR, java.time.LocalDate.parse(DATE_STR)); + } + + @Test + public void testSetLocalDateJoda() throws Exception { + testSetDate0(DATE_STR, org.joda.time.LocalDate.parse(DATE_STR)); + } + + @Test + public void testSetLong() throws Exception { + cache.set("/number", 33L); + assertEquals("getLong() returned incorrect result;", 33L, cache.getLong("/number")); + + cache.set("/object/nestedNumber", 32L); + assertEquals("nested getLong() returned incorrect result;", 32L, cache.getLong("/object/nestedNumber")); + + assertTrue("cache should be dirty after long writes;", root.isDirty()); + } + + @Test + public void testSetNumber() throws Exception { + cache.set("/number", 6.28F); + assertEquals("getNumber() returned incorrect result;", 6.28F, cache.getNumber("/number")); + + cache.set("/object/nestedNumber", 1.618D); + assertEquals("nested getNumber() returned incorrect result;", 1.618D, cache.getNumber("/object/nestedNumber")); + + assertTrue("cache should be dirty after number writes;", root.isDirty()); + } + + @Test + public void testSetObject() throws Exception { + cache.set("/testObjects/0", TEST_OBJECT_1); + TestObject testObject0 = cache.getObject("/testObjects/0", TestObject.class); + assertSame("test object 0 was not set correctly", TEST_OBJECT_1, testObject0); + assertNull("POJO field did not return null;", cache.get("/testObjects/0/booleanField")); + + cache.set("/testObjects/1", TEST_OBJECT_0); + TestObject testObject1 = cache.getObject("/testObjects/1", TestObject.class); + assertSame("test object 1 was not deserialized correctly", TEST_OBJECT_0, testObject1); + assertNull("POJO field did not return null;", cache.get("/testObjects/1/stringField")); + + cache.set("/boolean", Boolean.FALSE); + assertEquals("set(Boolean) did not work;", false, cache.getBoolean("/boolean")); + + cache.set("/number", Integer.valueOf(666)); + assertEquals("set(Integer) did not work;", 666, cache.getInt("/number")); + + cache.set("/string", (Object) "a replacement string"); + assertEquals("set(Object) did not work;", "a replacement string", cache.getString("/string")); + + // TODO: should we be able to set ArrayNode and ObjectNode values in this fashion? + + assertTrue("cache should be dirty after object writes;", root.isDirty()); + } + + @Test + public void testSetObjects() throws Exception { + List testObjects = Arrays.asList(TEST_OBJECT_1, TEST_OBJECT_0); + cache.set("/testObjects", testObjects); + List result = cache.getObjects("/testObjects", TestObject.class); + assertEquals("set(path, list) did not work", testObjects, result); + assertTrue("cache should be dirty after set(path, list);", root.isDirty()); + } + + @Test + public void testSetShort() throws Exception { + cache.set("/number", 13); + assertEquals("getShort() returned incorrect result;", 13, cache.getShort("/number")); + + cache.set("/object/nestedNumber", 12); + assertEquals("nested getShort() returned incorrect result;", 12, cache.getShort("/object/nestedNumber")); + + assertTrue("cache should be dirty after short writes;", root.isDirty()); + } + + @Test + public void testSetString() throws Exception { + cache.set("/string", "a different string"); + assertEquals("getString returned incorrect result;", "a different string", cache.getString("/string")); + + cache.set("/object/nestedString", "a different nested string"); + assertEquals("nested getString returned incorrect result;", "a different nested string", + cache.getString("/object/nestedString")); + + assertTrue("cache should be dirty after string writes;", root.isDirty()); + } + + @Test + public void testSetWithMissingAncestors() throws Exception { + JsonPointer ptr = JsonPointer.compile("/nonExistentArray/0/nonExistentObject/stringProperty"); + assertFalse("exists(ptr) returned incorrect value;", cache.exists(ptr)); + Object value = cache.get(ptr); + assertNull("stringProperty is non-null;", value); + cache.set(ptr, "string value"); + assertTrue("exists(ptr) returned incorrect value;", cache.exists(ptr)); + value = cache.get(ptr); + assertEquals("stringProperty is null after being set;", "string value", value); + } + + // TODO: get/set POJO +} diff --git a/samples/client/petstore/jaxrs-cxf-client/pom.xml b/samples/client/petstore/jaxrs-cxf-client/pom.xml index 9ac884ccb1a..ee6920b9a5e 100644 --- a/samples/client/petstore/jaxrs-cxf-client/pom.xml +++ b/samples/client/petstore/jaxrs-cxf-client/pom.xml @@ -1,10 +1,10 @@ 4.0.0 - io.swagger + org.openapitools jaxrs-cxf-petstore-client jar jaxrs-cxf-petstore-client - This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. 1.0.0 src/main/java diff --git a/samples/client/petstore/jaxrs-cxf-client/src/gen/java/org/openapitools/api/PetApi.java b/samples/client/petstore/jaxrs-cxf-client/src/gen/java/org/openapitools/api/PetApi.java index 1b11560839e..72df7daef99 100644 --- a/samples/client/petstore/jaxrs-cxf-client/src/gen/java/org/openapitools/api/PetApi.java +++ b/samples/client/petstore/jaxrs-cxf-client/src/gen/java/org/openapitools/api/PetApi.java @@ -39,7 +39,7 @@ public interface PetApi { @ApiOperation(value = "Add a new pet to the store", tags={ }) @ApiResponses(value = { @ApiResponse(code = 405, message = "Invalid input") }) - public void addPet(Pet pet); + public void addPet(Pet body); /** * Deletes a pet @@ -110,7 +110,7 @@ public interface PetApi { @ApiResponse(code = 400, message = "Invalid ID supplied"), @ApiResponse(code = 404, message = "Pet not found"), @ApiResponse(code = 405, message = "Validation exception") }) - public void updatePet(Pet pet); + public void updatePet(Pet body); /** * Updates a pet in the store with form data diff --git a/samples/client/petstore/jaxrs-cxf-client/src/gen/java/org/openapitools/api/StoreApi.java b/samples/client/petstore/jaxrs-cxf-client/src/gen/java/org/openapitools/api/StoreApi.java index c7f39237b11..f335bf43c6b 100644 --- a/samples/client/petstore/jaxrs-cxf-client/src/gen/java/org/openapitools/api/StoreApi.java +++ b/samples/client/petstore/jaxrs-cxf-client/src/gen/java/org/openapitools/api/StoreApi.java @@ -82,6 +82,6 @@ public interface StoreApi { @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Order.class), @ApiResponse(code = 400, message = "Invalid Order") }) - public Order placeOrder(Order order); + public Order placeOrder(Order body); } diff --git a/samples/client/petstore/jaxrs-cxf-client/src/gen/java/org/openapitools/api/UserApi.java b/samples/client/petstore/jaxrs-cxf-client/src/gen/java/org/openapitools/api/UserApi.java index 9d10f9c8c12..eb14a63a71b 100644 --- a/samples/client/petstore/jaxrs-cxf-client/src/gen/java/org/openapitools/api/UserApi.java +++ b/samples/client/petstore/jaxrs-cxf-client/src/gen/java/org/openapitools/api/UserApi.java @@ -38,7 +38,7 @@ public interface UserApi { @ApiOperation(value = "Create user", tags={ }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation") }) - public void createUser(User user); + public void createUser(User body); /** * Creates list of users with given input array @@ -49,7 +49,7 @@ public interface UserApi { @ApiOperation(value = "Creates list of users with given input array", tags={ }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation") }) - public void createUsersWithArrayInput(List user); + public void createUsersWithArrayInput(List body); /** * Creates list of users with given input array @@ -60,7 +60,7 @@ public interface UserApi { @ApiOperation(value = "Creates list of users with given input array", tags={ }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation") }) - public void createUsersWithListInput(List user); + public void createUsersWithListInput(List body); /** * Delete user @@ -126,6 +126,6 @@ public interface UserApi { @ApiResponses(value = { @ApiResponse(code = 400, message = "Invalid user supplied"), @ApiResponse(code = 404, message = "User not found") }) - public void updateUser(@PathParam("username") String username, User user); + public void updateUser(@PathParam("username") String username, User body); } diff --git a/samples/client/petstore/jaxrs-cxf-client/src/test/java/org/openapitools/api/PetApiTest.java b/samples/client/petstore/jaxrs-cxf-client/src/test/java/org/openapitools/api/PetApiTest.java index 105d7c18847..4f3509f5d61 100644 --- a/samples/client/petstore/jaxrs-cxf-client/src/test/java/org/openapitools/api/PetApiTest.java +++ b/samples/client/petstore/jaxrs-cxf-client/src/test/java/org/openapitools/api/PetApiTest.java @@ -1,12 +1,12 @@ /** - * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * 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. * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech * Do not edit the class manually. * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -49,9 +49,9 @@ import java.util.Map; /** - * Swagger Petstore + * OpenAPI Petstore * - *

This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + *

This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. * * API tests for PetApi */ @@ -81,8 +81,8 @@ public class PetApiTest { */ @Test public void addPetTest() { - Pet pet = null; - //api.addPet(pet); + Pet body = null; + //api.addPet(body); // TODO: test validations @@ -168,8 +168,8 @@ public class PetApiTest { */ @Test public void updatePetTest() { - Pet pet = null; - //api.updatePet(pet); + Pet body = null; + //api.updatePet(body); // TODO: test validations diff --git a/samples/client/petstore/jaxrs-cxf-client/src/test/java/org/openapitools/api/StoreApiTest.java b/samples/client/petstore/jaxrs-cxf-client/src/test/java/org/openapitools/api/StoreApiTest.java index 26ef4dc7d5e..2cd04cd9aa2 100644 --- a/samples/client/petstore/jaxrs-cxf-client/src/test/java/org/openapitools/api/StoreApiTest.java +++ b/samples/client/petstore/jaxrs-cxf-client/src/test/java/org/openapitools/api/StoreApiTest.java @@ -1,12 +1,12 @@ /** - * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * 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. * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech * Do not edit the class manually. * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -47,9 +47,9 @@ import java.util.Map; /** - * Swagger Petstore + * OpenAPI Petstore * - *

This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + *

This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. * * API tests for StoreApi */ @@ -132,8 +132,8 @@ public class StoreApiTest { */ @Test public void placeOrderTest() { - Order order = null; - //Order response = api.placeOrder(order); + Order body = null; + //Order response = api.placeOrder(body); //assertNotNull(response); // TODO: test validations diff --git a/samples/client/petstore/jaxrs-cxf-client/src/test/java/org/openapitools/api/UserApiTest.java b/samples/client/petstore/jaxrs-cxf-client/src/test/java/org/openapitools/api/UserApiTest.java index bb9eab21deb..1d1c98f8f26 100644 --- a/samples/client/petstore/jaxrs-cxf-client/src/test/java/org/openapitools/api/UserApiTest.java +++ b/samples/client/petstore/jaxrs-cxf-client/src/test/java/org/openapitools/api/UserApiTest.java @@ -1,12 +1,12 @@ /** - * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * 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. * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech * Do not edit the class manually. * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -47,9 +47,9 @@ import java.util.Map; /** - * Swagger Petstore + * OpenAPI Petstore * - *

This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + *

This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. * * API tests for UserApi */ @@ -81,8 +81,8 @@ public class UserApiTest { */ @Test public void createUserTest() { - User user = null; - //api.createUser(user); + User body = null; + //api.createUser(body); // TODO: test validations @@ -97,8 +97,8 @@ public class UserApiTest { */ @Test public void createUsersWithArrayInputTest() { - List user = null; - //api.createUsersWithArrayInput(user); + List body = null; + //api.createUsersWithArrayInput(body); // TODO: test validations @@ -113,8 +113,8 @@ public class UserApiTest { */ @Test public void createUsersWithListInputTest() { - List user = null; - //api.createUsersWithListInput(user); + List body = null; + //api.createUsersWithListInput(body); // TODO: test validations @@ -198,8 +198,8 @@ public class UserApiTest { @Test public void updateUserTest() { String username = null; - User user = null; - //api.updateUser(username, user); + User body = null; + //api.updateUser(username, body); // TODO: test validations diff --git a/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/main/java/org/openapitools/api/impl/PetApiServiceImpl.java b/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/main/java/org/openapitools/api/impl/PetApiServiceImpl.java index 4ec7eaee91a..d8244b0f2e0 100644 --- a/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/main/java/org/openapitools/api/impl/PetApiServiceImpl.java +++ b/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/main/java/org/openapitools/api/impl/PetApiServiceImpl.java @@ -29,7 +29,7 @@ public class PetApiServiceImpl implements PetApi { * Add a new pet to the store * */ - public void addPet(Pet pet) { + public void addPet(Pet body) { // TODO: Implement... @@ -85,7 +85,7 @@ public class PetApiServiceImpl implements PetApi { * Update an existing pet * */ - public void updatePet(Pet pet) { + public void updatePet(Pet body) { // TODO: Implement... diff --git a/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/main/java/org/openapitools/api/impl/StoreApiServiceImpl.java b/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/main/java/org/openapitools/api/impl/StoreApiServiceImpl.java index 701a00e583f..3944d1fd04a 100644 --- a/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/main/java/org/openapitools/api/impl/StoreApiServiceImpl.java +++ b/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/main/java/org/openapitools/api/impl/StoreApiServiceImpl.java @@ -64,7 +64,7 @@ public class StoreApiServiceImpl implements StoreApi { * Place an order for a pet * */ - public Order placeOrder(Order order) { + public Order placeOrder(Order body) { // TODO: Implement... return null; diff --git a/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/main/java/org/openapitools/api/impl/UserApiServiceImpl.java b/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/main/java/org/openapitools/api/impl/UserApiServiceImpl.java index 1533b764244..df7f07ecdfb 100644 --- a/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/main/java/org/openapitools/api/impl/UserApiServiceImpl.java +++ b/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/main/java/org/openapitools/api/impl/UserApiServiceImpl.java @@ -30,7 +30,7 @@ public class UserApiServiceImpl implements UserApi { * This can only be done by the logged in user. * */ - public void createUser(User user) { + public void createUser(User body) { // TODO: Implement... @@ -40,7 +40,7 @@ public class UserApiServiceImpl implements UserApi { * Creates list of users with given input array * */ - public void createUsersWithArrayInput(List user) { + public void createUsersWithArrayInput(List body) { // TODO: Implement... @@ -50,7 +50,7 @@ public class UserApiServiceImpl implements UserApi { * Creates list of users with given input array * */ - public void createUsersWithListInput(List user) { + public void createUsersWithListInput(List body) { // TODO: Implement... @@ -104,7 +104,7 @@ public class UserApiServiceImpl implements UserApi { * This can only be done by the logged in user. * */ - public void updateUser(String username, User user) { + public void updateUser(String username, User body) { // TODO: Implement... diff --git a/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/test/java/org/openapitools/api/PetApiTest.java b/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/test/java/org/openapitools/api/PetApiTest.java index 105d7c18847..4f3509f5d61 100644 --- a/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/test/java/org/openapitools/api/PetApiTest.java +++ b/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/test/java/org/openapitools/api/PetApiTest.java @@ -1,12 +1,12 @@ /** - * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * 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. * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech * Do not edit the class manually. * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -49,9 +49,9 @@ import java.util.Map; /** - * Swagger Petstore + * OpenAPI Petstore * - *

This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + *

This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. * * API tests for PetApi */ @@ -81,8 +81,8 @@ public class PetApiTest { */ @Test public void addPetTest() { - Pet pet = null; - //api.addPet(pet); + Pet body = null; + //api.addPet(body); // TODO: test validations @@ -168,8 +168,8 @@ public class PetApiTest { */ @Test public void updatePetTest() { - Pet pet = null; - //api.updatePet(pet); + Pet body = null; + //api.updatePet(body); // TODO: test validations diff --git a/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/test/java/org/openapitools/api/StoreApiTest.java b/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/test/java/org/openapitools/api/StoreApiTest.java index 994ccedd71d..1f7a1dd303a 100644 --- a/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/test/java/org/openapitools/api/StoreApiTest.java +++ b/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/test/java/org/openapitools/api/StoreApiTest.java @@ -1,12 +1,12 @@ /** - * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * 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. * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech * Do not edit the class manually. * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -48,9 +48,9 @@ import java.util.Map; /** - * Swagger Petstore + * OpenAPI Petstore * - *

This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + *

This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. * * API tests for StoreApi */ @@ -133,8 +133,8 @@ public class StoreApiTest { */ @Test public void placeOrderTest() { - Order order = null; - //Order response = api.placeOrder(order); + Order body = null; + //Order response = api.placeOrder(body); //assertNotNull(response); // TODO: test validations diff --git a/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/test/java/org/openapitools/api/UserApiTest.java b/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/test/java/org/openapitools/api/UserApiTest.java index d3fcb9f0f22..da2bd154e03 100644 --- a/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/test/java/org/openapitools/api/UserApiTest.java +++ b/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/test/java/org/openapitools/api/UserApiTest.java @@ -1,12 +1,12 @@ /** - * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * 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. * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech * Do not edit the class manually. * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -48,9 +48,9 @@ import java.util.Map; /** - * Swagger Petstore + * OpenAPI Petstore * - *

This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + *

This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. * * API tests for UserApi */ @@ -82,8 +82,8 @@ public class UserApiTest { */ @Test public void createUserTest() { - User user = null; - //api.createUser(user); + User body = null; + //api.createUser(body); // TODO: test validations @@ -98,8 +98,8 @@ public class UserApiTest { */ @Test public void createUsersWithArrayInputTest() { - List user = null; - //api.createUsersWithArrayInput(user); + List body = null; + //api.createUsersWithArrayInput(body); // TODO: test validations @@ -114,8 +114,8 @@ public class UserApiTest { */ @Test public void createUsersWithListInputTest() { - List user = null; - //api.createUsersWithListInput(user); + List body = null; + //api.createUsersWithListInput(body); // TODO: test validations @@ -199,8 +199,8 @@ public class UserApiTest { @Test public void updateUserTest() { String username = null; - User user = null; - //api.updateUser(username, user); + User body = null; + //api.updateUser(username, body); // TODO: test validations diff --git a/samples/server/petstore/jaxrs-cxf-non-spring-app/src/main/java/org/openapitools/api/impl/PetApiServiceImpl.java b/samples/server/petstore/jaxrs-cxf-non-spring-app/src/main/java/org/openapitools/api/impl/PetApiServiceImpl.java index 4ec7eaee91a..d8244b0f2e0 100644 --- a/samples/server/petstore/jaxrs-cxf-non-spring-app/src/main/java/org/openapitools/api/impl/PetApiServiceImpl.java +++ b/samples/server/petstore/jaxrs-cxf-non-spring-app/src/main/java/org/openapitools/api/impl/PetApiServiceImpl.java @@ -29,7 +29,7 @@ public class PetApiServiceImpl implements PetApi { * Add a new pet to the store * */ - public void addPet(Pet pet) { + public void addPet(Pet body) { // TODO: Implement... @@ -85,7 +85,7 @@ public class PetApiServiceImpl implements PetApi { * Update an existing pet * */ - public void updatePet(Pet pet) { + public void updatePet(Pet body) { // TODO: Implement... diff --git a/samples/server/petstore/jaxrs-cxf-non-spring-app/src/main/java/org/openapitools/api/impl/StoreApiServiceImpl.java b/samples/server/petstore/jaxrs-cxf-non-spring-app/src/main/java/org/openapitools/api/impl/StoreApiServiceImpl.java index 701a00e583f..3944d1fd04a 100644 --- a/samples/server/petstore/jaxrs-cxf-non-spring-app/src/main/java/org/openapitools/api/impl/StoreApiServiceImpl.java +++ b/samples/server/petstore/jaxrs-cxf-non-spring-app/src/main/java/org/openapitools/api/impl/StoreApiServiceImpl.java @@ -64,7 +64,7 @@ public class StoreApiServiceImpl implements StoreApi { * Place an order for a pet * */ - public Order placeOrder(Order order) { + public Order placeOrder(Order body) { // TODO: Implement... return null; diff --git a/samples/server/petstore/jaxrs-cxf-non-spring-app/src/main/java/org/openapitools/api/impl/UserApiServiceImpl.java b/samples/server/petstore/jaxrs-cxf-non-spring-app/src/main/java/org/openapitools/api/impl/UserApiServiceImpl.java index 1533b764244..df7f07ecdfb 100644 --- a/samples/server/petstore/jaxrs-cxf-non-spring-app/src/main/java/org/openapitools/api/impl/UserApiServiceImpl.java +++ b/samples/server/petstore/jaxrs-cxf-non-spring-app/src/main/java/org/openapitools/api/impl/UserApiServiceImpl.java @@ -30,7 +30,7 @@ public class UserApiServiceImpl implements UserApi { * This can only be done by the logged in user. * */ - public void createUser(User user) { + public void createUser(User body) { // TODO: Implement... @@ -40,7 +40,7 @@ public class UserApiServiceImpl implements UserApi { * Creates list of users with given input array * */ - public void createUsersWithArrayInput(List user) { + public void createUsersWithArrayInput(List body) { // TODO: Implement... @@ -50,7 +50,7 @@ public class UserApiServiceImpl implements UserApi { * Creates list of users with given input array * */ - public void createUsersWithListInput(List user) { + public void createUsersWithListInput(List body) { // TODO: Implement... @@ -104,7 +104,7 @@ public class UserApiServiceImpl implements UserApi { * This can only be done by the logged in user. * */ - public void updateUser(String username, User user) { + public void updateUser(String username, User body) { // TODO: Implement... diff --git a/samples/server/petstore/jaxrs-cxf-non-spring-app/src/test/java/org/openapitools/api/PetApiTest.java b/samples/server/petstore/jaxrs-cxf-non-spring-app/src/test/java/org/openapitools/api/PetApiTest.java index 105d7c18847..4f3509f5d61 100644 --- a/samples/server/petstore/jaxrs-cxf-non-spring-app/src/test/java/org/openapitools/api/PetApiTest.java +++ b/samples/server/petstore/jaxrs-cxf-non-spring-app/src/test/java/org/openapitools/api/PetApiTest.java @@ -1,12 +1,12 @@ /** - * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * 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. * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech * Do not edit the class manually. * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -49,9 +49,9 @@ import java.util.Map; /** - * Swagger Petstore + * OpenAPI Petstore * - *

This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + *

This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. * * API tests for PetApi */ @@ -81,8 +81,8 @@ public class PetApiTest { */ @Test public void addPetTest() { - Pet pet = null; - //api.addPet(pet); + Pet body = null; + //api.addPet(body); // TODO: test validations @@ -168,8 +168,8 @@ public class PetApiTest { */ @Test public void updatePetTest() { - Pet pet = null; - //api.updatePet(pet); + Pet body = null; + //api.updatePet(body); // TODO: test validations diff --git a/samples/server/petstore/jaxrs-cxf-non-spring-app/src/test/java/org/openapitools/api/StoreApiTest.java b/samples/server/petstore/jaxrs-cxf-non-spring-app/src/test/java/org/openapitools/api/StoreApiTest.java index 994ccedd71d..1f7a1dd303a 100644 --- a/samples/server/petstore/jaxrs-cxf-non-spring-app/src/test/java/org/openapitools/api/StoreApiTest.java +++ b/samples/server/petstore/jaxrs-cxf-non-spring-app/src/test/java/org/openapitools/api/StoreApiTest.java @@ -1,12 +1,12 @@ /** - * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * 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. * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech * Do not edit the class manually. * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -48,9 +48,9 @@ import java.util.Map; /** - * Swagger Petstore + * OpenAPI Petstore * - *

This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + *

This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. * * API tests for StoreApi */ @@ -133,8 +133,8 @@ public class StoreApiTest { */ @Test public void placeOrderTest() { - Order order = null; - //Order response = api.placeOrder(order); + Order body = null; + //Order response = api.placeOrder(body); //assertNotNull(response); // TODO: test validations diff --git a/samples/server/petstore/jaxrs-cxf-non-spring-app/src/test/java/org/openapitools/api/UserApiTest.java b/samples/server/petstore/jaxrs-cxf-non-spring-app/src/test/java/org/openapitools/api/UserApiTest.java index d3fcb9f0f22..da2bd154e03 100644 --- a/samples/server/petstore/jaxrs-cxf-non-spring-app/src/test/java/org/openapitools/api/UserApiTest.java +++ b/samples/server/petstore/jaxrs-cxf-non-spring-app/src/test/java/org/openapitools/api/UserApiTest.java @@ -1,12 +1,12 @@ /** - * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * 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. * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech * Do not edit the class manually. * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -48,9 +48,9 @@ import java.util.Map; /** - * Swagger Petstore + * OpenAPI Petstore * - *

This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + *

This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. * * API tests for UserApi */ @@ -82,8 +82,8 @@ public class UserApiTest { */ @Test public void createUserTest() { - User user = null; - //api.createUser(user); + User body = null; + //api.createUser(body); // TODO: test validations @@ -98,8 +98,8 @@ public class UserApiTest { */ @Test public void createUsersWithArrayInputTest() { - List user = null; - //api.createUsersWithArrayInput(user); + List body = null; + //api.createUsersWithArrayInput(body); // TODO: test validations @@ -114,8 +114,8 @@ public class UserApiTest { */ @Test public void createUsersWithListInputTest() { - List user = null; - //api.createUsersWithListInput(user); + List body = null; + //api.createUsersWithListInput(body); // TODO: test validations @@ -199,8 +199,8 @@ public class UserApiTest { @Test public void updateUserTest() { String username = null; - User user = null; - //api.updateUser(username, user); + User body = null; + //api.updateUser(username, body); // TODO: test validations diff --git a/samples/server/petstore/jaxrs-cxf-test-data/.openapi-generator-ignore b/samples/server/petstore/jaxrs-cxf-test-data/.openapi-generator-ignore new file mode 100644 index 00000000000..79b4220e7e1 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-test-data/.openapi-generator-ignore @@ -0,0 +1,25 @@ +# 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 + +#**/impl/* diff --git a/samples/server/petstore/jaxrs-cxf-test-data/.openapi-generator/VERSION b/samples/server/petstore/jaxrs-cxf-test-data/.openapi-generator/VERSION new file mode 100644 index 00000000000..afa63656064 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-test-data/.openapi-generator/VERSION @@ -0,0 +1 @@ +4.0.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/jaxrs-cxf-test-data/pom.xml b/samples/server/petstore/jaxrs-cxf-test-data/pom.xml new file mode 100644 index 00000000000..9cc072a0753 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-test-data/pom.xml @@ -0,0 +1,266 @@ + + 4.0.0 + org.openapitools + jaxrs-cxf-petstore-server-test-data + war + jaxrs-cxf-petstore-server-test-data + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + 1.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.0.4.RELEASE + + + src/main/java + + + maven-failsafe-plugin + + + + integration-test + verify + + + + + + + org.codehaus.mojo + build-helper-maven-plugin + + + add-source + generate-sources + + add-source + + + + src/gen/java + + + + + + + + + maven-war-plugin + + false + + + + + + + io.swagger + swagger-jaxrs + compile + ${swagger-core-version} + + + javax.ws.rs + jsr311-api + + + + + ch.qos.logback + logback-classic + compile + + + ch.qos.logback + logback-core + compile + + + junit + junit + test + + + + javax.validation + validation-api + provided + + + + org.apache.cxf + cxf-rt-rs-client + ${cxf-version} + test + + + + org.apache.cxf + cxf-rt-frontend-jaxrs + ${cxf-version} + compile + + + org.apache.cxf + cxf-rt-rs-service-description + ${cxf-version} + compile + + + org.apache.cxf + cxf-rt-rs-service-description-swagger + ${cxf-version} + compile + + + org.apache.cxf + cxf-rt-ws-policy + ${cxf-version} + compile + + + org.apache.cxf + cxf-rt-wsdl + ${cxf-version} + compile + + + + com.fasterxml.jackson.jaxrs + jackson-jaxrs-json-provider + compile + + + com.fasterxml.jackson.jaxrs + jackson-jaxrs-xml-provider + compile + + + com.fasterxml.jackson.datatype + jackson-datatype-jsr310 + + + + org.springframework + spring-core + + + org.springframework + spring-aop + + + org.springframework + spring-context + + + org.springframework + spring-web + + + + + org.springframework.boot + spring-boot + + + org.springframework.boot + spring-boot-autoconfigure + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-test + test + + + org.apache.cxf + cxf-spring-boot-starter-jaxrs + ${cxf-version} + provided + + + org.openapitools + openapi-generator + 4.0.0-SNAPSHOT + + + + + sonatype-snapshots + https://oss.sonatype.org/content/repositories/snapshots + + true + + + + sonatype-releases + https://oss.sonatype.org/content/repositories/releases + + false + + + + + 1.8 + ${java.version} + ${java.version} + 1.5.18 + 9.2.9.v20150224 + 1.1.0.Final + 3.3.0 + 2.9.8 + UTF-8 + + diff --git a/samples/server/petstore/jaxrs-cxf-test-data/readme.md b/samples/server/petstore/jaxrs-cxf-test-data/readme.md new file mode 100644 index 00000000000..60afd53a0df --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-test-data/readme.md @@ -0,0 +1,36 @@ + +# JAX-RS CXF 3 server application + +## Supported features +* Bean-Validation-API support +* Spring-configuration of Swagger, WADL and Endpoints +* Swagger-API is accessible (CXF3 Swagger2Feature) +* Swagger-UI can be included as Web-Jar automatically +* WADL is accessible (CXF WADL-Generator) +* Unit-tests include Gzip-Interceptors for demonstration + + +## Urls to access the REST API +### Urls for Spring Boot + +* Available services listing +http://localhost:8080/ + +* Swagger API + http://localhost:8080/services/openapi.json + +* CXF WADL + http://localhost:8080/services?_wadl + + +### Urls if deployed to an AS +* Available services listing +http://localhost:8080/swagger-cxf-server/rest/services/ + +* Swagger API + http://localhost:8080/swagger-cxf-server/rest/services/swagger.json + +* CXF WADL + http://localhost:8080/swagger-cxf-server/rest/services?_wadl + + diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/api/AnotherFakeApi.java b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/api/AnotherFakeApi.java new file mode 100644 index 00000000000..c9d76b80ce6 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/api/AnotherFakeApi.java @@ -0,0 +1,49 @@ +package org.openapitools.api; + +import org.openapitools.model.Client; +import java.util.List; +import java.util.Map; + +import java.io.InputStream; +import java.io.OutputStream; +import java.util.List; +import java.util.Map; +import javax.ws.rs.*; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.MediaType; +import org.apache.cxf.jaxrs.ext.multipart.*; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiResponses; +import io.swagger.annotations.ApiResponse; +import io.swagger.jaxrs.PATCH; +import javax.validation.constraints.*; +import javax.validation.Valid; + +/** + * 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: \" \\ + * + */ +@Path("/v2") +@Api(value = "/", description = "") +public interface AnotherFakeApi { + + /** + * To test special tags + * + * To test special tags and operation ID starting with number + * + */ + @PATCH + @Path("/another-fake/dummy") + @Consumes({ "application/json" }) + @Produces({ "application/json" }) + @ApiOperation(value = "To test special tags", tags={ "$another-fake?" }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Client.class) }) + public Client call123testSpecialTags(@Valid Client body); +} + diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/api/FakeApi.java b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/api/FakeApi.java new file mode 100644 index 00000000000..34d3f595cbd --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/api/FakeApi.java @@ -0,0 +1,190 @@ +package org.openapitools.api; + +import java.math.BigDecimal; +import org.openapitools.model.Client; +import java.util.Date; +import java.io.File; +import org.openapitools.model.FileSchemaTestClass; +import java.util.List; +import org.joda.time.LocalDate; +import java.util.Map; +import org.openapitools.model.OuterComposite; +import org.openapitools.model.User; +import org.openapitools.model.XmlItem; + +import java.io.InputStream; +import java.io.OutputStream; +import java.util.List; +import java.util.Map; +import javax.ws.rs.*; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.MediaType; +import org.apache.cxf.jaxrs.ext.multipart.*; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiResponses; +import io.swagger.annotations.ApiResponse; +import io.swagger.jaxrs.PATCH; +import javax.validation.constraints.*; +import javax.validation.Valid; + +/** + * 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: \" \\ + * + */ +@Path("/v2") +@Api(value = "/", description = "") +public interface FakeApi { + + /** + * creates an XmlItem + * + * this route creates an XmlItem + * + */ + @POST + @Path("/fake/create_xml_item") + @Consumes({ "application/xml", "application/xml; charset=utf-8", "application/xml; charset=utf-16", "text/xml", "text/xml; charset=utf-8", "text/xml; charset=utf-16" }) + @ApiOperation(value = "creates an XmlItem", tags={ "fake", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation") }) + public void createXmlItem(@Valid XmlItem xmlItem); + + @POST + @Path("/fake/outer/boolean") + @Consumes({ "text/plain" }) + @Produces({ "*/*" }) + @ApiOperation(value = "", tags={ "fake", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "Output boolean", response = Boolean.class) }) + public Boolean fakeOuterBooleanSerialize(@Valid Boolean body); + + @POST + @Path("/fake/outer/composite") + @Consumes({ "application/json" }) + @Produces({ "*/*" }) + @ApiOperation(value = "", tags={ "fake", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "Output composite", response = OuterComposite.class) }) + public OuterComposite fakeOuterCompositeSerialize(@Valid OuterComposite body); + + @POST + @Path("/fake/outer/number") + @Consumes({ "application/json" }) + @Produces({ "*/*" }) + @ApiOperation(value = "", tags={ "fake", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "Output number", response = BigDecimal.class) }) + public BigDecimal fakeOuterNumberSerialize(@Valid BigDecimal body); + + @POST + @Path("/fake/outer/string") + @Consumes({ "text/plain" }) + @Produces({ "*/*" }) + @ApiOperation(value = "", tags={ "fake", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "Output string", response = String.class) }) + public String fakeOuterStringSerialize(@Valid String body); + + @PUT + @Path("/fake/body-with-file-schema") + @Consumes({ "application/json" }) + @ApiOperation(value = "", tags={ "fake", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "Success") }) + public void testBodyWithFileSchema(@Valid FileSchemaTestClass body); + + @PUT + @Path("/fake/body-with-query-params") + @Consumes({ "application/json" }) + @ApiOperation(value = "", tags={ "fake", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "Success") }) + public void testBodyWithQueryParams(@QueryParam("query") @NotNull String query, @Valid User body); + + /** + * To test \"client\" model + * + * To test \"client\" model + * + */ + @PATCH + @Path("/fake") + @Consumes({ "application/json" }) + @Produces({ "application/json" }) + @ApiOperation(value = "To test \"client\" model", tags={ "fake", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Client.class) }) + public Client testClientModel(@Valid Client body); + + /** + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * + */ + @POST + @Path("/fake") + @Consumes({ "application/x-www-form-urlencoded" }) + @ApiOperation(value = "Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 ", tags={ "fake", }) + @ApiResponses(value = { + @ApiResponse(code = 400, message = "Invalid username supplied"), + @ApiResponse(code = 404, message = "User not found") }) + public void testEndpointParameters(@Multipart(value = "number") BigDecimal number, @Multipart(value = "double") Double _double, @Multipart(value = "pattern_without_delimiter") String patternWithoutDelimiter, @Multipart(value = "byte") byte[] _byte, @Multipart(value = "integer", required = false) Integer integer, @Multipart(value = "int32", required = false) Integer int32, @Multipart(value = "int64", required = false) Long int64, @Multipart(value = "float", required = false) Float _float, @Multipart(value = "string", required = false) String string, @Multipart(value = "binary" , required = false) Attachment binaryDetail, @Multipart(value = "date", required = false) LocalDate date, @Multipart(value = "dateTime", required = false) Date dateTime, @Multipart(value = "password", required = false) String password, @Multipart(value = "callback", required = false) String paramCallback); + + /** + * To test enum parameters + * + * To test enum parameters + * + */ + @GET + @Path("/fake") + @Consumes({ "application/x-www-form-urlencoded" }) + @ApiOperation(value = "To test enum parameters", tags={ "fake", }) + @ApiResponses(value = { + @ApiResponse(code = 400, message = "Invalid request"), + @ApiResponse(code = 404, message = "Not found") }) + public void testEnumParameters(@HeaderParam("enum_header_string_array") List enumHeaderStringArray, @HeaderParam("enum_header_string") String enumHeaderString, @QueryParam("enum_query_string_array") List enumQueryStringArray, @QueryParam("enum_query_string") @DefaultValue("-efg") String enumQueryString, @QueryParam("enum_query_integer") Integer enumQueryInteger, @QueryParam("enum_query_double") Double enumQueryDouble, @Multipart(value = "enum_form_string_array", required = false) List enumFormStringArray, @Multipart(value = "enum_form_string", required = false) String enumFormString); + + /** + * Fake endpoint to test group parameters (optional) + * + * Fake endpoint to test group parameters (optional) + * + */ + @DELETE + @Path("/fake") + @ApiOperation(value = "Fake endpoint to test group parameters (optional)", tags={ "fake", }) + @ApiResponses(value = { + @ApiResponse(code = 400, message = "Someting wrong") }) + public void testGroupParameters(@QueryParam("required_string_group") @NotNull Integer requiredStringGroup, @HeaderParam("required_boolean_group") @NotNull Boolean requiredBooleanGroup, @QueryParam("required_int64_group") @NotNull Long requiredInt64Group, @QueryParam("string_group") Integer stringGroup, @HeaderParam("boolean_group") Boolean booleanGroup, @QueryParam("int64_group") Long int64Group); + + /** + * test inline additionalProperties + * + */ + @POST + @Path("/fake/inline-additionalProperties") + @Consumes({ "application/json" }) + @ApiOperation(value = "test inline additionalProperties", tags={ "fake", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation") }) + public void testInlineAdditionalProperties(@Valid Map param); + + /** + * test json serialization of form data + * + */ + @GET + @Path("/fake/jsonFormData") + @Consumes({ "application/x-www-form-urlencoded" }) + @ApiOperation(value = "test json serialization of form data", tags={ "fake" }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation") }) + public void testJsonFormData(@Multipart(value = "param") String param, @Multipart(value = "param2") String param2); +} + diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/api/FakeClassnameTags123Api.java b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/api/FakeClassnameTags123Api.java new file mode 100644 index 00000000000..acfb963a5f8 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/api/FakeClassnameTags123Api.java @@ -0,0 +1,49 @@ +package org.openapitools.api; + +import org.openapitools.model.Client; +import java.util.List; +import java.util.Map; + +import java.io.InputStream; +import java.io.OutputStream; +import java.util.List; +import java.util.Map; +import javax.ws.rs.*; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.MediaType; +import org.apache.cxf.jaxrs.ext.multipart.*; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiResponses; +import io.swagger.annotations.ApiResponse; +import io.swagger.jaxrs.PATCH; +import javax.validation.constraints.*; +import javax.validation.Valid; + +/** + * 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: \" \\ + * + */ +@Path("/v2") +@Api(value = "/", description = "") +public interface FakeClassnameTags123Api { + + /** + * To test class name in snake case + * + * To test class name in snake case + * + */ + @PATCH + @Path("/fake_classname_test") + @Consumes({ "application/json" }) + @Produces({ "application/json" }) + @ApiOperation(value = "To test class name in snake case", tags={ "fake_classname_tags 123#$%^" }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Client.class) }) + public Client testClassname(@Valid Client body); +} + diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/api/PetApi.java b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/api/PetApi.java new file mode 100644 index 00000000000..6d593eaaf51 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/api/PetApi.java @@ -0,0 +1,158 @@ +package org.openapitools.api; + +import org.openapitools.model.Category; +import java.io.File; +import java.util.List; +import java.util.Map; +import org.openapitools.model.ModelApiResponse; +import org.openapitools.model.Pet; + +import java.io.InputStream; +import java.io.OutputStream; +import java.util.List; +import java.util.Map; +import javax.ws.rs.*; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.MediaType; +import org.apache.cxf.jaxrs.ext.multipart.*; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiResponses; +import io.swagger.annotations.ApiResponse; +import io.swagger.jaxrs.PATCH; +import javax.validation.constraints.*; +import javax.validation.Valid; + +/** + * 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: \" \\ + * + */ +@Path("/v2") +@Api(value = "/", description = "") +public interface PetApi { + + /** + * Add a new pet to the store + * + */ + @POST + @Path("/pet") + @Consumes({ "application/json", "application/xml" }) + @ApiOperation(value = "Add a new pet to the store", tags={ "pet", }) + @ApiResponses(value = { + @ApiResponse(code = 405, message = "Invalid input") }) + public void addPet(@Valid Pet body); + + /** + * Deletes a pet + * + */ + @DELETE + @Path("/pet/{petId}") + @ApiOperation(value = "Deletes a pet", tags={ "pet", }) + @ApiResponses(value = { + @ApiResponse(code = 400, message = "Invalid pet value") }) + public void deletePet(@PathParam("petId") Long petId, @HeaderParam("api_key") String apiKey); + + /** + * Finds Pets by status + * + * Multiple status values can be provided with comma separated strings + * + */ + @GET + @Path("/pet/findByStatus") + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Finds Pets by status", tags={ "pet", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Pet.class, responseContainer = "List"), + @ApiResponse(code = 400, message = "Invalid status value") }) + public List findPetsByStatus(@QueryParam("status") @NotNull List status); + + /** + * Finds Pets by tags + * + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * + */ + @GET + @Path("/pet/findByTags") + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Finds Pets by tags", tags={ "pet", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Pet.class, responseContainer = "List"), + @ApiResponse(code = 400, message = "Invalid tag value") }) + public List findPetsByTags(@QueryParam("tags") @NotNull List tags); + + /** + * Find pet by ID + * + * Returns a single pet + * + */ + @GET + @Path("/pet/{petId}") + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Find pet by ID", tags={ "pet", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Pet.class), + @ApiResponse(code = 400, message = "Invalid ID supplied"), + @ApiResponse(code = 404, message = "Pet not found") }) + public Pet getPetById(@PathParam("petId") Long petId); + + /** + * Update an existing pet + * + */ + @PUT + @Path("/pet") + @Consumes({ "application/json", "application/xml" }) + @ApiOperation(value = "Update an existing pet", tags={ "pet", }) + @ApiResponses(value = { + @ApiResponse(code = 400, message = "Invalid ID supplied"), + @ApiResponse(code = 404, message = "Pet not found"), + @ApiResponse(code = 405, message = "Validation exception") }) + public void updatePet(@Valid Pet body); + + /** + * Updates a pet in the store with form data + * + */ + @POST + @Path("/pet/{petId}") + @Consumes({ "application/x-www-form-urlencoded" }) + @ApiOperation(value = "Updates a pet in the store with form data", tags={ "pet", }) + @ApiResponses(value = { + @ApiResponse(code = 405, message = "Invalid input") }) + public void updatePetWithForm(@PathParam("petId") Long petId, @Multipart(value = "name", required = false) String name, @Multipart(value = "status", required = false) String status); + + /** + * uploads an image + * + */ + @POST + @Path("/pet/{petId}/uploadImage") + @Consumes({ "multipart/form-data" }) + @Produces({ "application/json" }) + @ApiOperation(value = "uploads an image", tags={ "pet", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = ModelApiResponse.class) }) + public ModelApiResponse uploadFile(@PathParam("petId") Long petId, @Multipart(value = "additionalMetadata", required = false) String additionalMetadata, @Multipart(value = "file" , required = false) Attachment fileDetail); + + /** + * uploads an image (required) + * + */ + @POST + @Path("/fake/{petId}/uploadImageWithRequiredFile") + @Consumes({ "multipart/form-data" }) + @Produces({ "application/json" }) + @ApiOperation(value = "uploads an image (required)", tags={ "pet" }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = ModelApiResponse.class) }) + public ModelApiResponse uploadFileWithRequiredFile(@PathParam("petId") Long petId, @Multipart(value = "requiredFile" ) Attachment requiredFileDetail, @Multipart(value = "additionalMetadata", required = false) String additionalMetadata); +} + diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/api/StoreApi.java b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/api/StoreApi.java new file mode 100644 index 00000000000..84a33a55d73 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/api/StoreApi.java @@ -0,0 +1,92 @@ +package org.openapitools.api; + +import java.util.List; +import java.util.Map; +import org.openapitools.model.Order; + +import java.io.InputStream; +import java.io.OutputStream; +import java.util.List; +import java.util.Map; +import javax.ws.rs.*; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.MediaType; +import org.apache.cxf.jaxrs.ext.multipart.*; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiResponses; +import io.swagger.annotations.ApiResponse; +import io.swagger.jaxrs.PATCH; +import javax.validation.constraints.*; +import javax.validation.Valid; + +/** + * 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: \" \\ + * + */ +@Path("/v2") +@Api(value = "/", description = "") +public interface StoreApi { + + /** + * Delete purchase order by ID + * + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * + */ + @DELETE + @Path("/store/order/{order_id}") + @ApiOperation(value = "Delete purchase order by ID", tags={ "store", }) + @ApiResponses(value = { + @ApiResponse(code = 400, message = "Invalid ID supplied"), + @ApiResponse(code = 404, message = "Order not found") }) + public void deleteOrder(@PathParam("order_id") String orderId); + + /** + * Returns pet inventories by status + * + * Returns a map of status codes to quantities + * + */ + @GET + @Path("/store/inventory") + @Produces({ "application/json" }) + @ApiOperation(value = "Returns pet inventories by status", tags={ "store", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Map.class, responseContainer = "Map") }) + public Map getInventory(); + + /** + * Find purchase order by ID + * + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * + */ + @GET + @Path("/store/order/{order_id}") + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Find purchase order by ID", tags={ "store", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Order.class), + @ApiResponse(code = 400, message = "Invalid ID supplied"), + @ApiResponse(code = 404, message = "Order not found") }) + public Order getOrderById(@PathParam("order_id") @Min(1L) @Max(5L) Long orderId); + + /** + * Place an order for a pet + * + */ + @POST + @Path("/store/order") + @Consumes({ "application/json" }) + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Place an order for a pet", tags={ "store" }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Order.class), + @ApiResponse(code = 400, message = "Invalid Order") }) + public Order placeOrder(@Valid Order body); +} + diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/api/UserApi.java b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/api/UserApi.java new file mode 100644 index 00000000000..995623db419 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/api/UserApi.java @@ -0,0 +1,139 @@ +package org.openapitools.api; + +import java.util.List; +import java.util.Map; +import org.openapitools.model.User; + +import java.io.InputStream; +import java.io.OutputStream; +import java.util.List; +import java.util.Map; +import javax.ws.rs.*; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.MediaType; +import org.apache.cxf.jaxrs.ext.multipart.*; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiResponses; +import io.swagger.annotations.ApiResponse; +import io.swagger.jaxrs.PATCH; +import javax.validation.constraints.*; +import javax.validation.Valid; + +/** + * 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: \" \\ + * + */ +@Path("/v2") +@Api(value = "/", description = "") +public interface UserApi { + + /** + * Create user + * + * This can only be done by the logged in user. + * + */ + @POST + @Path("/user") + @Consumes({ "application/json" }) + @ApiOperation(value = "Create user", tags={ "user", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation") }) + public void createUser(@Valid User body); + + /** + * Creates list of users with given input array + * + */ + @POST + @Path("/user/createWithArray") + @Consumes({ "application/json" }) + @ApiOperation(value = "Creates list of users with given input array", tags={ "user", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation") }) + public void createUsersWithArrayInput(@Valid List body); + + /** + * Creates list of users with given input array + * + */ + @POST + @Path("/user/createWithList") + @Consumes({ "application/json" }) + @ApiOperation(value = "Creates list of users with given input array", tags={ "user", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation") }) + public void createUsersWithListInput(@Valid List body); + + /** + * Delete user + * + * This can only be done by the logged in user. + * + */ + @DELETE + @Path("/user/{username}") + @ApiOperation(value = "Delete user", tags={ "user", }) + @ApiResponses(value = { + @ApiResponse(code = 400, message = "Invalid username supplied"), + @ApiResponse(code = 404, message = "User not found") }) + public void deleteUser(@PathParam("username") String username); + + /** + * Get user by user name + * + */ + @GET + @Path("/user/{username}") + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Get user by user name", tags={ "user", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = User.class), + @ApiResponse(code = 400, message = "Invalid username supplied"), + @ApiResponse(code = 404, message = "User not found") }) + public User getUserByName(@PathParam("username") String username); + + /** + * Logs user into the system + * + */ + @GET + @Path("/user/login") + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Logs user into the system", tags={ "user", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = String.class), + @ApiResponse(code = 400, message = "Invalid username/password supplied") }) + public String loginUser(@QueryParam("username") @NotNull String username, @QueryParam("password") @NotNull String password); + + /** + * Logs out current logged in user session + * + */ + @GET + @Path("/user/logout") + @ApiOperation(value = "Logs out current logged in user session", tags={ "user", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation") }) + public void logoutUser(); + + /** + * Updated user + * + * This can only be done by the logged in user. + * + */ + @PUT + @Path("/user/{username}") + @Consumes({ "application/json" }) + @ApiOperation(value = "Updated user", tags={ "user" }) + @ApiResponses(value = { + @ApiResponse(code = 400, message = "Invalid user supplied"), + @ApiResponse(code = 404, message = "User not found") }) + public void updateUser(@PathParam("username") String username, @Valid User body); +} + diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/AdditionalPropertiesClass.java b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/AdditionalPropertiesClass.java new file mode 100644 index 00000000000..45917d22770 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/AdditionalPropertiesClass.java @@ -0,0 +1,115 @@ +package org.openapitools.model; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import javax.validation.constraints.*; +import javax.validation.Valid; + +import io.swagger.annotations.ApiModelProperty; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; +import com.fasterxml.jackson.annotation.JsonFormat; +import com.fasterxml.jackson.annotation.JsonProperty; + +public class AdditionalPropertiesClass { + + @ApiModelProperty(value = "") + private Map mapProperty = null; + + @ApiModelProperty(value = "") + @Valid + private Map> mapOfMapProperty = null; + /** + * Get mapProperty + * @return mapProperty + */ + @JsonProperty("map_property") + public Map getMapProperty() { + return mapProperty; + } + + /** + * Sets the mapProperty property. + */ + public void setMapProperty(Map mapProperty) { + this.mapProperty = mapProperty; + } + + /** + * Sets the mapProperty property. + */ + public AdditionalPropertiesClass mapProperty(Map mapProperty) { + this.mapProperty = mapProperty; + return this; + } + + /** + * Puts a new item into the mapProperty map. + */ + public AdditionalPropertiesClass putMapPropertyItem(String key, String mapPropertyItem) { + this.mapProperty.put(key, mapPropertyItem); + return this; + } + + /** + * Get mapOfMapProperty + * @return mapOfMapProperty + */ + @JsonProperty("map_of_map_property") + public Map> getMapOfMapProperty() { + return mapOfMapProperty; + } + + /** + * Sets the mapOfMapProperty property. + */ + public void setMapOfMapProperty(Map> mapOfMapProperty) { + this.mapOfMapProperty = mapOfMapProperty; + } + + /** + * Sets the mapOfMapProperty property. + */ + public AdditionalPropertiesClass mapOfMapProperty(Map> mapOfMapProperty) { + this.mapOfMapProperty = mapOfMapProperty; + return this; + } + + /** + * Puts a new item into the mapOfMapProperty map. + */ + public AdditionalPropertiesClass putMapOfMapPropertyItem(String key, Map mapOfMapPropertyItem) { + this.mapOfMapProperty.put(key, mapOfMapPropertyItem); + return this; + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AdditionalPropertiesClass {\n"); + + sb.append(" mapProperty: ").append(toIndentedString(mapProperty)).append("\n"); + sb.append(" mapOfMapProperty: ").append(toIndentedString(mapOfMapProperty)).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 static String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/Animal.java b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/Animal.java new file mode 100644 index 00000000000..38b0ca1598a --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/Animal.java @@ -0,0 +1,98 @@ +package org.openapitools.model; + +import com.fasterxml.jackson.annotation.JsonSubTypes; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import javax.validation.constraints.*; +import javax.validation.Valid; + +import io.swagger.annotations.ApiModelProperty; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; +import com.fasterxml.jackson.annotation.JsonFormat; +import com.fasterxml.jackson.annotation.JsonProperty; + +public class Animal { + + @ApiModelProperty(required = true, value = "") + private String className; + + @ApiModelProperty(value = "") + private String color = "red"; + /** + * Get className + * @return className + */ + @JsonProperty("className") + @NotNull + public String getClassName() { + return className; + } + + /** + * Sets the className property. + */ + public void setClassName(String className) { + this.className = className; + } + + /** + * Sets the className property. + */ + public Animal className(String className) { + this.className = className; + return this; + } + + /** + * Get color + * @return color + */ + @JsonProperty("color") + public String getColor() { + return color; + } + + /** + * Sets the color property. + */ + public void setColor(String color) { + this.color = color; + } + + /** + * Sets the color property. + */ + public Animal color(String color) { + this.color = color; + return this; + } + + + @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("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/AnimalFarm.java b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/AnimalFarm.java new file mode 100644 index 00000000000..c418106a524 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/AnimalFarm.java @@ -0,0 +1,42 @@ +package org.openapitools.model; + +import java.util.ArrayList; +import java.util.List; +import org.openapitools.model.Animal; +import javax.validation.constraints.*; +import javax.validation.Valid; + +import io.swagger.annotations.ApiModelProperty; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; +import com.fasterxml.jackson.annotation.JsonFormat; +import com.fasterxml.jackson.annotation.JsonProperty; + +public class AnimalFarm extends ArrayList { + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AnimalFarm {\n"); + sb.append(" ").append(toIndentedString(super.toString())).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 static String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/ArrayOfArrayOfNumberOnly.java b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/ArrayOfArrayOfNumberOnly.java new file mode 100644 index 00000000000..b30ac2cddba --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/ArrayOfArrayOfNumberOnly.java @@ -0,0 +1,79 @@ +package org.openapitools.model; + +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; +import javax.validation.constraints.*; +import javax.validation.Valid; + +import io.swagger.annotations.ApiModelProperty; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; +import com.fasterxml.jackson.annotation.JsonFormat; +import com.fasterxml.jackson.annotation.JsonProperty; + +public class ArrayOfArrayOfNumberOnly { + + @ApiModelProperty(value = "") + @Valid + private List> arrayArrayNumber = null; + /** + * Get arrayArrayNumber + * @return arrayArrayNumber + */ + @JsonProperty("ArrayArrayNumber") + public List> getArrayArrayNumber() { + return arrayArrayNumber; + } + + /** + * Sets the arrayArrayNumber property. + */ + public void setArrayArrayNumber(List> arrayArrayNumber) { + this.arrayArrayNumber = arrayArrayNumber; + } + + /** + * Sets the arrayArrayNumber property. + */ + public ArrayOfArrayOfNumberOnly arrayArrayNumber(List> arrayArrayNumber) { + this.arrayArrayNumber = arrayArrayNumber; + return this; + } + + /** + * Adds a new item to the arrayArrayNumber list. + */ + public ArrayOfArrayOfNumberOnly addArrayArrayNumberItem(List arrayArrayNumberItem) { + this.arrayArrayNumber.add(arrayArrayNumberItem); + return this; + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ArrayOfArrayOfNumberOnly {\n"); + + sb.append(" arrayArrayNumber: ").append(toIndentedString(arrayArrayNumber)).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 static String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/ArrayOfNumberOnly.java b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/ArrayOfNumberOnly.java new file mode 100644 index 00000000000..89edc0079e7 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/ArrayOfNumberOnly.java @@ -0,0 +1,79 @@ +package org.openapitools.model; + +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; +import javax.validation.constraints.*; +import javax.validation.Valid; + +import io.swagger.annotations.ApiModelProperty; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; +import com.fasterxml.jackson.annotation.JsonFormat; +import com.fasterxml.jackson.annotation.JsonProperty; + +public class ArrayOfNumberOnly { + + @ApiModelProperty(value = "") + @Valid + private List arrayNumber = null; + /** + * Get arrayNumber + * @return arrayNumber + */ + @JsonProperty("ArrayNumber") + public List getArrayNumber() { + return arrayNumber; + } + + /** + * Sets the arrayNumber property. + */ + public void setArrayNumber(List arrayNumber) { + this.arrayNumber = arrayNumber; + } + + /** + * Sets the arrayNumber property. + */ + public ArrayOfNumberOnly arrayNumber(List arrayNumber) { + this.arrayNumber = arrayNumber; + return this; + } + + /** + * Adds a new item to the arrayNumber list. + */ + public ArrayOfNumberOnly addArrayNumberItem(BigDecimal arrayNumberItem) { + this.arrayNumber.add(arrayNumberItem); + return this; + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ArrayOfNumberOnly {\n"); + + sb.append(" arrayNumber: ").append(toIndentedString(arrayNumber)).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 static String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/ArrayTest.java b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/ArrayTest.java new file mode 100644 index 00000000000..88d5c73521d --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/ArrayTest.java @@ -0,0 +1,152 @@ +package org.openapitools.model; + +import java.util.ArrayList; +import java.util.List; +import org.openapitools.model.ReadOnlyFirst; +import javax.validation.constraints.*; +import javax.validation.Valid; + +import io.swagger.annotations.ApiModelProperty; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; +import com.fasterxml.jackson.annotation.JsonFormat; +import com.fasterxml.jackson.annotation.JsonProperty; + +public class ArrayTest { + + @ApiModelProperty(value = "") + private List arrayOfString = null; + + @ApiModelProperty(value = "") + @Valid + private List> arrayArrayOfInteger = null; + + @ApiModelProperty(value = "") + @Valid + private List> arrayArrayOfModel = null; + /** + * Get arrayOfString + * @return arrayOfString + */ + @JsonProperty("array_of_string") + public List getArrayOfString() { + return arrayOfString; + } + + /** + * Sets the arrayOfString property. + */ + public void setArrayOfString(List arrayOfString) { + this.arrayOfString = arrayOfString; + } + + /** + * Sets the arrayOfString property. + */ + public ArrayTest arrayOfString(List arrayOfString) { + this.arrayOfString = arrayOfString; + return this; + } + + /** + * Adds a new item to the arrayOfString list. + */ + public ArrayTest addArrayOfStringItem(String arrayOfStringItem) { + this.arrayOfString.add(arrayOfStringItem); + return this; + } + + /** + * Get arrayArrayOfInteger + * @return arrayArrayOfInteger + */ + @JsonProperty("array_array_of_integer") + public List> getArrayArrayOfInteger() { + return arrayArrayOfInteger; + } + + /** + * Sets the arrayArrayOfInteger property. + */ + public void setArrayArrayOfInteger(List> arrayArrayOfInteger) { + this.arrayArrayOfInteger = arrayArrayOfInteger; + } + + /** + * Sets the arrayArrayOfInteger property. + */ + public ArrayTest arrayArrayOfInteger(List> arrayArrayOfInteger) { + this.arrayArrayOfInteger = arrayArrayOfInteger; + return this; + } + + /** + * Adds a new item to the arrayArrayOfInteger list. + */ + public ArrayTest addArrayArrayOfIntegerItem(List arrayArrayOfIntegerItem) { + this.arrayArrayOfInteger.add(arrayArrayOfIntegerItem); + return this; + } + + /** + * Get arrayArrayOfModel + * @return arrayArrayOfModel + */ + @JsonProperty("array_array_of_model") + public List> getArrayArrayOfModel() { + return arrayArrayOfModel; + } + + /** + * Sets the arrayArrayOfModel property. + */ + public void setArrayArrayOfModel(List> arrayArrayOfModel) { + this.arrayArrayOfModel = arrayArrayOfModel; + } + + /** + * Sets the arrayArrayOfModel property. + */ + public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { + this.arrayArrayOfModel = arrayArrayOfModel; + return this; + } + + /** + * Adds a new item to the arrayArrayOfModel list. + */ + public ArrayTest addArrayArrayOfModelItem(List arrayArrayOfModelItem) { + this.arrayArrayOfModel.add(arrayArrayOfModelItem); + return this; + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ArrayTest {\n"); + + sb.append(" arrayOfString: ").append(toIndentedString(arrayOfString)).append("\n"); + sb.append(" arrayArrayOfInteger: ").append(toIndentedString(arrayArrayOfInteger)).append("\n"); + sb.append(" arrayArrayOfModel: ").append(toIndentedString(arrayArrayOfModel)).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 static String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/Capitalization.java b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/Capitalization.java new file mode 100644 index 00000000000..899f4b5e5d7 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/Capitalization.java @@ -0,0 +1,210 @@ +package org.openapitools.model; + +import javax.validation.constraints.*; +import javax.validation.Valid; + +import io.swagger.annotations.ApiModelProperty; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; +import com.fasterxml.jackson.annotation.JsonFormat; +import com.fasterxml.jackson.annotation.JsonProperty; + +public class Capitalization { + + @ApiModelProperty(value = "") + private String smallCamel; + + @ApiModelProperty(value = "") + private String capitalCamel; + + @ApiModelProperty(value = "") + private String smallSnake; + + @ApiModelProperty(value = "") + private String capitalSnake; + + @ApiModelProperty(value = "") + private String scAETHFlowPoints; + + /** + * Name of the pet + */ + @ApiModelProperty(value = "Name of the pet ") + private String ATT_NAME; + /** + * Get smallCamel + * @return smallCamel + */ + @JsonProperty("smallCamel") + public String getSmallCamel() { + return smallCamel; + } + + /** + * Sets the smallCamel property. + */ + public void setSmallCamel(String smallCamel) { + this.smallCamel = smallCamel; + } + + /** + * Sets the smallCamel property. + */ + public Capitalization smallCamel(String smallCamel) { + this.smallCamel = smallCamel; + return this; + } + + /** + * Get capitalCamel + * @return capitalCamel + */ + @JsonProperty("CapitalCamel") + public String getCapitalCamel() { + return capitalCamel; + } + + /** + * Sets the capitalCamel property. + */ + public void setCapitalCamel(String capitalCamel) { + this.capitalCamel = capitalCamel; + } + + /** + * Sets the capitalCamel property. + */ + public Capitalization capitalCamel(String capitalCamel) { + this.capitalCamel = capitalCamel; + return this; + } + + /** + * Get smallSnake + * @return smallSnake + */ + @JsonProperty("small_Snake") + public String getSmallSnake() { + return smallSnake; + } + + /** + * Sets the smallSnake property. + */ + public void setSmallSnake(String smallSnake) { + this.smallSnake = smallSnake; + } + + /** + * Sets the smallSnake property. + */ + public Capitalization smallSnake(String smallSnake) { + this.smallSnake = smallSnake; + return this; + } + + /** + * Get capitalSnake + * @return capitalSnake + */ + @JsonProperty("Capital_Snake") + public String getCapitalSnake() { + return capitalSnake; + } + + /** + * Sets the capitalSnake property. + */ + public void setCapitalSnake(String capitalSnake) { + this.capitalSnake = capitalSnake; + } + + /** + * Sets the capitalSnake property. + */ + public Capitalization capitalSnake(String capitalSnake) { + this.capitalSnake = capitalSnake; + return this; + } + + /** + * Get scAETHFlowPoints + * @return scAETHFlowPoints + */ + @JsonProperty("SCA_ETH_Flow_Points") + public String getScAETHFlowPoints() { + return scAETHFlowPoints; + } + + /** + * Sets the scAETHFlowPoints property. + */ + public void setScAETHFlowPoints(String scAETHFlowPoints) { + this.scAETHFlowPoints = scAETHFlowPoints; + } + + /** + * Sets the scAETHFlowPoints property. + */ + public Capitalization scAETHFlowPoints(String scAETHFlowPoints) { + this.scAETHFlowPoints = scAETHFlowPoints; + return this; + } + + /** + * Name of the pet + * @return ATT_NAME + */ + @JsonProperty("ATT_NAME") + public String getATTNAME() { + return ATT_NAME; + } + + /** + * Sets the ATT_NAME property. + */ + public void setATTNAME(String ATT_NAME) { + this.ATT_NAME = ATT_NAME; + } + + /** + * Sets the ATT_NAME property. + */ + public Capitalization ATT_NAME(String ATT_NAME) { + this.ATT_NAME = ATT_NAME; + return this; + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Capitalization {\n"); + + sb.append(" smallCamel: ").append(toIndentedString(smallCamel)).append("\n"); + sb.append(" capitalCamel: ").append(toIndentedString(capitalCamel)).append("\n"); + sb.append(" smallSnake: ").append(toIndentedString(smallSnake)).append("\n"); + sb.append(" capitalSnake: ").append(toIndentedString(capitalSnake)).append("\n"); + sb.append(" scAETHFlowPoints: ").append(toIndentedString(scAETHFlowPoints)).append("\n"); + sb.append(" ATT_NAME: ").append(toIndentedString(ATT_NAME)).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 static String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/Cat.java b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/Cat.java new file mode 100644 index 00000000000..83b49a63e37 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/Cat.java @@ -0,0 +1,68 @@ +package org.openapitools.model; + +import org.openapitools.model.Animal; +import javax.validation.constraints.*; +import javax.validation.Valid; + +import io.swagger.annotations.ApiModelProperty; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; +import com.fasterxml.jackson.annotation.JsonFormat; +import com.fasterxml.jackson.annotation.JsonProperty; + +public class Cat extends Animal { + + @ApiModelProperty(value = "") + private Boolean declawed; + /** + * Get declawed + * @return declawed + */ + @JsonProperty("declawed") + public Boolean getDeclawed() { + return declawed; + } + + /** + * Sets the declawed property. + */ + public void setDeclawed(Boolean declawed) { + this.declawed = declawed; + } + + /** + * Sets the declawed property. + */ + public Cat declawed(Boolean declawed) { + this.declawed = declawed; + return this; + } + + + @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("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/Category.java b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/Category.java new file mode 100644 index 00000000000..c7bfb3b253e --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/Category.java @@ -0,0 +1,96 @@ +package org.openapitools.model; + +import javax.validation.constraints.*; +import javax.validation.Valid; + +import io.swagger.annotations.ApiModelProperty; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; +import com.fasterxml.jackson.annotation.JsonFormat; +import com.fasterxml.jackson.annotation.JsonProperty; + +public class Category { + + @ApiModelProperty(value = "") + private Long id; + + @ApiModelProperty(required = true, value = "") + private String name = "default-name"; + /** + * Get id + * @return id + */ + @JsonProperty("id") + public Long getId() { + return id; + } + + /** + * Sets the id property. + */ + public void setId(Long id) { + this.id = id; + } + + /** + * Sets the id property. + */ + public Category id(Long id) { + this.id = id; + return this; + } + + /** + * Get name + * @return name + */ + @JsonProperty("name") + @NotNull + public String getName() { + return name; + } + + /** + * Sets the name property. + */ + public void setName(String name) { + this.name = name; + } + + /** + * Sets the name property. + */ + public Category name(String name) { + this.name = name; + return this; + } + + + @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("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/ClassModel.java b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/ClassModel.java new file mode 100644 index 00000000000..fdd41428e99 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/ClassModel.java @@ -0,0 +1,72 @@ +package org.openapitools.model; + +import io.swagger.annotations.ApiModel; +import javax.validation.constraints.*; +import javax.validation.Valid; + +import io.swagger.annotations.ApiModelProperty; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; +import com.fasterxml.jackson.annotation.JsonFormat; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Model for testing model with \"_class\" property + */ +@ApiModel(description="Model for testing model with \"_class\" property") +public class ClassModel { + + @ApiModelProperty(value = "") + private String propertyClass; + /** + * Get propertyClass + * @return propertyClass + */ + @JsonProperty("_class") + public String getPropertyClass() { + return propertyClass; + } + + /** + * Sets the propertyClass property. + */ + public void setPropertyClass(String propertyClass) { + this.propertyClass = propertyClass; + } + + /** + * Sets the propertyClass property. + */ + public ClassModel propertyClass(String propertyClass) { + this.propertyClass = propertyClass; + return this; + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ClassModel {\n"); + + sb.append(" propertyClass: ").append(toIndentedString(propertyClass)).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 static String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/Client.java b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/Client.java new file mode 100644 index 00000000000..dc7323ea414 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/Client.java @@ -0,0 +1,67 @@ +package org.openapitools.model; + +import javax.validation.constraints.*; +import javax.validation.Valid; + +import io.swagger.annotations.ApiModelProperty; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; +import com.fasterxml.jackson.annotation.JsonFormat; +import com.fasterxml.jackson.annotation.JsonProperty; + +public class Client { + + @ApiModelProperty(value = "") + private String client; + /** + * Get client + * @return client + */ + @JsonProperty("client") + public String getClient() { + return client; + } + + /** + * Sets the client property. + */ + public void setClient(String client) { + this.client = client; + } + + /** + * Sets the client property. + */ + public Client client(String client) { + this.client = client; + return this; + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Client {\n"); + + sb.append(" client: ").append(toIndentedString(client)).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 static String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/Dog.java b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/Dog.java new file mode 100644 index 00000000000..e9d8e2ba541 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/Dog.java @@ -0,0 +1,68 @@ +package org.openapitools.model; + +import org.openapitools.model.Animal; +import javax.validation.constraints.*; +import javax.validation.Valid; + +import io.swagger.annotations.ApiModelProperty; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; +import com.fasterxml.jackson.annotation.JsonFormat; +import com.fasterxml.jackson.annotation.JsonProperty; + +public class Dog extends Animal { + + @ApiModelProperty(value = "") + private String breed; + /** + * Get breed + * @return breed + */ + @JsonProperty("breed") + public String getBreed() { + return breed; + } + + /** + * Sets the breed property. + */ + public void setBreed(String breed) { + this.breed = breed; + } + + /** + * Sets the breed property. + */ + public Dog breed(String breed) { + this.breed = breed; + return this; + } + + + @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("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/EnumArrays.java b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/EnumArrays.java new file mode 100644 index 00000000000..9ad9315f42a --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/EnumArrays.java @@ -0,0 +1,169 @@ +package org.openapitools.model; + +import java.util.ArrayList; +import java.util.List; +import javax.validation.constraints.*; +import javax.validation.Valid; + +import io.swagger.annotations.ApiModelProperty; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; +import com.fasterxml.jackson.annotation.JsonFormat; +import com.fasterxml.jackson.annotation.JsonProperty; + +public class EnumArrays { + +@XmlType(name="JustSymbolEnum") +@XmlEnum(String.class) +public enum JustSymbolEnum { + + @XmlEnumValue(">=") @JsonProperty(">=") GREATER_THAN_OR_EQUAL_TO(String.valueOf(">=")), + @XmlEnumValue("$") @JsonProperty("$") DOLLAR(String.valueOf("$")); + + private String value; + + JustSymbolEnum (String v) { + value = v; + } + + public String value() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static JustSymbolEnum fromValue(String v) { + for (JustSymbolEnum b : JustSymbolEnum.values()) { + if (String.valueOf(b.value).equals(v)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + v + "'"); + } +} + + @ApiModelProperty(value = "") + private JustSymbolEnum justSymbol; + +@XmlType(name="ArrayEnumEnum") +@XmlEnum(String.class) +public enum ArrayEnumEnum { + + @XmlEnumValue("fish") @JsonProperty("fish") FISH(String.valueOf("fish")), + @XmlEnumValue("crab") @JsonProperty("crab") CRAB(String.valueOf("crab")); + + private String value; + + ArrayEnumEnum (String v) { + value = v; + } + + public String value() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static ArrayEnumEnum fromValue(String v) { + for (ArrayEnumEnum b : ArrayEnumEnum.values()) { + if (String.valueOf(b.value).equals(v)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + v + "'"); + } +} + + @ApiModelProperty(value = "") + private List arrayEnum = null; + /** + * Get justSymbol + * @return justSymbol + */ + @JsonProperty("just_symbol") + public String getJustSymbol() { + return justSymbol == null ? null : justSymbol.value(); + } + + /** + * Sets the justSymbol property. + */ + public void setJustSymbol(JustSymbolEnum justSymbol) { + this.justSymbol = justSymbol; + } + + /** + * Sets the justSymbol property. + */ + public EnumArrays justSymbol(JustSymbolEnum justSymbol) { + this.justSymbol = justSymbol; + return this; + } + + /** + * Get arrayEnum + * @return arrayEnum + */ + @JsonProperty("array_enum") + public List getArrayEnum() { + return arrayEnum; + } + + /** + * Sets the arrayEnum property. + */ + public void setArrayEnum(List arrayEnum) { + this.arrayEnum = arrayEnum; + } + + /** + * Sets the arrayEnum property. + */ + public EnumArrays arrayEnum(List arrayEnum) { + this.arrayEnum = arrayEnum; + return this; + } + + /** + * Adds a new item to the arrayEnum list. + */ + public EnumArrays addArrayEnumItem(ArrayEnumEnum arrayEnumItem) { + this.arrayEnum.add(arrayEnumItem); + return this; + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class EnumArrays {\n"); + + sb.append(" justSymbol: ").append(toIndentedString(justSymbol)).append("\n"); + sb.append(" arrayEnum: ").append(toIndentedString(arrayEnum)).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 static String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/EnumClass.java b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/EnumClass.java new file mode 100644 index 00000000000..bc4c742b12d --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/EnumClass.java @@ -0,0 +1,43 @@ +package org.openapitools.model; + +import javax.validation.constraints.*; +import javax.validation.Valid; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Gets or Sets EnumClass + */ +public enum EnumClass { + + _ABC("_abc"), + + _EFG("-efg"), + + _XYZ_("(xyz)"); + + private String value; + + EnumClass(String value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static EnumClass fromValue(String text) { + for (EnumClass b : EnumClass.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + text + "'"); + } + +} + diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/EnumTest.java b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/EnumTest.java new file mode 100644 index 00000000000..4e618c8a557 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/EnumTest.java @@ -0,0 +1,312 @@ +package org.openapitools.model; + +import org.openapitools.model.OuterEnum; +import javax.validation.constraints.*; +import javax.validation.Valid; + +import io.swagger.annotations.ApiModelProperty; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; +import com.fasterxml.jackson.annotation.JsonFormat; +import com.fasterxml.jackson.annotation.JsonProperty; + +public class EnumTest { + +@XmlType(name="EnumStringEnum") +@XmlEnum(String.class) +public enum EnumStringEnum { + + @XmlEnumValue("UPPER") @JsonProperty("UPPER") UPPER(String.valueOf("UPPER")), + @XmlEnumValue("lower") @JsonProperty("lower") LOWER(String.valueOf("lower")), + @XmlEnumValue("") @JsonProperty("") EMPTY(String.valueOf("")); + + private String value; + + EnumStringEnum (String v) { + value = v; + } + + public String value() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static EnumStringEnum fromValue(String v) { + for (EnumStringEnum b : EnumStringEnum.values()) { + if (String.valueOf(b.value).equals(v)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + v + "'"); + } +} + + @ApiModelProperty(value = "") + private EnumStringEnum enumString; + +@XmlType(name="EnumStringRequiredEnum") +@XmlEnum(String.class) +public enum EnumStringRequiredEnum { + + @XmlEnumValue("UPPER") @JsonProperty("UPPER") UPPER(String.valueOf("UPPER")), + @XmlEnumValue("lower") @JsonProperty("lower") LOWER(String.valueOf("lower")), + @XmlEnumValue("") @JsonProperty("") EMPTY(String.valueOf("")); + + private String value; + + EnumStringRequiredEnum (String v) { + value = v; + } + + public String value() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static EnumStringRequiredEnum fromValue(String v) { + for (EnumStringRequiredEnum b : EnumStringRequiredEnum.values()) { + if (String.valueOf(b.value).equals(v)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + v + "'"); + } +} + + @ApiModelProperty(required = true, value = "") + private EnumStringRequiredEnum enumStringRequired; + +@XmlType(name="EnumIntegerEnum") +@XmlEnum(Integer.class) +public enum EnumIntegerEnum { + + @XmlEnumValue("1") @JsonProperty("1") NUMBER_1(Integer.valueOf(1)), + @XmlEnumValue("-1") @JsonProperty("-1") NUMBER_MINUS_1(Integer.valueOf(-1)); + + private Integer value; + + EnumIntegerEnum (Integer v) { + value = v; + } + + public Integer value() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static EnumIntegerEnum fromValue(String v) { + for (EnumIntegerEnum b : EnumIntegerEnum.values()) { + if (String.valueOf(b.value).equals(v)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + v + "'"); + } +} + + @ApiModelProperty(value = "") + private EnumIntegerEnum enumInteger; + +@XmlType(name="EnumNumberEnum") +@XmlEnum(Double.class) +public enum EnumNumberEnum { + + @XmlEnumValue("1.1") @JsonProperty("1.1") NUMBER_1_DOT_1(Double.valueOf(1.1)), + @XmlEnumValue("-1.2") @JsonProperty("-1.2") NUMBER_MINUS_1_DOT_2(Double.valueOf(-1.2)); + + private Double value; + + EnumNumberEnum (Double v) { + value = v; + } + + public Double value() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static EnumNumberEnum fromValue(String v) { + for (EnumNumberEnum b : EnumNumberEnum.values()) { + if (String.valueOf(b.value).equals(v)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + v + "'"); + } +} + + @ApiModelProperty(value = "") + private EnumNumberEnum enumNumber; + + @ApiModelProperty(value = "") + @Valid + private OuterEnum outerEnum; + /** + * Get enumString + * @return enumString + */ + @JsonProperty("enum_string") + public String getEnumString() { + return enumString == null ? null : enumString.value(); + } + + /** + * Sets the enumString property. + */ + public void setEnumString(EnumStringEnum enumString) { + this.enumString = enumString; + } + + /** + * Sets the enumString property. + */ + public EnumTest enumString(EnumStringEnum enumString) { + this.enumString = enumString; + return this; + } + + /** + * Get enumStringRequired + * @return enumStringRequired + */ + @JsonProperty("enum_string_required") + @NotNull + public String getEnumStringRequired() { + return enumStringRequired == null ? null : enumStringRequired.value(); + } + + /** + * Sets the enumStringRequired property. + */ + public void setEnumStringRequired(EnumStringRequiredEnum enumStringRequired) { + this.enumStringRequired = enumStringRequired; + } + + /** + * Sets the enumStringRequired property. + */ + public EnumTest enumStringRequired(EnumStringRequiredEnum enumStringRequired) { + this.enumStringRequired = enumStringRequired; + return this; + } + + /** + * Get enumInteger + * @return enumInteger + */ + @JsonProperty("enum_integer") + public Integer getEnumInteger() { + return enumInteger == null ? null : enumInteger.value(); + } + + /** + * Sets the enumInteger property. + */ + public void setEnumInteger(EnumIntegerEnum enumInteger) { + this.enumInteger = enumInteger; + } + + /** + * Sets the enumInteger property. + */ + public EnumTest enumInteger(EnumIntegerEnum enumInteger) { + this.enumInteger = enumInteger; + return this; + } + + /** + * Get enumNumber + * @return enumNumber + */ + @JsonProperty("enum_number") + public Double getEnumNumber() { + return enumNumber == null ? null : enumNumber.value(); + } + + /** + * Sets the enumNumber property. + */ + public void setEnumNumber(EnumNumberEnum enumNumber) { + this.enumNumber = enumNumber; + } + + /** + * Sets the enumNumber property. + */ + public EnumTest enumNumber(EnumNumberEnum enumNumber) { + this.enumNumber = enumNumber; + return this; + } + + /** + * Get outerEnum + * @return outerEnum + */ + @JsonProperty("outerEnum") + public OuterEnum getOuterEnum() { + return outerEnum; + } + + /** + * Sets the outerEnum property. + */ + public void setOuterEnum(OuterEnum outerEnum) { + this.outerEnum = outerEnum; + } + + /** + * Sets the outerEnum property. + */ + public EnumTest outerEnum(OuterEnum outerEnum) { + this.outerEnum = outerEnum; + return this; + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class EnumTest {\n"); + + sb.append(" enumString: ").append(toIndentedString(enumString)).append("\n"); + sb.append(" enumStringRequired: ").append(toIndentedString(enumStringRequired)).append("\n"); + sb.append(" enumInteger: ").append(toIndentedString(enumInteger)).append("\n"); + sb.append(" enumNumber: ").append(toIndentedString(enumNumber)).append("\n"); + sb.append(" outerEnum: ").append(toIndentedString(outerEnum)).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 static String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/FileSchemaTestClass.java b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/FileSchemaTestClass.java new file mode 100644 index 00000000000..8d3da8aa033 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/FileSchemaTestClass.java @@ -0,0 +1,107 @@ +package org.openapitools.model; + +import java.util.ArrayList; +import java.util.List; +import javax.validation.constraints.*; +import javax.validation.Valid; + +import io.swagger.annotations.ApiModelProperty; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; +import com.fasterxml.jackson.annotation.JsonFormat; +import com.fasterxml.jackson.annotation.JsonProperty; + +public class FileSchemaTestClass { + + @ApiModelProperty(value = "") + @Valid + private java.io.File file = null; + + @ApiModelProperty(value = "") + @Valid + private List files = null; + /** + * Get file + * @return file + */ + @JsonProperty("file") + public java.io.File getFile() { + return file; + } + + /** + * Sets the file property. + */ + public void setFile(java.io.File file) { + this.file = file; + } + + /** + * Sets the file property. + */ + public FileSchemaTestClass file(java.io.File file) { + this.file = file; + return this; + } + + /** + * Get files + * @return files + */ + @JsonProperty("files") + public List getFiles() { + return files; + } + + /** + * Sets the files property. + */ + public void setFiles(List files) { + this.files = files; + } + + /** + * Sets the files property. + */ + public FileSchemaTestClass files(List files) { + this.files = files; + return this; + } + + /** + * Adds a new item to the files list. + */ + public FileSchemaTestClass addFilesItem(java.io.File filesItem) { + this.files.add(filesItem); + return this; + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class FileSchemaTestClass {\n"); + + sb.append(" file: ").append(toIndentedString(file)).append("\n"); + sb.append(" files: ").append(toIndentedString(files)).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 static String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/FormatTest.java b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/FormatTest.java new file mode 100644 index 00000000000..c354e724d59 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/FormatTest.java @@ -0,0 +1,425 @@ +package org.openapitools.model; + +import java.io.File; +import java.math.BigDecimal; +import java.util.Date; +import java.util.UUID; +import org.joda.time.LocalDate; +import javax.validation.constraints.*; +import javax.validation.Valid; + +import io.swagger.annotations.ApiModelProperty; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; +import com.fasterxml.jackson.annotation.JsonFormat; +import com.fasterxml.jackson.annotation.JsonProperty; + +public class FormatTest { + + @ApiModelProperty(value = "") + private Integer integer; + + @ApiModelProperty(value = "") + private Integer int32; + + @ApiModelProperty(value = "") + private Long int64; + + @ApiModelProperty(required = true, value = "") + @Valid + private BigDecimal number; + + @ApiModelProperty(value = "") + private Float _float; + + @ApiModelProperty(value = "") + private Double _double; + + @ApiModelProperty(value = "") + private String string; + + @ApiModelProperty(required = true, value = "") + private byte[] _byte; + + @ApiModelProperty(value = "") + private File binary; + + @ApiModelProperty(required = true, value = "") + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd") + private LocalDate date; + + @ApiModelProperty(value = "") + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'hh:mm:ss.SSSX") + private Date dateTime; + + @ApiModelProperty(example = "72f98069-206d-4f12-9f12-3d1e525a8e84", value = "") + private UUID uuid; + + @ApiModelProperty(required = true, value = "") + private String password; + /** + * Get integer + * minimum: 10 + * maximum: 100 + * @return integer + */ + @JsonProperty("integer") + @Min(10) @Max(100) public Integer getInteger() { + return integer; + } + + /** + * Sets the integer property. + */ + public void setInteger(Integer integer) { + this.integer = integer; + } + + /** + * Sets the integer property. + */ + public FormatTest integer(Integer integer) { + this.integer = integer; + return this; + } + + /** + * Get int32 + * minimum: 20 + * maximum: 200 + * @return int32 + */ + @JsonProperty("int32") + @Min(20) @Max(200) public Integer getInt32() { + return int32; + } + + /** + * Sets the int32 property. + */ + public void setInt32(Integer int32) { + this.int32 = int32; + } + + /** + * Sets the int32 property. + */ + public FormatTest int32(Integer int32) { + this.int32 = int32; + return this; + } + + /** + * Get int64 + * @return int64 + */ + @JsonProperty("int64") + public Long getInt64() { + return int64; + } + + /** + * Sets the int64 property. + */ + public void setInt64(Long int64) { + this.int64 = int64; + } + + /** + * Sets the int64 property. + */ + public FormatTest int64(Long int64) { + this.int64 = int64; + return this; + } + + /** + * Get number + * minimum: 32.1 + * maximum: 543.2 + * @return number + */ + @JsonProperty("number") + @NotNull + @DecimalMin("32.1") @DecimalMax("543.2") public BigDecimal getNumber() { + return number; + } + + /** + * Sets the number property. + */ + public void setNumber(BigDecimal number) { + this.number = number; + } + + /** + * Sets the number property. + */ + public FormatTest number(BigDecimal number) { + this.number = number; + return this; + } + + /** + * Get _float + * minimum: 54.3 + * maximum: 987.6 + * @return _float + */ + @JsonProperty("float") + @DecimalMin("54.3") @DecimalMax("987.6") public Float getFloat() { + return _float; + } + + /** + * Sets the _float property. + */ + public void setFloat(Float _float) { + this._float = _float; + } + + /** + * Sets the _float property. + */ + public FormatTest _float(Float _float) { + this._float = _float; + return this; + } + + /** + * Get _double + * minimum: 67.8 + * maximum: 123.4 + * @return _double + */ + @JsonProperty("double") + @DecimalMin("67.8") @DecimalMax("123.4") public Double getDouble() { + return _double; + } + + /** + * Sets the _double property. + */ + public void setDouble(Double _double) { + this._double = _double; + } + + /** + * Sets the _double property. + */ + public FormatTest _double(Double _double) { + this._double = _double; + return this; + } + + /** + * Get string + * @return string + */ + @JsonProperty("string") + @Pattern(regexp="/[a-z]/i") public String getString() { + return string; + } + + /** + * Sets the string property. + */ + public void setString(String string) { + this.string = string; + } + + /** + * Sets the string property. + */ + public FormatTest string(String string) { + this.string = string; + return this; + } + + /** + * Get _byte + * @return _byte + */ + @JsonProperty("byte") + @NotNull + @Pattern(regexp="^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$") public byte[] getByte() { + return _byte; + } + + /** + * Sets the _byte property. + */ + public void setByte(byte[] _byte) { + this._byte = _byte; + } + + /** + * Sets the _byte property. + */ + public FormatTest _byte(byte[] _byte) { + this._byte = _byte; + return this; + } + + /** + * Get binary + * @return binary + */ + @JsonProperty("binary") + public File getBinary() { + return binary; + } + + /** + * Sets the binary property. + */ + public void setBinary(File binary) { + this.binary = binary; + } + + /** + * Sets the binary property. + */ + public FormatTest binary(File binary) { + this.binary = binary; + return this; + } + + /** + * Get date + * @return date + */ + @JsonProperty("date") + @NotNull + public LocalDate getDate() { + return date; + } + + /** + * Sets the date property. + */ + public void setDate(LocalDate date) { + this.date = date; + } + + /** + * Sets the date property. + */ + public FormatTest date(LocalDate date) { + this.date = date; + return this; + } + + /** + * Get dateTime + * @return dateTime + */ + @JsonProperty("dateTime") + public Date getDateTime() { + return dateTime; + } + + /** + * Sets the dateTime property. + */ + public void setDateTime(Date dateTime) { + this.dateTime = dateTime; + } + + /** + * Sets the dateTime property. + */ + public FormatTest dateTime(Date dateTime) { + this.dateTime = dateTime; + return this; + } + + /** + * Get uuid + * @return uuid + */ + @JsonProperty("uuid") + public UUID getUuid() { + return uuid; + } + + /** + * Sets the uuid property. + */ + public void setUuid(UUID uuid) { + this.uuid = uuid; + } + + /** + * Sets the uuid property. + */ + public FormatTest uuid(UUID uuid) { + this.uuid = uuid; + return this; + } + + /** + * Get password + * @return password + */ + @JsonProperty("password") + @NotNull + @Size(min=10,max=64) public String getPassword() { + return password; + } + + /** + * Sets the password property. + */ + public void setPassword(String password) { + this.password = password; + } + + /** + * Sets the password property. + */ + public FormatTest password(String password) { + this.password = password; + return this; + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class FormatTest {\n"); + + sb.append(" integer: ").append(toIndentedString(integer)).append("\n"); + sb.append(" int32: ").append(toIndentedString(int32)).append("\n"); + sb.append(" int64: ").append(toIndentedString(int64)).append("\n"); + sb.append(" number: ").append(toIndentedString(number)).append("\n"); + sb.append(" _float: ").append(toIndentedString(_float)).append("\n"); + sb.append(" _double: ").append(toIndentedString(_double)).append("\n"); + sb.append(" string: ").append(toIndentedString(string)).append("\n"); + sb.append(" _byte: ").append(toIndentedString(_byte)).append("\n"); + sb.append(" binary: ").append(toIndentedString(binary)).append("\n"); + sb.append(" date: ").append(toIndentedString(date)).append("\n"); + sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); + sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); + sb.append(" password: ").append(toIndentedString(password)).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 static String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/HasOnlyReadOnly.java b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/HasOnlyReadOnly.java new file mode 100644 index 00000000000..e615164235c --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/HasOnlyReadOnly.java @@ -0,0 +1,99 @@ +package org.openapitools.model; + +import javax.validation.constraints.*; +import javax.validation.Valid; + +import io.swagger.annotations.ApiModelProperty; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; +import com.fasterxml.jackson.annotation.JsonFormat; +import com.fasterxml.jackson.annotation.JsonProperty; + +public class HasOnlyReadOnly { + + @ApiModelProperty(value = "") + private String bar; + + @ApiModelProperty(value = "") + private String foo; + /** + * Get bar + * @return bar + */ + @JsonProperty("bar") + public String getBar() { + return bar; + } + + /** + * Sets the bar property. + *
N.B. bar is read only; client code should not call this method. + */ + public void setBar(String bar) { + this.bar = bar; + } + + /** + * Sets the bar property. + *
N.B. bar is read only; client code should not call this method. + */ + public HasOnlyReadOnly bar(String bar) { + this.bar = bar; + return this; + } + + /** + * Get foo + * @return foo + */ + @JsonProperty("foo") + public String getFoo() { + return foo; + } + + /** + * Sets the foo property. + *
N.B. foo is read only; client code should not call this method. + */ + public void setFoo(String foo) { + this.foo = foo; + } + + /** + * Sets the foo property. + *
N.B. foo is read only; client code should not call this method. + */ + public HasOnlyReadOnly foo(String foo) { + this.foo = foo; + return this; + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class HasOnlyReadOnly {\n"); + + sb.append(" bar: ").append(toIndentedString(bar)).append("\n"); + sb.append(" foo: ").append(toIndentedString(foo)).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 static String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/MapTest.java b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/MapTest.java new file mode 100644 index 00000000000..125c3f80173 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/MapTest.java @@ -0,0 +1,213 @@ +package org.openapitools.model; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.openapitools.model.StringBooleanMap; +import javax.validation.constraints.*; +import javax.validation.Valid; + +import io.swagger.annotations.ApiModelProperty; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; +import com.fasterxml.jackson.annotation.JsonFormat; +import com.fasterxml.jackson.annotation.JsonProperty; + +public class MapTest { + + @ApiModelProperty(value = "") + @Valid + private Map> mapMapOfString = null; + +@XmlType(name="InnerEnum") +@XmlEnum(String.class) +public enum InnerEnum { + + @XmlEnumValue("UPPER") @JsonProperty("UPPER") UPPER(String.valueOf("UPPER")), + @XmlEnumValue("lower") @JsonProperty("lower") LOWER(String.valueOf("lower")); + + private String value; + + InnerEnum (String v) { + value = v; + } + + public String value() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static InnerEnum fromValue(String v) { + for (InnerEnum b : InnerEnum.values()) { + if (String.valueOf(b.value).equals(v)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + v + "'"); + } +} + + @ApiModelProperty(value = "") + private Map mapOfEnumString = null; + + @ApiModelProperty(value = "") + private Map directMap = null; + + @ApiModelProperty(value = "") + @Valid + private StringBooleanMap indirectMap = new StringBooleanMap(); + /** + * Get mapMapOfString + * @return mapMapOfString + */ + @JsonProperty("map_map_of_string") + public Map> getMapMapOfString() { + return mapMapOfString; + } + + /** + * Sets the mapMapOfString property. + */ + public void setMapMapOfString(Map> mapMapOfString) { + this.mapMapOfString = mapMapOfString; + } + + /** + * Sets the mapMapOfString property. + */ + public MapTest mapMapOfString(Map> mapMapOfString) { + this.mapMapOfString = mapMapOfString; + return this; + } + + /** + * Puts a new item into the mapMapOfString map. + */ + public MapTest putMapMapOfStringItem(String key, Map mapMapOfStringItem) { + this.mapMapOfString.put(key, mapMapOfStringItem); + return this; + } + + /** + * Get mapOfEnumString + * @return mapOfEnumString + */ + @JsonProperty("map_of_enum_string") + public Map getMapOfEnumString() { + return mapOfEnumString; + } + + /** + * Sets the mapOfEnumString property. + */ + public void setMapOfEnumString(Map mapOfEnumString) { + this.mapOfEnumString = mapOfEnumString; + } + + /** + * Sets the mapOfEnumString property. + */ + public MapTest mapOfEnumString(Map mapOfEnumString) { + this.mapOfEnumString = mapOfEnumString; + return this; + } + + /** + * Puts a new item into the mapOfEnumString map. + */ + public MapTest putMapOfEnumStringItem(String key, InnerEnum mapOfEnumStringItem) { + this.mapOfEnumString.put(key, mapOfEnumStringItem); + return this; + } + + /** + * Get directMap + * @return directMap + */ + @JsonProperty("direct_map") + public Map getDirectMap() { + return directMap; + } + + /** + * Sets the directMap property. + */ + public void setDirectMap(Map directMap) { + this.directMap = directMap; + } + + /** + * Sets the directMap property. + */ + public MapTest directMap(Map directMap) { + this.directMap = directMap; + return this; + } + + /** + * Puts a new item into the directMap map. + */ + public MapTest putDirectMapItem(String key, Boolean directMapItem) { + this.directMap.put(key, directMapItem); + return this; + } + + /** + * Get indirectMap + * @return indirectMap + */ + @JsonProperty("indirect_map") + public StringBooleanMap getIndirectMap() { + return indirectMap; + } + + /** + * Sets the indirectMap property. + */ + public void setIndirectMap(StringBooleanMap indirectMap) { + this.indirectMap = indirectMap; + } + + /** + * Sets the indirectMap property. + */ + public MapTest indirectMap(StringBooleanMap indirectMap) { + this.indirectMap = indirectMap; + return this; + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class MapTest {\n"); + + sb.append(" mapMapOfString: ").append(toIndentedString(mapMapOfString)).append("\n"); + sb.append(" mapOfEnumString: ").append(toIndentedString(mapOfEnumString)).append("\n"); + sb.append(" directMap: ").append(toIndentedString(directMap)).append("\n"); + sb.append(" indirectMap: ").append(toIndentedString(indirectMap)).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 static String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/MixedPropertiesAndAdditionalPropertiesClass.java new file mode 100644 index 00000000000..f8323b7e766 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -0,0 +1,139 @@ +package org.openapitools.model; + +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import org.openapitools.model.Animal; +import javax.validation.constraints.*; +import javax.validation.Valid; + +import io.swagger.annotations.ApiModelProperty; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; +import com.fasterxml.jackson.annotation.JsonFormat; +import com.fasterxml.jackson.annotation.JsonProperty; + +public class MixedPropertiesAndAdditionalPropertiesClass { + + @ApiModelProperty(value = "") + private UUID uuid; + + @ApiModelProperty(value = "") + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'hh:mm:ss.SSSX") + private Date dateTime; + + @ApiModelProperty(value = "") + @Valid + private Map map = null; + /** + * Get uuid + * @return uuid + */ + @JsonProperty("uuid") + public UUID getUuid() { + return uuid; + } + + /** + * Sets the uuid property. + */ + public void setUuid(UUID uuid) { + this.uuid = uuid; + } + + /** + * Sets the uuid property. + */ + public MixedPropertiesAndAdditionalPropertiesClass uuid(UUID uuid) { + this.uuid = uuid; + return this; + } + + /** + * Get dateTime + * @return dateTime + */ + @JsonProperty("dateTime") + public Date getDateTime() { + return dateTime; + } + + /** + * Sets the dateTime property. + */ + public void setDateTime(Date dateTime) { + this.dateTime = dateTime; + } + + /** + * Sets the dateTime property. + */ + public MixedPropertiesAndAdditionalPropertiesClass dateTime(Date dateTime) { + this.dateTime = dateTime; + return this; + } + + /** + * Get map + * @return map + */ + @JsonProperty("map") + public Map getMap() { + return map; + } + + /** + * Sets the map property. + */ + public void setMap(Map map) { + this.map = map; + } + + /** + * Sets the map property. + */ + public MixedPropertiesAndAdditionalPropertiesClass map(Map map) { + this.map = map; + return this; + } + + /** + * Puts a new item into the map map. + */ + public MixedPropertiesAndAdditionalPropertiesClass putMapItem(String key, Animal mapItem) { + this.map.put(key, mapItem); + return this; + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class MixedPropertiesAndAdditionalPropertiesClass {\n"); + + sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); + sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); + sb.append(" map: ").append(toIndentedString(map)).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 static String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/Model200Response.java b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/Model200Response.java new file mode 100644 index 00000000000..1e419b60007 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/Model200Response.java @@ -0,0 +1,100 @@ +package org.openapitools.model; + +import io.swagger.annotations.ApiModel; +import javax.validation.constraints.*; +import javax.validation.Valid; + +import io.swagger.annotations.ApiModelProperty; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; +import com.fasterxml.jackson.annotation.JsonFormat; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Model for testing model name starting with number + */ +@ApiModel(description="Model for testing model name starting with number") +public class Model200Response { + + @ApiModelProperty(value = "") + private Integer name; + + @ApiModelProperty(value = "") + private String propertyClass; + /** + * Get name + * @return name + */ + @JsonProperty("name") + public Integer getName() { + return name; + } + + /** + * Sets the name property. + */ + public void setName(Integer name) { + this.name = name; + } + + /** + * Sets the name property. + */ + public Model200Response name(Integer name) { + this.name = name; + return this; + } + + /** + * Get propertyClass + * @return propertyClass + */ + @JsonProperty("class") + public String getPropertyClass() { + return propertyClass; + } + + /** + * Sets the propertyClass property. + */ + public void setPropertyClass(String propertyClass) { + this.propertyClass = propertyClass; + } + + /** + * Sets the propertyClass property. + */ + public Model200Response propertyClass(String propertyClass) { + this.propertyClass = propertyClass; + return this; + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Model200Response {\n"); + + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" propertyClass: ").append(toIndentedString(propertyClass)).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 static String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/ModelApiResponse.java b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/ModelApiResponse.java new file mode 100644 index 00000000000..3f24ce9a87c --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/ModelApiResponse.java @@ -0,0 +1,123 @@ +package org.openapitools.model; + +import javax.validation.constraints.*; +import javax.validation.Valid; + +import io.swagger.annotations.ApiModelProperty; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; +import com.fasterxml.jackson.annotation.JsonFormat; +import com.fasterxml.jackson.annotation.JsonProperty; + +public class ModelApiResponse { + + @ApiModelProperty(value = "") + private Integer code; + + @ApiModelProperty(value = "") + private String type; + + @ApiModelProperty(value = "") + private String message; + /** + * Get code + * @return code + */ + @JsonProperty("code") + public Integer getCode() { + return code; + } + + /** + * Sets the code property. + */ + public void setCode(Integer code) { + this.code = code; + } + + /** + * Sets the code property. + */ + public ModelApiResponse code(Integer code) { + this.code = code; + return this; + } + + /** + * Get type + * @return type + */ + @JsonProperty("type") + public String getType() { + return type; + } + + /** + * Sets the type property. + */ + public void setType(String type) { + this.type = type; + } + + /** + * Sets the type property. + */ + public ModelApiResponse type(String type) { + this.type = type; + return this; + } + + /** + * Get message + * @return message + */ + @JsonProperty("message") + public String getMessage() { + return message; + } + + /** + * Sets the message property. + */ + public void setMessage(String message) { + this.message = message; + } + + /** + * Sets the message property. + */ + public ModelApiResponse message(String message) { + this.message = message; + return this; + } + + + @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("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/ModelReturn.java b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/ModelReturn.java new file mode 100644 index 00000000000..d99d9e208d6 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/ModelReturn.java @@ -0,0 +1,72 @@ +package org.openapitools.model; + +import io.swagger.annotations.ApiModel; +import javax.validation.constraints.*; +import javax.validation.Valid; + +import io.swagger.annotations.ApiModelProperty; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; +import com.fasterxml.jackson.annotation.JsonFormat; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Model for testing reserved words + */ +@ApiModel(description="Model for testing reserved words") +public class ModelReturn { + + @ApiModelProperty(value = "") + private Integer _return; + /** + * Get _return + * @return _return + */ + @JsonProperty("return") + public Integer getReturn() { + return _return; + } + + /** + * Sets the _return property. + */ + public void setReturn(Integer _return) { + this._return = _return; + } + + /** + * Sets the _return property. + */ + public ModelReturn _return(Integer _return) { + this._return = _return; + return this; + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ModelReturn {\n"); + + sb.append(" _return: ").append(toIndentedString(_return)).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 static String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/Name.java b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/Name.java new file mode 100644 index 00000000000..fd07730a978 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/Name.java @@ -0,0 +1,161 @@ +package org.openapitools.model; + +import io.swagger.annotations.ApiModel; +import javax.validation.constraints.*; +import javax.validation.Valid; + +import io.swagger.annotations.ApiModelProperty; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; +import com.fasterxml.jackson.annotation.JsonFormat; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Model for testing model name same as property name + */ +@ApiModel(description="Model for testing model name same as property name") +public class Name { + + @ApiModelProperty(required = true, value = "") + private Integer name; + + @ApiModelProperty(value = "") + private Integer snakeCase; + + @ApiModelProperty(value = "") + private String property; + + @ApiModelProperty(value = "") + private Integer _123number; + /** + * Get name + * @return name + */ + @JsonProperty("name") + @NotNull + public Integer getName() { + return name; + } + + /** + * Sets the name property. + */ + public void setName(Integer name) { + this.name = name; + } + + /** + * Sets the name property. + */ + public Name name(Integer name) { + this.name = name; + return this; + } + + /** + * Get snakeCase + * @return snakeCase + */ + @JsonProperty("snake_case") + public Integer getSnakeCase() { + return snakeCase; + } + + /** + * Sets the snakeCase property. + *
N.B. snakeCase is read only; client code should not call this method. + */ + public void setSnakeCase(Integer snakeCase) { + this.snakeCase = snakeCase; + } + + /** + * Sets the snakeCase property. + *
N.B. snakeCase is read only; client code should not call this method. + */ + public Name snakeCase(Integer snakeCase) { + this.snakeCase = snakeCase; + return this; + } + + /** + * Get property + * @return property + */ + @JsonProperty("property") + public String getProperty() { + return property; + } + + /** + * Sets the property property. + */ + public void setProperty(String property) { + this.property = property; + } + + /** + * Sets the property property. + */ + public Name property(String property) { + this.property = property; + return this; + } + + /** + * Get _123number + * @return _123number + */ + @JsonProperty("123Number") + public Integer get123number() { + return _123number; + } + + /** + * Sets the _123number property. + *
N.B. _123number is read only; client code should not call this method. + */ + public void set123number(Integer _123number) { + this._123number = _123number; + } + + /** + * Sets the _123number property. + *
N.B. _123number is read only; client code should not call this method. + */ + public Name _123number(Integer _123number) { + this._123number = _123number; + return this; + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Name {\n"); + + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" snakeCase: ").append(toIndentedString(snakeCase)).append("\n"); + sb.append(" property: ").append(toIndentedString(property)).append("\n"); + sb.append(" _123number: ").append(toIndentedString(_123number)).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 static String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/NumberOnly.java b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/NumberOnly.java new file mode 100644 index 00000000000..59b9db7ff8d --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/NumberOnly.java @@ -0,0 +1,69 @@ +package org.openapitools.model; + +import java.math.BigDecimal; +import javax.validation.constraints.*; +import javax.validation.Valid; + +import io.swagger.annotations.ApiModelProperty; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; +import com.fasterxml.jackson.annotation.JsonFormat; +import com.fasterxml.jackson.annotation.JsonProperty; + +public class NumberOnly { + + @ApiModelProperty(value = "") + @Valid + private BigDecimal justNumber; + /** + * Get justNumber + * @return justNumber + */ + @JsonProperty("JustNumber") + public BigDecimal getJustNumber() { + return justNumber; + } + + /** + * Sets the justNumber property. + */ + public void setJustNumber(BigDecimal justNumber) { + this.justNumber = justNumber; + } + + /** + * Sets the justNumber property. + */ + public NumberOnly justNumber(BigDecimal justNumber) { + this.justNumber = justNumber; + return this; + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class NumberOnly {\n"); + + sb.append(" justNumber: ").append(toIndentedString(justNumber)).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 static String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/Order.java b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/Order.java new file mode 100644 index 00000000000..5e4092e7b19 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/Order.java @@ -0,0 +1,245 @@ +package org.openapitools.model; + +import java.util.Date; +import javax.validation.constraints.*; +import javax.validation.Valid; + +import io.swagger.annotations.ApiModelProperty; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; +import com.fasterxml.jackson.annotation.JsonFormat; +import com.fasterxml.jackson.annotation.JsonProperty; + +public class Order { + + @ApiModelProperty(value = "") + private Long id; + + @ApiModelProperty(value = "") + private Long petId; + + @ApiModelProperty(value = "") + private Integer quantity; + + @ApiModelProperty(value = "") + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'hh:mm:ss.SSSX") + private Date shipDate; + +@XmlType(name="StatusEnum") +@XmlEnum(String.class) +public enum StatusEnum { + + @XmlEnumValue("placed") @JsonProperty("placed") PLACED(String.valueOf("placed")), + @XmlEnumValue("approved") @JsonProperty("approved") APPROVED(String.valueOf("approved")), + @XmlEnumValue("delivered") @JsonProperty("delivered") DELIVERED(String.valueOf("delivered")); + + private String value; + + StatusEnum (String v) { + value = v; + } + + public String value() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static StatusEnum fromValue(String v) { + for (StatusEnum b : StatusEnum.values()) { + if (String.valueOf(b.value).equals(v)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + v + "'"); + } +} + + /** + * Order Status + */ + @ApiModelProperty(value = "Order Status") + private StatusEnum status; + + @ApiModelProperty(value = "") + private Boolean complete = false; + /** + * Get id + * @return id + */ + @JsonProperty("id") + public Long getId() { + return id; + } + + /** + * Sets the id property. + */ + public void setId(Long id) { + this.id = id; + } + + /** + * Sets the id property. + */ + public Order id(Long id) { + this.id = id; + return this; + } + + /** + * Get petId + * @return petId + */ + @JsonProperty("petId") + public Long getPetId() { + return petId; + } + + /** + * Sets the petId property. + */ + public void setPetId(Long petId) { + this.petId = petId; + } + + /** + * Sets the petId property. + */ + public Order petId(Long petId) { + this.petId = petId; + return this; + } + + /** + * Get quantity + * @return quantity + */ + @JsonProperty("quantity") + public Integer getQuantity() { + return quantity; + } + + /** + * Sets the quantity property. + */ + public void setQuantity(Integer quantity) { + this.quantity = quantity; + } + + /** + * Sets the quantity property. + */ + public Order quantity(Integer quantity) { + this.quantity = quantity; + return this; + } + + /** + * Get shipDate + * @return shipDate + */ + @JsonProperty("shipDate") + public Date getShipDate() { + return shipDate; + } + + /** + * Sets the shipDate property. + */ + public void setShipDate(Date shipDate) { + this.shipDate = shipDate; + } + + /** + * Sets the shipDate property. + */ + public Order shipDate(Date shipDate) { + this.shipDate = shipDate; + return this; + } + + /** + * Order Status + * @return status + */ + @JsonProperty("status") + public String getStatus() { + return status == null ? null : status.value(); + } + + /** + * Sets the status property. + */ + public void setStatus(StatusEnum status) { + this.status = status; + } + + /** + * Sets the status property. + */ + public Order status(StatusEnum status) { + this.status = status; + return this; + } + + /** + * Get complete + * @return complete + */ + @JsonProperty("complete") + public Boolean getComplete() { + return complete; + } + + /** + * Sets the complete property. + */ + public void setComplete(Boolean complete) { + this.complete = complete; + } + + /** + * Sets the complete property. + */ + public Order complete(Boolean complete) { + this.complete = complete; + return this; + } + + + @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("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/OuterComposite.java b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/OuterComposite.java new file mode 100644 index 00000000000..bdc1aaca2f7 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/OuterComposite.java @@ -0,0 +1,125 @@ +package org.openapitools.model; + +import java.math.BigDecimal; +import javax.validation.constraints.*; +import javax.validation.Valid; + +import io.swagger.annotations.ApiModelProperty; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; +import com.fasterxml.jackson.annotation.JsonFormat; +import com.fasterxml.jackson.annotation.JsonProperty; + +public class OuterComposite { + + @ApiModelProperty(value = "") + @Valid + private BigDecimal myNumber; + + @ApiModelProperty(value = "") + private String myString; + + @ApiModelProperty(value = "") + private Boolean myBoolean; + /** + * Get myNumber + * @return myNumber + */ + @JsonProperty("my_number") + public BigDecimal getMyNumber() { + return myNumber; + } + + /** + * Sets the myNumber property. + */ + public void setMyNumber(BigDecimal myNumber) { + this.myNumber = myNumber; + } + + /** + * Sets the myNumber property. + */ + public OuterComposite myNumber(BigDecimal myNumber) { + this.myNumber = myNumber; + return this; + } + + /** + * Get myString + * @return myString + */ + @JsonProperty("my_string") + public String getMyString() { + return myString; + } + + /** + * Sets the myString property. + */ + public void setMyString(String myString) { + this.myString = myString; + } + + /** + * Sets the myString property. + */ + public OuterComposite myString(String myString) { + this.myString = myString; + return this; + } + + /** + * Get myBoolean + * @return myBoolean + */ + @JsonProperty("my_boolean") + public Boolean getMyBoolean() { + return myBoolean; + } + + /** + * Sets the myBoolean property. + */ + public void setMyBoolean(Boolean myBoolean) { + this.myBoolean = myBoolean; + } + + /** + * Sets the myBoolean property. + */ + public OuterComposite myBoolean(Boolean myBoolean) { + this.myBoolean = myBoolean; + return this; + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class OuterComposite {\n"); + + sb.append(" myNumber: ").append(toIndentedString(myNumber)).append("\n"); + sb.append(" myString: ").append(toIndentedString(myString)).append("\n"); + sb.append(" myBoolean: ").append(toIndentedString(myBoolean)).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 static String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/OuterEnum.java b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/OuterEnum.java new file mode 100644 index 00000000000..331eab9acf7 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/OuterEnum.java @@ -0,0 +1,43 @@ +package org.openapitools.model; + +import javax.validation.constraints.*; +import javax.validation.Valid; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Gets or Sets OuterEnum + */ +public enum OuterEnum { + + PLACED("placed"), + + APPROVED("approved"), + + DELIVERED("delivered"); + + private String value; + + OuterEnum(String value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static OuterEnum fromValue(String text) { + for (OuterEnum b : OuterEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + text + "'"); + } + +} + diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/Pet.java b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/Pet.java new file mode 100644 index 00000000000..9919777ec38 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/Pet.java @@ -0,0 +1,267 @@ +package org.openapitools.model; + +import java.util.ArrayList; +import java.util.List; +import org.openapitools.model.Category; +import org.openapitools.model.Tag; +import javax.validation.constraints.*; +import javax.validation.Valid; + +import io.swagger.annotations.ApiModelProperty; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; +import com.fasterxml.jackson.annotation.JsonFormat; +import com.fasterxml.jackson.annotation.JsonProperty; + +public class Pet { + + @ApiModelProperty(value = "") + private Long id; + + @ApiModelProperty(value = "") + @Valid + private Category category = null; + + @ApiModelProperty(example = "doggie", required = true, value = "") + private String name; + + @ApiModelProperty(required = true, value = "") + private List photoUrls = new ArrayList<>(); + + @ApiModelProperty(value = "") + @Valid + private List tags = null; + +@XmlType(name="StatusEnum") +@XmlEnum(String.class) +public enum StatusEnum { + + @XmlEnumValue("available") @JsonProperty("available") AVAILABLE(String.valueOf("available")), + @XmlEnumValue("pending") @JsonProperty("pending") PENDING(String.valueOf("pending")), + @XmlEnumValue("sold") @JsonProperty("sold") SOLD(String.valueOf("sold")); + + private String value; + + StatusEnum (String v) { + value = v; + } + + public String value() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static StatusEnum fromValue(String v) { + for (StatusEnum b : StatusEnum.values()) { + if (String.valueOf(b.value).equals(v)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + v + "'"); + } +} + + /** + * pet status in the store + */ + @ApiModelProperty(value = "pet status in the store") + private StatusEnum status; + /** + * Get id + * @return id + */ + @JsonProperty("id") + public Long getId() { + return id; + } + + /** + * Sets the id property. + */ + public void setId(Long id) { + this.id = id; + } + + /** + * Sets the id property. + */ + public Pet id(Long id) { + this.id = id; + return this; + } + + /** + * Get category + * @return category + */ + @JsonProperty("category") + public Category getCategory() { + return category; + } + + /** + * Sets the category property. + */ + public void setCategory(Category category) { + this.category = category; + } + + /** + * Sets the category property. + */ + public Pet category(Category category) { + this.category = category; + return this; + } + + /** + * Get name + * @return name + */ + @JsonProperty("name") + @NotNull + public String getName() { + return name; + } + + /** + * Sets the name property. + */ + public void setName(String name) { + this.name = name; + } + + /** + * Sets the name property. + */ + public Pet name(String name) { + this.name = name; + return this; + } + + /** + * Get photoUrls + * @return photoUrls + */ + @JsonProperty("photoUrls") + @NotNull + public List getPhotoUrls() { + return photoUrls; + } + + /** + * Sets the photoUrls property. + */ + public void setPhotoUrls(List photoUrls) { + this.photoUrls = photoUrls; + } + + /** + * Sets the photoUrls property. + */ + public Pet photoUrls(List photoUrls) { + this.photoUrls = photoUrls; + return this; + } + + /** + * Adds a new item to the photoUrls list. + */ + public Pet addPhotoUrlsItem(String photoUrlsItem) { + this.photoUrls.add(photoUrlsItem); + return this; + } + + /** + * Get tags + * @return tags + */ + @JsonProperty("tags") + public List getTags() { + return tags; + } + + /** + * Sets the tags property. + */ + public void setTags(List tags) { + this.tags = tags; + } + + /** + * Sets the tags property. + */ + public Pet tags(List tags) { + this.tags = tags; + return this; + } + + /** + * Adds a new item to the tags list. + */ + public Pet addTagsItem(Tag tagsItem) { + this.tags.add(tagsItem); + return this; + } + + /** + * pet status in the store + * @return status + */ + @JsonProperty("status") + public String getStatus() { + return status == null ? null : status.value(); + } + + /** + * Sets the status property. + */ + public void setStatus(StatusEnum status) { + this.status = status; + } + + /** + * Sets the status property. + */ + public Pet status(StatusEnum status) { + this.status = status; + return this; + } + + + @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("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/ReadOnlyFirst.java b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/ReadOnlyFirst.java new file mode 100644 index 00000000000..f265ecabd17 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/ReadOnlyFirst.java @@ -0,0 +1,97 @@ +package org.openapitools.model; + +import javax.validation.constraints.*; +import javax.validation.Valid; + +import io.swagger.annotations.ApiModelProperty; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; +import com.fasterxml.jackson.annotation.JsonFormat; +import com.fasterxml.jackson.annotation.JsonProperty; + +public class ReadOnlyFirst { + + @ApiModelProperty(value = "") + private String bar; + + @ApiModelProperty(value = "") + private String baz; + /** + * Get bar + * @return bar + */ + @JsonProperty("bar") + public String getBar() { + return bar; + } + + /** + * Sets the bar property. + *
N.B. bar is read only; client code should not call this method. + */ + public void setBar(String bar) { + this.bar = bar; + } + + /** + * Sets the bar property. + *
N.B. bar is read only; client code should not call this method. + */ + public ReadOnlyFirst bar(String bar) { + this.bar = bar; + return this; + } + + /** + * Get baz + * @return baz + */ + @JsonProperty("baz") + public String getBaz() { + return baz; + } + + /** + * Sets the baz property. + */ + public void setBaz(String baz) { + this.baz = baz; + } + + /** + * Sets the baz property. + */ + public ReadOnlyFirst baz(String baz) { + this.baz = baz; + return this; + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ReadOnlyFirst {\n"); + + sb.append(" bar: ").append(toIndentedString(bar)).append("\n"); + sb.append(" baz: ").append(toIndentedString(baz)).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 static String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/SpecialModelName.java b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/SpecialModelName.java new file mode 100644 index 00000000000..97b4ab49274 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/SpecialModelName.java @@ -0,0 +1,67 @@ +package org.openapitools.model; + +import javax.validation.constraints.*; +import javax.validation.Valid; + +import io.swagger.annotations.ApiModelProperty; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; +import com.fasterxml.jackson.annotation.JsonFormat; +import com.fasterxml.jackson.annotation.JsonProperty; + +public class SpecialModelName { + + @ApiModelProperty(value = "") + private Long $specialPropertyName; + /** + * Get $specialPropertyName + * @return $specialPropertyName + */ + @JsonProperty("$special[property.name]") + public Long get$SpecialPropertyName() { + return $specialPropertyName; + } + + /** + * Sets the $specialPropertyName property. + */ + public void set$SpecialPropertyName(Long $specialPropertyName) { + this.$specialPropertyName = $specialPropertyName; + } + + /** + * Sets the $specialPropertyName property. + */ + public SpecialModelName $specialPropertyName(Long $specialPropertyName) { + this.$specialPropertyName = $specialPropertyName; + return this; + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class SpecialModelName {\n"); + + sb.append(" $specialPropertyName: ").append(toIndentedString($specialPropertyName)).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 static String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/StringBooleanMap.java b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/StringBooleanMap.java new file mode 100644 index 00000000000..595b94064d3 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/StringBooleanMap.java @@ -0,0 +1,41 @@ +package org.openapitools.model; + +import java.util.HashMap; +import java.util.Map; +import javax.validation.constraints.*; +import javax.validation.Valid; + +import io.swagger.annotations.ApiModelProperty; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; +import com.fasterxml.jackson.annotation.JsonFormat; +import com.fasterxml.jackson.annotation.JsonProperty; + +public class StringBooleanMap extends HashMap { + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class StringBooleanMap {\n"); + sb.append(" ").append(toIndentedString(super.toString())).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 static String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/Tag.java b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/Tag.java new file mode 100644 index 00000000000..3c1cc5afe27 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/Tag.java @@ -0,0 +1,95 @@ +package org.openapitools.model; + +import javax.validation.constraints.*; +import javax.validation.Valid; + +import io.swagger.annotations.ApiModelProperty; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; +import com.fasterxml.jackson.annotation.JsonFormat; +import com.fasterxml.jackson.annotation.JsonProperty; + +public class Tag { + + @ApiModelProperty(value = "") + private Long id; + + @ApiModelProperty(value = "") + private String name; + /** + * Get id + * @return id + */ + @JsonProperty("id") + public Long getId() { + return id; + } + + /** + * Sets the id property. + */ + public void setId(Long id) { + this.id = id; + } + + /** + * Sets the id property. + */ + public Tag id(Long id) { + this.id = id; + return this; + } + + /** + * Get name + * @return name + */ + @JsonProperty("name") + public String getName() { + return name; + } + + /** + * Sets the name property. + */ + public void setName(String name) { + this.name = name; + } + + /** + * Sets the name property. + */ + public Tag name(String name) { + this.name = name; + return this; + } + + + @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("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/TypeHolderDefault.java b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/TypeHolderDefault.java new file mode 100644 index 00000000000..54f512a9a84 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/TypeHolderDefault.java @@ -0,0 +1,196 @@ +package org.openapitools.model; + +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; +import javax.validation.constraints.*; +import javax.validation.Valid; + +import io.swagger.annotations.ApiModelProperty; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; +import com.fasterxml.jackson.annotation.JsonFormat; +import com.fasterxml.jackson.annotation.JsonProperty; + +public class TypeHolderDefault { + + @ApiModelProperty(required = true, value = "") + private String stringItem = "what"; + + @ApiModelProperty(required = true, value = "") + @Valid + private BigDecimal numberItem; + + @ApiModelProperty(required = true, value = "") + private Integer integerItem; + + @ApiModelProperty(required = true, value = "") + private Boolean boolItem = true; + + @ApiModelProperty(required = true, value = "") + private List arrayItem = new ArrayList<>(); + /** + * Get stringItem + * @return stringItem + */ + @JsonProperty("string_item") + @NotNull + public String getStringItem() { + return stringItem; + } + + /** + * Sets the stringItem property. + */ + public void setStringItem(String stringItem) { + this.stringItem = stringItem; + } + + /** + * Sets the stringItem property. + */ + public TypeHolderDefault stringItem(String stringItem) { + this.stringItem = stringItem; + return this; + } + + /** + * Get numberItem + * @return numberItem + */ + @JsonProperty("number_item") + @NotNull + public BigDecimal getNumberItem() { + return numberItem; + } + + /** + * Sets the numberItem property. + */ + public void setNumberItem(BigDecimal numberItem) { + this.numberItem = numberItem; + } + + /** + * Sets the numberItem property. + */ + public TypeHolderDefault numberItem(BigDecimal numberItem) { + this.numberItem = numberItem; + return this; + } + + /** + * Get integerItem + * @return integerItem + */ + @JsonProperty("integer_item") + @NotNull + public Integer getIntegerItem() { + return integerItem; + } + + /** + * Sets the integerItem property. + */ + public void setIntegerItem(Integer integerItem) { + this.integerItem = integerItem; + } + + /** + * Sets the integerItem property. + */ + public TypeHolderDefault integerItem(Integer integerItem) { + this.integerItem = integerItem; + return this; + } + + /** + * Get boolItem + * @return boolItem + */ + @JsonProperty("bool_item") + @NotNull + public Boolean getBoolItem() { + return boolItem; + } + + /** + * Sets the boolItem property. + */ + public void setBoolItem(Boolean boolItem) { + this.boolItem = boolItem; + } + + /** + * Sets the boolItem property. + */ + public TypeHolderDefault boolItem(Boolean boolItem) { + this.boolItem = boolItem; + return this; + } + + /** + * Get arrayItem + * @return arrayItem + */ + @JsonProperty("array_item") + @NotNull + public List getArrayItem() { + return arrayItem; + } + + /** + * Sets the arrayItem property. + */ + public void setArrayItem(List arrayItem) { + this.arrayItem = arrayItem; + } + + /** + * Sets the arrayItem property. + */ + public TypeHolderDefault arrayItem(List arrayItem) { + this.arrayItem = arrayItem; + return this; + } + + /** + * Adds a new item to the arrayItem list. + */ + public TypeHolderDefault addArrayItemItem(Integer arrayItemItem) { + this.arrayItem.add(arrayItemItem); + return this; + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class TypeHolderDefault {\n"); + + sb.append(" stringItem: ").append(toIndentedString(stringItem)).append("\n"); + sb.append(" numberItem: ").append(toIndentedString(numberItem)).append("\n"); + sb.append(" integerItem: ").append(toIndentedString(integerItem)).append("\n"); + sb.append(" boolItem: ").append(toIndentedString(boolItem)).append("\n"); + sb.append(" arrayItem: ").append(toIndentedString(arrayItem)).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 static String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/TypeHolderExample.java b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/TypeHolderExample.java new file mode 100644 index 00000000000..a94ba528deb --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/TypeHolderExample.java @@ -0,0 +1,196 @@ +package org.openapitools.model; + +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; +import javax.validation.constraints.*; +import javax.validation.Valid; + +import io.swagger.annotations.ApiModelProperty; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; +import com.fasterxml.jackson.annotation.JsonFormat; +import com.fasterxml.jackson.annotation.JsonProperty; + +public class TypeHolderExample { + + @ApiModelProperty(example = "what", required = true, value = "") + private String stringItem; + + @ApiModelProperty(example = "1.234", required = true, value = "") + @Valid + private BigDecimal numberItem; + + @ApiModelProperty(example = "-2", required = true, value = "") + private Integer integerItem; + + @ApiModelProperty(example = "true", required = true, value = "") + private Boolean boolItem; + + @ApiModelProperty(example = "[0, 1, 2, 3]", required = true, value = "") + private List arrayItem = new ArrayList<>(); + /** + * Get stringItem + * @return stringItem + */ + @JsonProperty("string_item") + @NotNull + public String getStringItem() { + return stringItem; + } + + /** + * Sets the stringItem property. + */ + public void setStringItem(String stringItem) { + this.stringItem = stringItem; + } + + /** + * Sets the stringItem property. + */ + public TypeHolderExample stringItem(String stringItem) { + this.stringItem = stringItem; + return this; + } + + /** + * Get numberItem + * @return numberItem + */ + @JsonProperty("number_item") + @NotNull + public BigDecimal getNumberItem() { + return numberItem; + } + + /** + * Sets the numberItem property. + */ + public void setNumberItem(BigDecimal numberItem) { + this.numberItem = numberItem; + } + + /** + * Sets the numberItem property. + */ + public TypeHolderExample numberItem(BigDecimal numberItem) { + this.numberItem = numberItem; + return this; + } + + /** + * Get integerItem + * @return integerItem + */ + @JsonProperty("integer_item") + @NotNull + public Integer getIntegerItem() { + return integerItem; + } + + /** + * Sets the integerItem property. + */ + public void setIntegerItem(Integer integerItem) { + this.integerItem = integerItem; + } + + /** + * Sets the integerItem property. + */ + public TypeHolderExample integerItem(Integer integerItem) { + this.integerItem = integerItem; + return this; + } + + /** + * Get boolItem + * @return boolItem + */ + @JsonProperty("bool_item") + @NotNull + public Boolean getBoolItem() { + return boolItem; + } + + /** + * Sets the boolItem property. + */ + public void setBoolItem(Boolean boolItem) { + this.boolItem = boolItem; + } + + /** + * Sets the boolItem property. + */ + public TypeHolderExample boolItem(Boolean boolItem) { + this.boolItem = boolItem; + return this; + } + + /** + * Get arrayItem + * @return arrayItem + */ + @JsonProperty("array_item") + @NotNull + public List getArrayItem() { + return arrayItem; + } + + /** + * Sets the arrayItem property. + */ + public void setArrayItem(List arrayItem) { + this.arrayItem = arrayItem; + } + + /** + * Sets the arrayItem property. + */ + public TypeHolderExample arrayItem(List arrayItem) { + this.arrayItem = arrayItem; + return this; + } + + /** + * Adds a new item to the arrayItem list. + */ + public TypeHolderExample addArrayItemItem(Integer arrayItemItem) { + this.arrayItem.add(arrayItemItem); + return this; + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class TypeHolderExample {\n"); + + sb.append(" stringItem: ").append(toIndentedString(stringItem)).append("\n"); + sb.append(" numberItem: ").append(toIndentedString(numberItem)).append("\n"); + sb.append(" integerItem: ").append(toIndentedString(integerItem)).append("\n"); + sb.append(" boolItem: ").append(toIndentedString(boolItem)).append("\n"); + sb.append(" arrayItem: ").append(toIndentedString(arrayItem)).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 static String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/User.java b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/User.java new file mode 100644 index 00000000000..232586cec73 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/User.java @@ -0,0 +1,266 @@ +package org.openapitools.model; + +import javax.validation.constraints.*; +import javax.validation.Valid; + +import io.swagger.annotations.ApiModelProperty; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; +import com.fasterxml.jackson.annotation.JsonFormat; +import com.fasterxml.jackson.annotation.JsonProperty; + +public class User { + + @ApiModelProperty(value = "") + private Long id; + + @ApiModelProperty(value = "") + private String username; + + @ApiModelProperty(value = "") + private String firstName; + + @ApiModelProperty(value = "") + private String lastName; + + @ApiModelProperty(value = "") + private String email; + + @ApiModelProperty(value = "") + private String password; + + @ApiModelProperty(value = "") + private String phone; + + /** + * User Status + */ + @ApiModelProperty(value = "User Status") + private Integer userStatus; + /** + * Get id + * @return id + */ + @JsonProperty("id") + public Long getId() { + return id; + } + + /** + * Sets the id property. + */ + public void setId(Long id) { + this.id = id; + } + + /** + * Sets the id property. + */ + public User id(Long id) { + this.id = id; + return this; + } + + /** + * Get username + * @return username + */ + @JsonProperty("username") + public String getUsername() { + return username; + } + + /** + * Sets the username property. + */ + public void setUsername(String username) { + this.username = username; + } + + /** + * Sets the username property. + */ + public User username(String username) { + this.username = username; + return this; + } + + /** + * Get firstName + * @return firstName + */ + @JsonProperty("firstName") + public String getFirstName() { + return firstName; + } + + /** + * Sets the firstName property. + */ + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + /** + * Sets the firstName property. + */ + public User firstName(String firstName) { + this.firstName = firstName; + return this; + } + + /** + * Get lastName + * @return lastName + */ + @JsonProperty("lastName") + public String getLastName() { + return lastName; + } + + /** + * Sets the lastName property. + */ + public void setLastName(String lastName) { + this.lastName = lastName; + } + + /** + * Sets the lastName property. + */ + public User lastName(String lastName) { + this.lastName = lastName; + return this; + } + + /** + * Get email + * @return email + */ + @JsonProperty("email") + public String getEmail() { + return email; + } + + /** + * Sets the email property. + */ + public void setEmail(String email) { + this.email = email; + } + + /** + * Sets the email property. + */ + public User email(String email) { + this.email = email; + return this; + } + + /** + * Get password + * @return password + */ + @JsonProperty("password") + public String getPassword() { + return password; + } + + /** + * Sets the password property. + */ + public void setPassword(String password) { + this.password = password; + } + + /** + * Sets the password property. + */ + public User password(String password) { + this.password = password; + return this; + } + + /** + * Get phone + * @return phone + */ + @JsonProperty("phone") + public String getPhone() { + return phone; + } + + /** + * Sets the phone property. + */ + public void setPhone(String phone) { + this.phone = phone; + } + + /** + * Sets the phone property. + */ + public User phone(String phone) { + this.phone = phone; + return this; + } + + /** + * User Status + * @return userStatus + */ + @JsonProperty("userStatus") + public Integer getUserStatus() { + return userStatus; + } + + /** + * Sets the userStatus property. + */ + public void setUserStatus(Integer userStatus) { + this.userStatus = userStatus; + } + + /** + * Sets the userStatus property. + */ + public User userStatus(Integer userStatus) { + this.userStatus = userStatus; + return this; + } + + + @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("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/XmlItem.java b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/XmlItem.java new file mode 100644 index 00000000000..5f5af932236 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/XmlItem.java @@ -0,0 +1,931 @@ +package org.openapitools.model; + +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; +import javax.validation.constraints.*; +import javax.validation.Valid; + +import io.swagger.annotations.ApiModelProperty; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; +import com.fasterxml.jackson.annotation.JsonFormat; +import com.fasterxml.jackson.annotation.JsonProperty; + +public class XmlItem { + + @ApiModelProperty(example = "string", value = "") + private String attributeString; + + @ApiModelProperty(example = "1.234", value = "") + @Valid + private BigDecimal attributeNumber; + + @ApiModelProperty(example = "-2", value = "") + private Integer attributeInteger; + + @ApiModelProperty(example = "true", value = "") + private Boolean attributeBoolean; + + @ApiModelProperty(value = "") + private List wrappedArray = null; + + @ApiModelProperty(example = "string", value = "") + private String nameString; + + @ApiModelProperty(example = "1.234", value = "") + @Valid + private BigDecimal nameNumber; + + @ApiModelProperty(example = "-2", value = "") + private Integer nameInteger; + + @ApiModelProperty(example = "true", value = "") + private Boolean nameBoolean; + + @ApiModelProperty(value = "") + private List nameArray = null; + + @ApiModelProperty(value = "") + private List nameWrappedArray = null; + + @ApiModelProperty(example = "string", value = "") + private String prefixString; + + @ApiModelProperty(example = "1.234", value = "") + @Valid + private BigDecimal prefixNumber; + + @ApiModelProperty(example = "-2", value = "") + private Integer prefixInteger; + + @ApiModelProperty(example = "true", value = "") + private Boolean prefixBoolean; + + @ApiModelProperty(value = "") + private List prefixArray = null; + + @ApiModelProperty(value = "") + private List prefixWrappedArray = null; + + @ApiModelProperty(example = "string", value = "") + private String namespaceString; + + @ApiModelProperty(example = "1.234", value = "") + @Valid + private BigDecimal namespaceNumber; + + @ApiModelProperty(example = "-2", value = "") + private Integer namespaceInteger; + + @ApiModelProperty(example = "true", value = "") + private Boolean namespaceBoolean; + + @ApiModelProperty(value = "") + private List namespaceArray = null; + + @ApiModelProperty(value = "") + private List namespaceWrappedArray = null; + + @ApiModelProperty(example = "string", value = "") + private String prefixNsString; + + @ApiModelProperty(example = "1.234", value = "") + @Valid + private BigDecimal prefixNsNumber; + + @ApiModelProperty(example = "-2", value = "") + private Integer prefixNsInteger; + + @ApiModelProperty(example = "true", value = "") + private Boolean prefixNsBoolean; + + @ApiModelProperty(value = "") + private List prefixNsArray = null; + + @ApiModelProperty(value = "") + private List prefixNsWrappedArray = null; + /** + * Get attributeString + * @return attributeString + */ + @JsonProperty("attribute_string") + public String getAttributeString() { + return attributeString; + } + + /** + * Sets the attributeString property. + */ + public void setAttributeString(String attributeString) { + this.attributeString = attributeString; + } + + /** + * Sets the attributeString property. + */ + public XmlItem attributeString(String attributeString) { + this.attributeString = attributeString; + return this; + } + + /** + * Get attributeNumber + * @return attributeNumber + */ + @JsonProperty("attribute_number") + public BigDecimal getAttributeNumber() { + return attributeNumber; + } + + /** + * Sets the attributeNumber property. + */ + public void setAttributeNumber(BigDecimal attributeNumber) { + this.attributeNumber = attributeNumber; + } + + /** + * Sets the attributeNumber property. + */ + public XmlItem attributeNumber(BigDecimal attributeNumber) { + this.attributeNumber = attributeNumber; + return this; + } + + /** + * Get attributeInteger + * @return attributeInteger + */ + @JsonProperty("attribute_integer") + public Integer getAttributeInteger() { + return attributeInteger; + } + + /** + * Sets the attributeInteger property. + */ + public void setAttributeInteger(Integer attributeInteger) { + this.attributeInteger = attributeInteger; + } + + /** + * Sets the attributeInteger property. + */ + public XmlItem attributeInteger(Integer attributeInteger) { + this.attributeInteger = attributeInteger; + return this; + } + + /** + * Get attributeBoolean + * @return attributeBoolean + */ + @JsonProperty("attribute_boolean") + public Boolean getAttributeBoolean() { + return attributeBoolean; + } + + /** + * Sets the attributeBoolean property. + */ + public void setAttributeBoolean(Boolean attributeBoolean) { + this.attributeBoolean = attributeBoolean; + } + + /** + * Sets the attributeBoolean property. + */ + public XmlItem attributeBoolean(Boolean attributeBoolean) { + this.attributeBoolean = attributeBoolean; + return this; + } + + /** + * Get wrappedArray + * @return wrappedArray + */ + @JsonProperty("wrapped_array") + public List getWrappedArray() { + return wrappedArray; + } + + /** + * Sets the wrappedArray property. + */ + public void setWrappedArray(List wrappedArray) { + this.wrappedArray = wrappedArray; + } + + /** + * Sets the wrappedArray property. + */ + public XmlItem wrappedArray(List wrappedArray) { + this.wrappedArray = wrappedArray; + return this; + } + + /** + * Adds a new item to the wrappedArray list. + */ + public XmlItem addWrappedArrayItem(Integer wrappedArrayItem) { + this.wrappedArray.add(wrappedArrayItem); + return this; + } + + /** + * Get nameString + * @return nameString + */ + @JsonProperty("name_string") + public String getNameString() { + return nameString; + } + + /** + * Sets the nameString property. + */ + public void setNameString(String nameString) { + this.nameString = nameString; + } + + /** + * Sets the nameString property. + */ + public XmlItem nameString(String nameString) { + this.nameString = nameString; + return this; + } + + /** + * Get nameNumber + * @return nameNumber + */ + @JsonProperty("name_number") + public BigDecimal getNameNumber() { + return nameNumber; + } + + /** + * Sets the nameNumber property. + */ + public void setNameNumber(BigDecimal nameNumber) { + this.nameNumber = nameNumber; + } + + /** + * Sets the nameNumber property. + */ + public XmlItem nameNumber(BigDecimal nameNumber) { + this.nameNumber = nameNumber; + return this; + } + + /** + * Get nameInteger + * @return nameInteger + */ + @JsonProperty("name_integer") + public Integer getNameInteger() { + return nameInteger; + } + + /** + * Sets the nameInteger property. + */ + public void setNameInteger(Integer nameInteger) { + this.nameInteger = nameInteger; + } + + /** + * Sets the nameInteger property. + */ + public XmlItem nameInteger(Integer nameInteger) { + this.nameInteger = nameInteger; + return this; + } + + /** + * Get nameBoolean + * @return nameBoolean + */ + @JsonProperty("name_boolean") + public Boolean getNameBoolean() { + return nameBoolean; + } + + /** + * Sets the nameBoolean property. + */ + public void setNameBoolean(Boolean nameBoolean) { + this.nameBoolean = nameBoolean; + } + + /** + * Sets the nameBoolean property. + */ + public XmlItem nameBoolean(Boolean nameBoolean) { + this.nameBoolean = nameBoolean; + return this; + } + + /** + * Get nameArray + * @return nameArray + */ + @JsonProperty("name_array") + public List getNameArray() { + return nameArray; + } + + /** + * Sets the nameArray property. + */ + public void setNameArray(List nameArray) { + this.nameArray = nameArray; + } + + /** + * Sets the nameArray property. + */ + public XmlItem nameArray(List nameArray) { + this.nameArray = nameArray; + return this; + } + + /** + * Adds a new item to the nameArray list. + */ + public XmlItem addNameArrayItem(Integer nameArrayItem) { + this.nameArray.add(nameArrayItem); + return this; + } + + /** + * Get nameWrappedArray + * @return nameWrappedArray + */ + @JsonProperty("name_wrapped_array") + public List getNameWrappedArray() { + return nameWrappedArray; + } + + /** + * Sets the nameWrappedArray property. + */ + public void setNameWrappedArray(List nameWrappedArray) { + this.nameWrappedArray = nameWrappedArray; + } + + /** + * Sets the nameWrappedArray property. + */ + public XmlItem nameWrappedArray(List nameWrappedArray) { + this.nameWrappedArray = nameWrappedArray; + return this; + } + + /** + * Adds a new item to the nameWrappedArray list. + */ + public XmlItem addNameWrappedArrayItem(Integer nameWrappedArrayItem) { + this.nameWrappedArray.add(nameWrappedArrayItem); + return this; + } + + /** + * Get prefixString + * @return prefixString + */ + @JsonProperty("prefix_string") + public String getPrefixString() { + return prefixString; + } + + /** + * Sets the prefixString property. + */ + public void setPrefixString(String prefixString) { + this.prefixString = prefixString; + } + + /** + * Sets the prefixString property. + */ + public XmlItem prefixString(String prefixString) { + this.prefixString = prefixString; + return this; + } + + /** + * Get prefixNumber + * @return prefixNumber + */ + @JsonProperty("prefix_number") + public BigDecimal getPrefixNumber() { + return prefixNumber; + } + + /** + * Sets the prefixNumber property. + */ + public void setPrefixNumber(BigDecimal prefixNumber) { + this.prefixNumber = prefixNumber; + } + + /** + * Sets the prefixNumber property. + */ + public XmlItem prefixNumber(BigDecimal prefixNumber) { + this.prefixNumber = prefixNumber; + return this; + } + + /** + * Get prefixInteger + * @return prefixInteger + */ + @JsonProperty("prefix_integer") + public Integer getPrefixInteger() { + return prefixInteger; + } + + /** + * Sets the prefixInteger property. + */ + public void setPrefixInteger(Integer prefixInteger) { + this.prefixInteger = prefixInteger; + } + + /** + * Sets the prefixInteger property. + */ + public XmlItem prefixInteger(Integer prefixInteger) { + this.prefixInteger = prefixInteger; + return this; + } + + /** + * Get prefixBoolean + * @return prefixBoolean + */ + @JsonProperty("prefix_boolean") + public Boolean getPrefixBoolean() { + return prefixBoolean; + } + + /** + * Sets the prefixBoolean property. + */ + public void setPrefixBoolean(Boolean prefixBoolean) { + this.prefixBoolean = prefixBoolean; + } + + /** + * Sets the prefixBoolean property. + */ + public XmlItem prefixBoolean(Boolean prefixBoolean) { + this.prefixBoolean = prefixBoolean; + return this; + } + + /** + * Get prefixArray + * @return prefixArray + */ + @JsonProperty("prefix_array") + public List getPrefixArray() { + return prefixArray; + } + + /** + * Sets the prefixArray property. + */ + public void setPrefixArray(List prefixArray) { + this.prefixArray = prefixArray; + } + + /** + * Sets the prefixArray property. + */ + public XmlItem prefixArray(List prefixArray) { + this.prefixArray = prefixArray; + return this; + } + + /** + * Adds a new item to the prefixArray list. + */ + public XmlItem addPrefixArrayItem(Integer prefixArrayItem) { + this.prefixArray.add(prefixArrayItem); + return this; + } + + /** + * Get prefixWrappedArray + * @return prefixWrappedArray + */ + @JsonProperty("prefix_wrapped_array") + public List getPrefixWrappedArray() { + return prefixWrappedArray; + } + + /** + * Sets the prefixWrappedArray property. + */ + public void setPrefixWrappedArray(List prefixWrappedArray) { + this.prefixWrappedArray = prefixWrappedArray; + } + + /** + * Sets the prefixWrappedArray property. + */ + public XmlItem prefixWrappedArray(List prefixWrappedArray) { + this.prefixWrappedArray = prefixWrappedArray; + return this; + } + + /** + * Adds a new item to the prefixWrappedArray list. + */ + public XmlItem addPrefixWrappedArrayItem(Integer prefixWrappedArrayItem) { + this.prefixWrappedArray.add(prefixWrappedArrayItem); + return this; + } + + /** + * Get namespaceString + * @return namespaceString + */ + @JsonProperty("namespace_string") + public String getNamespaceString() { + return namespaceString; + } + + /** + * Sets the namespaceString property. + */ + public void setNamespaceString(String namespaceString) { + this.namespaceString = namespaceString; + } + + /** + * Sets the namespaceString property. + */ + public XmlItem namespaceString(String namespaceString) { + this.namespaceString = namespaceString; + return this; + } + + /** + * Get namespaceNumber + * @return namespaceNumber + */ + @JsonProperty("namespace_number") + public BigDecimal getNamespaceNumber() { + return namespaceNumber; + } + + /** + * Sets the namespaceNumber property. + */ + public void setNamespaceNumber(BigDecimal namespaceNumber) { + this.namespaceNumber = namespaceNumber; + } + + /** + * Sets the namespaceNumber property. + */ + public XmlItem namespaceNumber(BigDecimal namespaceNumber) { + this.namespaceNumber = namespaceNumber; + return this; + } + + /** + * Get namespaceInteger + * @return namespaceInteger + */ + @JsonProperty("namespace_integer") + public Integer getNamespaceInteger() { + return namespaceInteger; + } + + /** + * Sets the namespaceInteger property. + */ + public void setNamespaceInteger(Integer namespaceInteger) { + this.namespaceInteger = namespaceInteger; + } + + /** + * Sets the namespaceInteger property. + */ + public XmlItem namespaceInteger(Integer namespaceInteger) { + this.namespaceInteger = namespaceInteger; + return this; + } + + /** + * Get namespaceBoolean + * @return namespaceBoolean + */ + @JsonProperty("namespace_boolean") + public Boolean getNamespaceBoolean() { + return namespaceBoolean; + } + + /** + * Sets the namespaceBoolean property. + */ + public void setNamespaceBoolean(Boolean namespaceBoolean) { + this.namespaceBoolean = namespaceBoolean; + } + + /** + * Sets the namespaceBoolean property. + */ + public XmlItem namespaceBoolean(Boolean namespaceBoolean) { + this.namespaceBoolean = namespaceBoolean; + return this; + } + + /** + * Get namespaceArray + * @return namespaceArray + */ + @JsonProperty("namespace_array") + public List getNamespaceArray() { + return namespaceArray; + } + + /** + * Sets the namespaceArray property. + */ + public void setNamespaceArray(List namespaceArray) { + this.namespaceArray = namespaceArray; + } + + /** + * Sets the namespaceArray property. + */ + public XmlItem namespaceArray(List namespaceArray) { + this.namespaceArray = namespaceArray; + return this; + } + + /** + * Adds a new item to the namespaceArray list. + */ + public XmlItem addNamespaceArrayItem(Integer namespaceArrayItem) { + this.namespaceArray.add(namespaceArrayItem); + return this; + } + + /** + * Get namespaceWrappedArray + * @return namespaceWrappedArray + */ + @JsonProperty("namespace_wrapped_array") + public List getNamespaceWrappedArray() { + return namespaceWrappedArray; + } + + /** + * Sets the namespaceWrappedArray property. + */ + public void setNamespaceWrappedArray(List namespaceWrappedArray) { + this.namespaceWrappedArray = namespaceWrappedArray; + } + + /** + * Sets the namespaceWrappedArray property. + */ + public XmlItem namespaceWrappedArray(List namespaceWrappedArray) { + this.namespaceWrappedArray = namespaceWrappedArray; + return this; + } + + /** + * Adds a new item to the namespaceWrappedArray list. + */ + public XmlItem addNamespaceWrappedArrayItem(Integer namespaceWrappedArrayItem) { + this.namespaceWrappedArray.add(namespaceWrappedArrayItem); + return this; + } + + /** + * Get prefixNsString + * @return prefixNsString + */ + @JsonProperty("prefix_ns_string") + public String getPrefixNsString() { + return prefixNsString; + } + + /** + * Sets the prefixNsString property. + */ + public void setPrefixNsString(String prefixNsString) { + this.prefixNsString = prefixNsString; + } + + /** + * Sets the prefixNsString property. + */ + public XmlItem prefixNsString(String prefixNsString) { + this.prefixNsString = prefixNsString; + return this; + } + + /** + * Get prefixNsNumber + * @return prefixNsNumber + */ + @JsonProperty("prefix_ns_number") + public BigDecimal getPrefixNsNumber() { + return prefixNsNumber; + } + + /** + * Sets the prefixNsNumber property. + */ + public void setPrefixNsNumber(BigDecimal prefixNsNumber) { + this.prefixNsNumber = prefixNsNumber; + } + + /** + * Sets the prefixNsNumber property. + */ + public XmlItem prefixNsNumber(BigDecimal prefixNsNumber) { + this.prefixNsNumber = prefixNsNumber; + return this; + } + + /** + * Get prefixNsInteger + * @return prefixNsInteger + */ + @JsonProperty("prefix_ns_integer") + public Integer getPrefixNsInteger() { + return prefixNsInteger; + } + + /** + * Sets the prefixNsInteger property. + */ + public void setPrefixNsInteger(Integer prefixNsInteger) { + this.prefixNsInteger = prefixNsInteger; + } + + /** + * Sets the prefixNsInteger property. + */ + public XmlItem prefixNsInteger(Integer prefixNsInteger) { + this.prefixNsInteger = prefixNsInteger; + return this; + } + + /** + * Get prefixNsBoolean + * @return prefixNsBoolean + */ + @JsonProperty("prefix_ns_boolean") + public Boolean getPrefixNsBoolean() { + return prefixNsBoolean; + } + + /** + * Sets the prefixNsBoolean property. + */ + public void setPrefixNsBoolean(Boolean prefixNsBoolean) { + this.prefixNsBoolean = prefixNsBoolean; + } + + /** + * Sets the prefixNsBoolean property. + */ + public XmlItem prefixNsBoolean(Boolean prefixNsBoolean) { + this.prefixNsBoolean = prefixNsBoolean; + return this; + } + + /** + * Get prefixNsArray + * @return prefixNsArray + */ + @JsonProperty("prefix_ns_array") + public List getPrefixNsArray() { + return prefixNsArray; + } + + /** + * Sets the prefixNsArray property. + */ + public void setPrefixNsArray(List prefixNsArray) { + this.prefixNsArray = prefixNsArray; + } + + /** + * Sets the prefixNsArray property. + */ + public XmlItem prefixNsArray(List prefixNsArray) { + this.prefixNsArray = prefixNsArray; + return this; + } + + /** + * Adds a new item to the prefixNsArray list. + */ + public XmlItem addPrefixNsArrayItem(Integer prefixNsArrayItem) { + this.prefixNsArray.add(prefixNsArrayItem); + return this; + } + + /** + * Get prefixNsWrappedArray + * @return prefixNsWrappedArray + */ + @JsonProperty("prefix_ns_wrapped_array") + public List getPrefixNsWrappedArray() { + return prefixNsWrappedArray; + } + + /** + * Sets the prefixNsWrappedArray property. + */ + public void setPrefixNsWrappedArray(List prefixNsWrappedArray) { + this.prefixNsWrappedArray = prefixNsWrappedArray; + } + + /** + * Sets the prefixNsWrappedArray property. + */ + public XmlItem prefixNsWrappedArray(List prefixNsWrappedArray) { + this.prefixNsWrappedArray = prefixNsWrappedArray; + return this; + } + + /** + * Adds a new item to the prefixNsWrappedArray list. + */ + public XmlItem addPrefixNsWrappedArrayItem(Integer prefixNsWrappedArrayItem) { + this.prefixNsWrappedArray.add(prefixNsWrappedArrayItem); + return this; + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class XmlItem {\n"); + + sb.append(" attributeString: ").append(toIndentedString(attributeString)).append("\n"); + sb.append(" attributeNumber: ").append(toIndentedString(attributeNumber)).append("\n"); + sb.append(" attributeInteger: ").append(toIndentedString(attributeInteger)).append("\n"); + sb.append(" attributeBoolean: ").append(toIndentedString(attributeBoolean)).append("\n"); + sb.append(" wrappedArray: ").append(toIndentedString(wrappedArray)).append("\n"); + sb.append(" nameString: ").append(toIndentedString(nameString)).append("\n"); + sb.append(" nameNumber: ").append(toIndentedString(nameNumber)).append("\n"); + sb.append(" nameInteger: ").append(toIndentedString(nameInteger)).append("\n"); + sb.append(" nameBoolean: ").append(toIndentedString(nameBoolean)).append("\n"); + sb.append(" nameArray: ").append(toIndentedString(nameArray)).append("\n"); + sb.append(" nameWrappedArray: ").append(toIndentedString(nameWrappedArray)).append("\n"); + sb.append(" prefixString: ").append(toIndentedString(prefixString)).append("\n"); + sb.append(" prefixNumber: ").append(toIndentedString(prefixNumber)).append("\n"); + sb.append(" prefixInteger: ").append(toIndentedString(prefixInteger)).append("\n"); + sb.append(" prefixBoolean: ").append(toIndentedString(prefixBoolean)).append("\n"); + sb.append(" prefixArray: ").append(toIndentedString(prefixArray)).append("\n"); + sb.append(" prefixWrappedArray: ").append(toIndentedString(prefixWrappedArray)).append("\n"); + sb.append(" namespaceString: ").append(toIndentedString(namespaceString)).append("\n"); + sb.append(" namespaceNumber: ").append(toIndentedString(namespaceNumber)).append("\n"); + sb.append(" namespaceInteger: ").append(toIndentedString(namespaceInteger)).append("\n"); + sb.append(" namespaceBoolean: ").append(toIndentedString(namespaceBoolean)).append("\n"); + sb.append(" namespaceArray: ").append(toIndentedString(namespaceArray)).append("\n"); + sb.append(" namespaceWrappedArray: ").append(toIndentedString(namespaceWrappedArray)).append("\n"); + sb.append(" prefixNsString: ").append(toIndentedString(prefixNsString)).append("\n"); + sb.append(" prefixNsNumber: ").append(toIndentedString(prefixNsNumber)).append("\n"); + sb.append(" prefixNsInteger: ").append(toIndentedString(prefixNsInteger)).append("\n"); + sb.append(" prefixNsBoolean: ").append(toIndentedString(prefixNsBoolean)).append("\n"); + sb.append(" prefixNsArray: ").append(toIndentedString(prefixNsArray)).append("\n"); + sb.append(" prefixNsWrappedArray: ").append(toIndentedString(prefixNsWrappedArray)).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 static String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/main/java/org/openapitools/api/impl/AnotherFakeApiServiceImpl.java b/samples/server/petstore/jaxrs-cxf-test-data/src/main/java/org/openapitools/api/impl/AnotherFakeApiServiceImpl.java new file mode 100644 index 00000000000..acc74579d5f --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/main/java/org/openapitools/api/impl/AnotherFakeApiServiceImpl.java @@ -0,0 +1,61 @@ +package org.openapitools.api.impl; + +import org.openapitools.api.*; +import org.openapitools.model.Client; +import java.util.List; +import java.util.Map; + +import java.io.InputStream; +import java.io.OutputStream; +import java.util.List; +import java.util.Map; +import java.io.File; +import com.fasterxml.jackson.databind.node.JsonNodeFactory; +import com.fasterxml.jackson.databind.node.ObjectNode; +import org.openapitools.codegen.utils.JsonCache; +import org.openapitools.codegen.utils.JsonCache.CacheException; +import javax.ws.rs.*; +import javax.ws.rs.core.Response; +import org.apache.cxf.jaxrs.model.wadl.Description; +import org.apache.cxf.jaxrs.model.wadl.DocTarget; + +import org.apache.cxf.jaxrs.ext.multipart.*; + +import io.swagger.annotations.Api; + +/** + * 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: \" \\ + * + */ +public class AnotherFakeApiServiceImpl implements AnotherFakeApi { + private JsonCache cache; + + { + try { + File cacheFile = new File(System.getProperty("jaxrs.test.server.json", + "/Users/williamcheng/Code/demonfiddler/samples/server/petstore/jaxrs-cxf-test-data/src/main/resources/test-data.json")); + cache = JsonCache.Factory.instance.get("test-data").load(cacheFile).child("/org.openapitools.api/AnotherFakeApi"); + } catch (CacheException e) { + e.printStackTrace(); + } + } + + /** + * To test special tags + * + * To test special tags and operation ID starting with number + * + */ + @Override + public Client call123testSpecialTags(Client body) { + try { + Client response = cache.getObject("/call123testSpecialTags/response", Client.class); + return response; + } catch (CacheException e) { + throw new RuntimeException(e); + } + } + +} diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/main/java/org/openapitools/api/impl/FakeApiServiceImpl.java b/samples/server/petstore/jaxrs-cxf-test-data/src/main/java/org/openapitools/api/impl/FakeApiServiceImpl.java new file mode 100644 index 00000000000..2a49e0cd9e8 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/main/java/org/openapitools/api/impl/FakeApiServiceImpl.java @@ -0,0 +1,181 @@ +package org.openapitools.api.impl; + +import org.openapitools.api.*; +import java.math.BigDecimal; +import org.openapitools.model.Client; +import java.util.Date; +import java.io.File; +import org.openapitools.model.FileSchemaTestClass; +import java.util.List; +import org.joda.time.LocalDate; +import java.util.Map; +import org.openapitools.model.OuterComposite; +import org.openapitools.model.User; +import org.openapitools.model.XmlItem; + +import java.io.InputStream; +import java.io.OutputStream; +import java.util.List; +import java.util.Map; +import java.io.File; +import com.fasterxml.jackson.databind.node.JsonNodeFactory; +import com.fasterxml.jackson.databind.node.ObjectNode; +import org.openapitools.codegen.utils.JsonCache; +import org.openapitools.codegen.utils.JsonCache.CacheException; +import javax.ws.rs.*; +import javax.ws.rs.core.Response; +import org.apache.cxf.jaxrs.model.wadl.Description; +import org.apache.cxf.jaxrs.model.wadl.DocTarget; + +import org.apache.cxf.jaxrs.ext.multipart.*; + +import io.swagger.annotations.Api; + +/** + * 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: \" \\ + * + */ +public class FakeApiServiceImpl implements FakeApi { + private JsonCache cache; + + { + try { + File cacheFile = new File(System.getProperty("jaxrs.test.server.json", + "/Users/williamcheng/Code/demonfiddler/samples/server/petstore/jaxrs-cxf-test-data/src/main/resources/test-data.json")); + cache = JsonCache.Factory.instance.get("test-data").load(cacheFile).child("/org.openapitools.api/FakeApi"); + } catch (CacheException e) { + e.printStackTrace(); + } + } + + /** + * creates an XmlItem + * + * this route creates an XmlItem + * + */ + @Override + public void createXmlItem(XmlItem xmlItem) { + + } + + @Override + public Boolean fakeOuterBooleanSerialize(Boolean body) { + try { + Boolean response = cache.getBoolean("/fakeOuterBooleanSerialize/response"); + return response; + } catch (CacheException e) { + throw new RuntimeException(e); + } + } + + @Override + public OuterComposite fakeOuterCompositeSerialize(OuterComposite body) { + try { + OuterComposite response = cache.getObject("/fakeOuterCompositeSerialize/response", OuterComposite.class); + return response; + } catch (CacheException e) { + throw new RuntimeException(e); + } + } + + @Override + public BigDecimal fakeOuterNumberSerialize(BigDecimal body) { + try { + BigDecimal response = cache.getBigDecimal("/fakeOuterNumberSerialize/response"); + return response; + } catch (CacheException e) { + throw new RuntimeException(e); + } + } + + @Override + public String fakeOuterStringSerialize(String body) { + try { + String response = cache.getString("/fakeOuterStringSerialize/response"); + return response; + } catch (CacheException e) { + throw new RuntimeException(e); + } + } + + @Override + public void testBodyWithFileSchema(FileSchemaTestClass body) { + + } + + @Override + public void testBodyWithQueryParams(String query, User body) { + + } + + /** + * To test \"client\" model + * + * To test \"client\" model + * + */ + @Override + public Client testClientModel(Client body) { + try { + Client response = cache.getObject("/testClientModel/response", Client.class); + return response; + } catch (CacheException e) { + throw new RuntimeException(e); + } + } + + /** + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * + */ + @Override + public void testEndpointParameters(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, Attachment binaryDetail, LocalDate date, Date dateTime, String password, String paramCallback) { + + } + + /** + * To test enum parameters + * + * To test enum parameters + * + */ + @Override + public void testEnumParameters(List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, Integer enumQueryInteger, Double enumQueryDouble, List enumFormStringArray, String enumFormString) { + + } + + /** + * Fake endpoint to test group parameters (optional) + * + * Fake endpoint to test group parameters (optional) + * + */ + @Override + public void testGroupParameters(Integer requiredStringGroup, Boolean requiredBooleanGroup, Long requiredInt64Group, Integer stringGroup, Boolean booleanGroup, Long int64Group) { + + } + + /** + * test inline additionalProperties + * + */ + @Override + public void testInlineAdditionalProperties(Map param) { + + } + + /** + * test json serialization of form data + * + */ + @Override + public void testJsonFormData(String param, String param2) { + + } + +} diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/main/java/org/openapitools/api/impl/FakeClassnameTags123ApiServiceImpl.java b/samples/server/petstore/jaxrs-cxf-test-data/src/main/java/org/openapitools/api/impl/FakeClassnameTags123ApiServiceImpl.java new file mode 100644 index 00000000000..d98910643c3 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/main/java/org/openapitools/api/impl/FakeClassnameTags123ApiServiceImpl.java @@ -0,0 +1,61 @@ +package org.openapitools.api.impl; + +import org.openapitools.api.*; +import org.openapitools.model.Client; +import java.util.List; +import java.util.Map; + +import java.io.InputStream; +import java.io.OutputStream; +import java.util.List; +import java.util.Map; +import java.io.File; +import com.fasterxml.jackson.databind.node.JsonNodeFactory; +import com.fasterxml.jackson.databind.node.ObjectNode; +import org.openapitools.codegen.utils.JsonCache; +import org.openapitools.codegen.utils.JsonCache.CacheException; +import javax.ws.rs.*; +import javax.ws.rs.core.Response; +import org.apache.cxf.jaxrs.model.wadl.Description; +import org.apache.cxf.jaxrs.model.wadl.DocTarget; + +import org.apache.cxf.jaxrs.ext.multipart.*; + +import io.swagger.annotations.Api; + +/** + * 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: \" \\ + * + */ +public class FakeClassnameTags123ApiServiceImpl implements FakeClassnameTags123Api { + private JsonCache cache; + + { + try { + File cacheFile = new File(System.getProperty("jaxrs.test.server.json", + "/Users/williamcheng/Code/demonfiddler/samples/server/petstore/jaxrs-cxf-test-data/src/main/resources/test-data.json")); + cache = JsonCache.Factory.instance.get("test-data").load(cacheFile).child("/org.openapitools.api/FakeClassnameTags123Api"); + } catch (CacheException e) { + e.printStackTrace(); + } + } + + /** + * To test class name in snake case + * + * To test class name in snake case + * + */ + @Override + public Client testClassname(Client body) { + try { + Client response = cache.getObject("/testClassname/response", Client.class); + return response; + } catch (CacheException e) { + throw new RuntimeException(e); + } + } + +} diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/main/java/org/openapitools/api/impl/PetApiServiceImpl.java b/samples/server/petstore/jaxrs-cxf-test-data/src/main/java/org/openapitools/api/impl/PetApiServiceImpl.java new file mode 100644 index 00000000000..108b47a91b2 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/main/java/org/openapitools/api/impl/PetApiServiceImpl.java @@ -0,0 +1,160 @@ +package org.openapitools.api.impl; + +import org.openapitools.api.*; +import org.openapitools.model.Category; +import java.io.File; +import java.util.List; +import java.util.Map; +import org.openapitools.model.ModelApiResponse; +import org.openapitools.model.Pet; + +import java.io.InputStream; +import java.io.OutputStream; +import java.util.List; +import java.util.Map; +import java.io.File; +import com.fasterxml.jackson.databind.node.JsonNodeFactory; +import com.fasterxml.jackson.databind.node.ObjectNode; +import org.openapitools.codegen.utils.JsonCache; +import org.openapitools.codegen.utils.JsonCache.CacheException; +import javax.ws.rs.*; +import javax.ws.rs.core.Response; +import org.apache.cxf.jaxrs.model.wadl.Description; +import org.apache.cxf.jaxrs.model.wadl.DocTarget; + +import org.apache.cxf.jaxrs.ext.multipart.*; + +import io.swagger.annotations.Api; + +/** + * 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: \" \\ + * + */ +public class PetApiServiceImpl implements PetApi { + private JsonCache cache; + + { + try { + File cacheFile = new File(System.getProperty("jaxrs.test.server.json", + "/Users/williamcheng/Code/demonfiddler/samples/server/petstore/jaxrs-cxf-test-data/src/main/resources/test-data.json")); + cache = JsonCache.Factory.instance.get("test-data").load(cacheFile).child("/org.openapitools.api/PetApi"); + } catch (CacheException e) { + e.printStackTrace(); + } + } + + /** + * Add a new pet to the store + * + */ + @Override + public void addPet(Pet body) { + + } + + /** + * Deletes a pet + * + */ + @Override + public void deletePet(Long petId, String apiKey) { + + } + + /** + * Finds Pets by status + * + * Multiple status values can be provided with comma separated strings + * + */ + @Override + public List findPetsByStatus(List status) { + try { + List response = cache.getObjects("/findPetsByStatus/response", Pet.class); + return response; + } catch (CacheException e) { + throw new RuntimeException(e); + } + } + + /** + * Finds Pets by tags + * + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * + */ + @Override + public List findPetsByTags(List tags) { + try { + List response = cache.getObjects("/findPetsByTags/response", Pet.class); + return response; + } catch (CacheException e) { + throw new RuntimeException(e); + } + } + + /** + * Find pet by ID + * + * Returns a single pet + * + */ + @Override + public Pet getPetById(Long petId) { + try { + Pet response = cache.getObject("/getPetById/response", Pet.class); + return response; + } catch (CacheException e) { + throw new RuntimeException(e); + } + } + + /** + * Update an existing pet + * + */ + @Override + public void updatePet(Pet body) { + + } + + /** + * Updates a pet in the store with form data + * + */ + @Override + public void updatePetWithForm(Long petId, String name, String status) { + + } + + /** + * uploads an image + * + */ + @Override + public ModelApiResponse uploadFile(Long petId, String additionalMetadata, Attachment fileDetail) { + try { + ModelApiResponse response = cache.getObject("/uploadFile/response", ModelApiResponse.class); + return response; + } catch (CacheException e) { + throw new RuntimeException(e); + } + } + + /** + * uploads an image (required) + * + */ + @Override + public ModelApiResponse uploadFileWithRequiredFile(Long petId, Attachment requiredFileDetail, String additionalMetadata) { + try { + ModelApiResponse response = cache.getObject("/uploadFileWithRequiredFile/response", ModelApiResponse.class); + return response; + } catch (CacheException e) { + throw new RuntimeException(e); + } + } + +} diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/main/java/org/openapitools/api/impl/StoreApiServiceImpl.java b/samples/server/petstore/jaxrs-cxf-test-data/src/main/java/org/openapitools/api/impl/StoreApiServiceImpl.java new file mode 100644 index 00000000000..726a99ecb51 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/main/java/org/openapitools/api/impl/StoreApiServiceImpl.java @@ -0,0 +1,102 @@ +package org.openapitools.api.impl; + +import org.openapitools.api.*; +import java.util.List; +import java.util.Map; +import org.openapitools.model.Order; + +import java.io.InputStream; +import java.io.OutputStream; +import java.util.List; +import java.util.Map; +import java.io.File; +import com.fasterxml.jackson.databind.node.JsonNodeFactory; +import com.fasterxml.jackson.databind.node.ObjectNode; +import org.openapitools.codegen.utils.JsonCache; +import org.openapitools.codegen.utils.JsonCache.CacheException; +import javax.ws.rs.*; +import javax.ws.rs.core.Response; +import org.apache.cxf.jaxrs.model.wadl.Description; +import org.apache.cxf.jaxrs.model.wadl.DocTarget; + +import org.apache.cxf.jaxrs.ext.multipart.*; + +import io.swagger.annotations.Api; + +/** + * 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: \" \\ + * + */ +public class StoreApiServiceImpl implements StoreApi { + private JsonCache cache; + + { + try { + File cacheFile = new File(System.getProperty("jaxrs.test.server.json", + "/Users/williamcheng/Code/demonfiddler/samples/server/petstore/jaxrs-cxf-test-data/src/main/resources/test-data.json")); + cache = JsonCache.Factory.instance.get("test-data").load(cacheFile).child("/org.openapitools.api/StoreApi"); + } catch (CacheException e) { + e.printStackTrace(); + } + } + + /** + * Delete purchase order by ID + * + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * + */ + @Override + public void deleteOrder(String orderId) { + + } + + /** + * Returns pet inventories by status + * + * Returns a map of status codes to quantities + * + */ + @Override + public Map getInventory() { + try { + Map response = cache.getObject("/getInventory/response", Map.class); + return response; + } catch (CacheException e) { + throw new RuntimeException(e); + } + } + + /** + * Find purchase order by ID + * + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * + */ + @Override + public Order getOrderById(Long orderId) { + try { + Order response = cache.getObject("/getOrderById/response", Order.class); + return response; + } catch (CacheException e) { + throw new RuntimeException(e); + } + } + + /** + * Place an order for a pet + * + */ + @Override + public Order placeOrder(Order body) { + try { + Order response = cache.getObject("/placeOrder/response", Order.class); + return response; + } catch (CacheException e) { + throw new RuntimeException(e); + } + } + +} diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/main/java/org/openapitools/api/impl/UserApiServiceImpl.java b/samples/server/petstore/jaxrs-cxf-test-data/src/main/java/org/openapitools/api/impl/UserApiServiceImpl.java new file mode 100644 index 00000000000..3c2a5fbb9aa --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/main/java/org/openapitools/api/impl/UserApiServiceImpl.java @@ -0,0 +1,133 @@ +package org.openapitools.api.impl; + +import org.openapitools.api.*; +import java.util.List; +import java.util.Map; +import org.openapitools.model.User; + +import java.io.InputStream; +import java.io.OutputStream; +import java.util.List; +import java.util.Map; +import java.io.File; +import com.fasterxml.jackson.databind.node.JsonNodeFactory; +import com.fasterxml.jackson.databind.node.ObjectNode; +import org.openapitools.codegen.utils.JsonCache; +import org.openapitools.codegen.utils.JsonCache.CacheException; +import javax.ws.rs.*; +import javax.ws.rs.core.Response; +import org.apache.cxf.jaxrs.model.wadl.Description; +import org.apache.cxf.jaxrs.model.wadl.DocTarget; + +import org.apache.cxf.jaxrs.ext.multipart.*; + +import io.swagger.annotations.Api; + +/** + * 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: \" \\ + * + */ +public class UserApiServiceImpl implements UserApi { + private JsonCache cache; + + { + try { + File cacheFile = new File(System.getProperty("jaxrs.test.server.json", + "/Users/williamcheng/Code/demonfiddler/samples/server/petstore/jaxrs-cxf-test-data/src/main/resources/test-data.json")); + cache = JsonCache.Factory.instance.get("test-data").load(cacheFile).child("/org.openapitools.api/UserApi"); + } catch (CacheException e) { + e.printStackTrace(); + } + } + + /** + * Create user + * + * This can only be done by the logged in user. + * + */ + @Override + public void createUser(User body) { + + } + + /** + * Creates list of users with given input array + * + */ + @Override + public void createUsersWithArrayInput(List body) { + + } + + /** + * Creates list of users with given input array + * + */ + @Override + public void createUsersWithListInput(List body) { + + } + + /** + * Delete user + * + * This can only be done by the logged in user. + * + */ + @Override + public void deleteUser(String username) { + + } + + /** + * Get user by user name + * + */ + @Override + public User getUserByName(String username) { + try { + User response = cache.getObject("/getUserByName/response", User.class); + return response; + } catch (CacheException e) { + throw new RuntimeException(e); + } + } + + /** + * Logs user into the system + * + */ + @Override + public String loginUser(String username, String password) { + try { + String response = cache.getString("/loginUser/response"); + return response; + } catch (CacheException e) { + throw new RuntimeException(e); + } + } + + /** + * Logs out current logged in user session + * + */ + @Override + public void logoutUser() { + + } + + /** + * Updated user + * + * This can only be done by the logged in user. + * + */ + @Override + public void updateUser(String username, User body) { + + } + +} diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/main/resources/ApplicationContext.xml b/samples/server/petstore/jaxrs-cxf-test-data/src/main/resources/ApplicationContext.xml new file mode 100644 index 00000000000..81eb4c1f5c3 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/main/resources/ApplicationContext.xml @@ -0,0 +1,66 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/main/resources/test-data.json b/samples/server/petstore/jaxrs-cxf-test-data/src/main/resources/test-data.json new file mode 100644 index 00000000000..e32a76dd3ff --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/main/resources/test-data.json @@ -0,0 +1,359 @@ +{ + "org.openapitools.api" : { + "AnotherFakeApi" : { + "call123testSpecialTags" : { + "body" : { + "client" : "jcG45" + }, + "response" : { + "client" : "X370r" + } + } + }, + "FakeApi" : { + "createXmlItem" : { + "xmlItem" : { + "attributeString" : "Eb2u1U6", + "attributeInteger" : 147520098, + "attributeBoolean" : true, + "wrappedArray" : [ 386706627 ], + "nameString" : "dh860", + "nameInteger" : 1987576209, + "nameBoolean" : true, + "nameArray" : [ -659992604 ], + "nameWrappedArray" : [ -2119625820 ], + "prefixString" : "i3F56", + "prefixInteger" : 1911338960, + "prefixBoolean" : true, + "prefixArray" : [ 1722883742 ], + "prefixWrappedArray" : [ 1078700186 ], + "namespaceString" : "iS4Ds71", + "namespaceInteger" : 487489352, + "namespaceBoolean" : false, + "namespaceArray" : [ 1680914373 ], + "namespaceWrappedArray" : [ -1665967400 ], + "prefixNsString" : "Dw4j1", + "prefixNsInteger" : 1066222353, + "prefixNsBoolean" : true, + "prefixNsArray" : [ -323311251 ], + "prefixNsWrappedArray" : [ -97625425 ] + } + }, + "fakeOuterBooleanSerialize" : { + "body" : false, + "response" : true + }, + "fakeOuterCompositeSerialize" : { + "body" : { + "myString" : "X2D3gz", + "myBoolean" : false + }, + "response" : { + "myString" : "CoPXZxn", + "myBoolean" : false + } + }, + "fakeOuterStringSerialize" : { + "body" : "n7l4XMo", + "response" : "Qr4co9" + }, + "testBodyWithQueryParams" : { + "query" : "UV9bdZ2", + "body" : { + "id" : 4000262934535942144, + "username" : "XLJ4b9", + "firstName" : "hSDrOu", + "lastName" : "L11r0", + "email" : "Kjq6Mi61", + "password" : "hF294", + "phone" : "JJVU9", + "userStatus" : -1075062101 + } + }, + "testClientModel" : { + "body" : { + "client" : "A4h15W9u21" + }, + "response" : { + "client" : "Og4a5" + } + }, + "testEndpointParameters" : { + "_double" : 91.68589154730602421612164906388358076583244837820529937744140625, + "patternWithoutDelimiter" : "^K᫢", + "_byte" : "VA==", + "integer" : 79, + "int32" : 67, + "int64" : 2105658579350773760, + "_float" : -8.599085E37, + "string" : "/o/i", + "binary" : "6F2DE9EC31", + "dateTime" : "1970-01-01T00:00:00.000Z", + "password" : "ZO4zar14Va3jI1l", + "paramCallback" : "wPk77B7e5xF" + }, + "testEnumParameters" : { + "enumHeaderStringArray" : [ ">" ], + "enumHeaderString" : "_abc", + "enumQueryStringArray" : [ ">" ], + "enumQueryString" : "_abc", + "enumQueryInteger" : -2, + "enumQueryDouble" : 1.1, + "enumFormStringArray" : [ ">" ], + "enumFormString" : "(xyz)" + }, + "testGroupParameters" : { + "requiredStringGroup" : 1207842123, + "requiredBooleanGroup" : false, + "requiredInt64Group" : 5596825593739094016, + "stringGroup" : 159421280, + "booleanGroup" : false, + "int64Group" : -371090919006941184 + }, + "testInlineAdditionalProperties" : { + "param" : { + "wudzp01O" : "mE6kw6wXNh" + } + }, + "testJsonFormData" : { + "param" : "Gfe588Q6", + "param2" : "QBx28IQ" + } + }, + "FakeClassnameTags123Api" : { + "testClassname" : { + "body" : { + "client" : "S1aOxISzBs" + }, + "response" : { + "client" : "TbGI9" + } + } + }, + "PetApi" : { + "addPet" : { + "body" : { + "id" : -2653750499344775168, + "category" : { + "id" : -2928510589379909632, + "name" : "TO3p80Ky2x" + }, + "name" : "Qm6N3dP3", + "photoUrls" : [ "p53C0" ], + "tags" : [ { + "id" : -2307271697209421824, + "name" : "Al1TO" + } ], + "status" : "available" + } + }, + "deletePet" : { + "petId" : -5729095497896138752, + "apiKey" : "emX89u" + }, + "findPetsByStatus" : { + "status" : [ "pending" ], + "response" : [ { + "id" : 6691518087482916864, + "category" : { + "id" : 6964466714983940096, + "name" : "koE81eyo" + }, + "name" : "y4m4PhCE0i", + "photoUrls" : [ "IqJJmx" ], + "tags" : [ { + "id" : 8012801031574112256, + "name" : "YrJn1yGs0z" + } ], + "status" : "sold" + } ] + }, + "findPetsByTags" : { + "tags" : [ "j3nfE" ], + "response" : [ { + "id" : -9197231497833564160, + "category" : { + "id" : -5988701284856627200, + "name" : "BauS54" + }, + "name" : "M8kI7", + "photoUrls" : [ "Qa714D5" ], + "tags" : [ { + "id" : 4440883532640208896, + "name" : "Nkk3DY5" + } ], + "status" : "available" + } ] + }, + "getPetById" : { + "petId" : -6219590703298789376, + "response" : { + "id" : 5993566911200026624, + "category" : { + "id" : -2117647852255066112, + "name" : "eubaw7" + }, + "name" : "ET50LhRvnd", + "photoUrls" : [ "O99qs1" ], + "tags" : [ { + "id" : 2761338271092506624, + "name" : "jfPAX" + } ], + "status" : "sold" + } + }, + "updatePet" : { + "body" : { + "id" : -1456079319067897856, + "category" : { + "id" : 5419421286905976832, + "name" : "X0q8S" + }, + "name" : "he3p7", + "photoUrls" : [ "xlE9clF" ], + "tags" : [ { + "id" : 2103387396570261504, + "name" : "gcerr1IP" + } ], + "status" : "sold" + } + }, + "updatePetWithForm" : { + "petId" : -7656356217721585664, + "name" : "A2bOl", + "status" : "PH9f8356iEBn" + }, + "uploadFile" : { + "petId" : 6952534196252968960, + "additionalMetadata" : "G4m059l", + "file" : "9C9DA0EAF5D2AF1F6864A6", + "response" : { + "code" : -1435192892, + "type" : "gw24XnMH7", + "message" : "zzB72Z" + } + }, + "uploadFileWithRequiredFile" : { + "petId" : 512037124265578496, + "requiredFile" : "D8B705A8FB3F407B2F8E", + "additionalMetadata" : "PY6nDn9", + "response" : { + "code" : -1333813556, + "type" : "BrrZM", + "message" : "tFr79X" + } + } + }, + "StoreApi" : { + "deleteOrder" : { + "orderId" : "HsU41" + }, + "getInventory" : { + "response" : { + "ziD75" : 294464959 + } + }, + "getOrderById" : { + "orderId" : 4, + "response" : { + "id" : 3165203730926016512, + "petId" : -3012698886004281344, + "quantity" : -60286595, + "shipDate" : "1970-01-01T00:00:00.000Z", + "status" : "delivered", + "complete" : true + } + }, + "placeOrder" : { + "body" : { + "id" : 3338410355229698048, + "petId" : -4961432594453067776, + "quantity" : 1842478858, + "shipDate" : "1970-01-01T00:00:00.000Z", + "status" : "approved", + "complete" : true + }, + "response" : { + "id" : -1005036856530139136, + "petId" : -4453012365528330240, + "quantity" : -2040456846, + "shipDate" : "1970-01-01T00:00:00.000Z", + "status" : "placed", + "complete" : true + } + } + }, + "UserApi" : { + "createUser" : { + "body" : { + "id" : -8606986596057917440, + "username" : "tL0ec", + "firstName" : "Y0loLMb", + "lastName" : "zT5201", + "email" : "u81A86VgXTIE", + "password" : "HP0SR", + "phone" : "w1WQ810b", + "userStatus" : -1376509587 + } + }, + "createUsersWithArrayInput" : { + "body" : [ { + "id" : -1966638810474690560, + "username" : "VTWlOg", + "firstName" : "jpFb3", + "lastName" : "t25dWgTQ", + "email" : "aqf3E", + "password" : "Avn2BM8xK", + "phone" : "E4JIl", + "userStatus" : -1484810590 + } ] + }, + "createUsersWithListInput" : { + "body" : [ { + "id" : 8585018130972989440, + "username" : "P9vsF", + "firstName" : "J7CAoNQj", + "lastName" : "WD1h9", + "email" : "jKzvi6", + "password" : "cHska", + "phone" : "Dldds", + "userStatus" : 1097971227 + } ] + }, + "deleteUser" : { + "username" : "iT0Ys" + }, + "getUserByName" : { + "username" : "QpJg1", + "response" : { + "id" : 14156895191257088, + "username" : "sor05q0v8f", + "firstName" : "r4D82", + "lastName" : "WHMFN933cK1", + "email" : "BaLHhmu008", + "password" : "qk44V", + "phone" : "tUzVV", + "userStatus" : -373662379 + } + }, + "loginUser" : { + "username" : "Yr620", + "password" : "B196F", + "response" : "S5I74r9" + }, + "updateUser" : { + "username" : "zEoD6E0S", + "body" : { + "id" : -6743258527755587584, + "username" : "Bd3OVY", + "firstName" : "CW6Sc", + "lastName" : "TV8U0", + "email" : "yy7aew", + "password" : "ywud8QR4", + "phone" : "dy886aDKe", + "userStatus" : 1641465856 + } + } + } + } +} \ No newline at end of file diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/main/webapp/WEB-INF/context.xml b/samples/server/petstore/jaxrs-cxf-test-data/src/main/webapp/WEB-INF/context.xml new file mode 100644 index 00000000000..a14b9a13d01 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/main/webapp/WEB-INF/context.xml @@ -0,0 +1,18 @@ + + + + + + + + diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/main/webapp/WEB-INF/web.xml b/samples/server/petstore/jaxrs-cxf-test-data/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 00000000000..9d905ae076b --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,23 @@ + + + + + contextConfigLocation + WEB-INF/context.xml + + + org.springframework.web.context.ContextLoaderListener + + + CXF Service Servlet + CXFServiceServlet + org.apache.cxf.transport.servlet.CXFServlet + 1 + + + CXFServiceServlet + /rest/* + + + diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/test/java/org/openapitools/api/AnotherFakeApiTest.java b/samples/server/petstore/jaxrs-cxf-test-data/src/test/java/org/openapitools/api/AnotherFakeApiTest.java new file mode 100644 index 00000000000..2ee5a4036ed --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/test/java/org/openapitools/api/AnotherFakeApiTest.java @@ -0,0 +1,133 @@ +/** + * 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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package org.openapitools.api; + +import org.openapitools.model.Client; +import java.util.List; +import java.util.Map; +import org.junit.Test; +import org.junit.Before; +import static org.junit.Assert.*; + +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import org.apache.cxf.jaxrs.client.JAXRSClientFactory; +import org.apache.cxf.jaxrs.client.ClientConfiguration; +import org.apache.cxf.jaxrs.client.WebClient; +import org.apache.cxf.jaxrs.ext.multipart.Attachment; + + +import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider; +import com.fasterxml.jackson.jaxrs.xml.JacksonXMLProvider; +import org.apache.cxf.jaxrs.provider.MultipartProvider; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.junit.runner.RunWith; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.boot.web.server.LocalServerPort; +import java.io.File; +import java.util.Set; +import javax.validation.ConstraintViolation; +import javax.validation.Validation; +import javax.validation.Validator; +import javax.validation.ValidatorFactory; +import com.fasterxml.jackson.databind.node.JsonNodeFactory; +import com.fasterxml.jackson.databind.node.ObjectNode; +import org.junit.BeforeClass; +import org.openapitools.codegen.utils.JsonCache; + +/** + * 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: \" \\ + * + * API tests for AnotherFakeApi. + */ +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) +public class AnotherFakeApiTest { + private static Validator validator; + private static JsonCache cache; + + @BeforeClass + public static void beforeClass() throws Exception { + File cacheFile = new File(System.getProperty("jaxrs.test.client.json", + "C:\\source\\GitHub\\demonfiddler\\openapi-generator\\samples\\server\\petstore\\jaxrs-cxf-test-data\\src\\main\\resources\\test-data.json")); + cache = JsonCache.Factory.instance.get("test-data").load(cacheFile).child("/org.openapitools.api/AnotherFakeApi"); + + validator = Validation.buildDefaultValidatorFactory().getValidator(); + } + + @LocalServerPort + private int serverPort; + + private AnotherFakeApi api; + + @Before + public void setup() { + List providers = Arrays.asList(new JacksonJsonProvider(), new JacksonXMLProvider(), new MultipartProvider()); + + api = JAXRSClientFactory.create("http://localhost:" + serverPort + "/services", AnotherFakeApi.class, providers); + org.apache.cxf.jaxrs.client.Client client = WebClient.client(api); + + ClientConfiguration config = WebClient.getConfig(client); + } + + private void validate(Object o) { + assertNotNull(o); + Set> violations = validator.validate(o); + if (!violations.isEmpty()) { + StringBuilder message = new StringBuilder("Validation failed"); + for (ConstraintViolation violation : violations) + message.append("; ").append(violation.getPropertyPath()).append(": ").append(violation.getMessage()); + fail(message.toString()); + } + } + + + /** + * To test special tags + * + * To test special tags and operation ID starting with number + * + * @throws ApiException if the API call fails + */ + @Test + public void call123testSpecialTagsTest() throws Exception { + Client body = cache.getObject("/call123testSpecialTags/body", Client.class); + Client response = api.call123testSpecialTags(body); + // TODO: complete test assertions + validate(response); + } + +} diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/test/java/org/openapitools/api/FakeApiTest.java b/samples/server/petstore/jaxrs-cxf-test-data/src/test/java/org/openapitools/api/FakeApiTest.java new file mode 100644 index 00000000000..5912420335a --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/test/java/org/openapitools/api/FakeApiTest.java @@ -0,0 +1,311 @@ +/** + * 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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package org.openapitools.api; + +import java.math.BigDecimal; +import org.openapitools.model.Client; +import java.util.Date; +import java.io.File; +import org.openapitools.model.FileSchemaTestClass; +import java.util.List; +import org.joda.time.LocalDate; +import java.util.Map; +import org.openapitools.model.OuterComposite; +import org.openapitools.model.User; +import org.openapitools.model.XmlItem; +import org.junit.Test; +import org.junit.Before; +import static org.junit.Assert.*; + +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import org.apache.cxf.jaxrs.client.JAXRSClientFactory; +import org.apache.cxf.jaxrs.client.ClientConfiguration; +import org.apache.cxf.jaxrs.client.WebClient; +import org.apache.cxf.jaxrs.ext.multipart.Attachment; + + +import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider; +import com.fasterxml.jackson.jaxrs.xml.JacksonXMLProvider; +import org.apache.cxf.jaxrs.provider.MultipartProvider; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.junit.runner.RunWith; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.boot.web.server.LocalServerPort; +import java.io.File; +import java.util.Set; +import javax.validation.ConstraintViolation; +import javax.validation.Validation; +import javax.validation.Validator; +import javax.validation.ValidatorFactory; +import com.fasterxml.jackson.databind.node.JsonNodeFactory; +import com.fasterxml.jackson.databind.node.ObjectNode; +import org.junit.BeforeClass; +import org.junit.Ignore; +import org.openapitools.codegen.utils.JsonCache; + +/** + * 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: \" \\ + * + * API tests for FakeApi. + */ +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) +public class FakeApiTest { + private static Validator validator; + private static JsonCache cache; + + @BeforeClass + public static void beforeClass() throws Exception { + File cacheFile = new File(System.getProperty("jaxrs.test.client.json", + "C:\\source\\GitHub\\demonfiddler\\openapi-generator\\samples\\server\\petstore\\jaxrs-cxf-test-data\\src\\main\\resources\\test-data.json")); + cache = JsonCache.Factory.instance.get("test-data").load(cacheFile).child("/org.openapitools.api/FakeApi"); + + validator = Validation.buildDefaultValidatorFactory().getValidator(); + } + + @LocalServerPort + private int serverPort; + + private FakeApi api; + + @Before + public void setup() { + List providers = Arrays.asList(new JacksonJsonProvider(), new JacksonXMLProvider(), new MultipartProvider()); + + api = JAXRSClientFactory.create("http://localhost:" + serverPort + "/services", FakeApi.class, providers); + org.apache.cxf.jaxrs.client.Client client = WebClient.client(api); + + ClientConfiguration config = WebClient.getConfig(client); + } + + private void validate(Object o) { + assertNotNull(o); + Set> violations = validator.validate(o); + if (!violations.isEmpty()) { + StringBuilder message = new StringBuilder("Validation failed"); + for (ConstraintViolation violation : violations) + message.append("; ").append(violation.getPropertyPath()).append(": ").append(violation.getMessage()); + fail(message.toString()); + } + } + + + /** + * creates an XmlItem + * + * this route creates an XmlItem + * + * @throws ApiException if the API call fails + */ + @Test + public void createXmlItemTest() throws Exception { + XmlItem xmlItem = cache.getObject("/createXmlItem/xmlItem", XmlItem.class); + api.createXmlItem(xmlItem); + } + + /** + * @throws ApiException if the API call fails + */ + @Test + public void fakeOuterBooleanSerializeTest() throws Exception { + Boolean body = cache.getBoolean("/fakeOuterBooleanSerialize/body"); + Boolean response = api.fakeOuterBooleanSerialize(body); + // TODO: complete test assertions + validate(response); + } + + /** + * @throws ApiException if the API call fails + */ + @Test + public void fakeOuterCompositeSerializeTest() throws Exception { + OuterComposite body = cache.getObject("/fakeOuterCompositeSerialize/body", OuterComposite.class); + OuterComposite response = api.fakeOuterCompositeSerialize(body); + // TODO: complete test assertions + validate(response); + } + + /** + * @throws ApiException if the API call fails + */ + @Test + public void fakeOuterNumberSerializeTest() throws Exception { + BigDecimal body = cache.getBigDecimal("/fakeOuterNumberSerialize/body"); + BigDecimal response = api.fakeOuterNumberSerialize(body); + // TODO: complete test assertions + validate(response); + } + + /** + * @throws ApiException if the API call fails + */ + @Test + public void fakeOuterStringSerializeTest() throws Exception { + String body = cache.getString("/fakeOuterStringSerialize/body"); + String response = api.fakeOuterStringSerialize(body); + // TODO: complete test assertions + validate(response); + } + + /** + * @throws ApiException if the API call fails + */ + @Test + public void testBodyWithFileSchemaTest() throws Exception { + FileSchemaTestClass body = cache.getObject("/testBodyWithFileSchema/body", FileSchemaTestClass.class); + api.testBodyWithFileSchema(body); + } + + /** + * @throws ApiException if the API call fails + */ + @Test + public void testBodyWithQueryParamsTest() throws Exception { + String query = cache.getString("/testBodyWithQueryParams/query"); + User body = cache.getObject("/testBodyWithQueryParams/body", User.class); + api.testBodyWithQueryParams(query, body); + } + + /** + * To test \"client\" model + * + * To test \"client\" model + * + * @throws ApiException if the API call fails + */ + @Test + public void testClientModelTest() throws Exception { + Client body = cache.getObject("/testClientModel/body", Client.class); + Client response = api.testClientModel(body); + // TODO: complete test assertions + validate(response); + } + + // Currently failing - see https://github.com/OpenAPITools/openapi-generator/issues/2193. + /** + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * + * @throws ApiException if the API call fails + */ + @Test + @Ignore + public void testEndpointParametersTest() throws Exception { + BigDecimal number = cache.getBigDecimal("/testEndpointParameters/number"); + Double _double = cache.getDouble("/testEndpointParameters/_double"); + String patternWithoutDelimiter = cache.getString("/testEndpointParameters/patternWithoutDelimiter"); + byte[] _byte = cache.getBinary("/testEndpointParameters/_byte"); + Integer integer = cache.getInt("/testEndpointParameters/integer"); + Integer int32 = cache.getInt("/testEndpointParameters/int32"); + Long int64 = cache.getLong("/testEndpointParameters/int64"); + Float _float = cache.getFloat("/testEndpointParameters/_float"); + String string = cache.getString("/testEndpointParameters/string"); + Attachment binary = new Attachment("binary", MediaType.TEXT_PLAIN, "Dummy attachment content"); + LocalDate date = cache.getObject("/testEndpointParameters/date", LocalDate.class); + Date dateTime = cache.getObject("/testEndpointParameters/dateTime", Date.class); + String password = cache.getString("/testEndpointParameters/password"); + String paramCallback = cache.getString("/testEndpointParameters/paramCallback"); + api.testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback); + } + + // Currently failing - see https://github.com/OpenAPITools/openapi-generator/issues/2193. + /** + * To test enum parameters + * + * To test enum parameters + * + * @throws ApiException if the API call fails + */ + @Test + @Ignore + public void testEnumParametersTest() throws Exception { + List enumHeaderStringArray = cache.getObjects("/testEnumParameters/enumHeaderStringArray", String.class); + String enumHeaderString = cache.getString("/testEnumParameters/enumHeaderString"); + List enumQueryStringArray = cache.getObjects("/testEnumParameters/enumQueryStringArray", String.class); + String enumQueryString = cache.getString("/testEnumParameters/enumQueryString"); + Integer enumQueryInteger = cache.getInt("/testEnumParameters/enumQueryInteger"); + Double enumQueryDouble = cache.getDouble("/testEnumParameters/enumQueryDouble"); + List enumFormStringArray = cache.getObjects("/testEnumParameters/enumFormStringArray", String.class); + String enumFormString = cache.getString("/testEnumParameters/enumFormString"); + api.testEnumParameters(enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, enumFormStringArray, enumFormString); + } + + /** + * Fake endpoint to test group parameters (optional) + * + * Fake endpoint to test group parameters (optional) + * + * @throws ApiException if the API call fails + */ + @Test + public void testGroupParametersTest() throws Exception { + Integer requiredStringGroup = cache.getInt("/testGroupParameters/requiredStringGroup"); + Boolean requiredBooleanGroup = cache.getBoolean("/testGroupParameters/requiredBooleanGroup"); + Long requiredInt64Group = cache.getLong("/testGroupParameters/requiredInt64Group"); + Integer stringGroup = cache.getInt("/testGroupParameters/stringGroup"); + Boolean booleanGroup = cache.getBoolean("/testGroupParameters/booleanGroup"); + Long int64Group = cache.getLong("/testGroupParameters/int64Group"); + api.testGroupParameters(requiredStringGroup, requiredBooleanGroup, requiredInt64Group, stringGroup, booleanGroup, int64Group); + } + + /** + * test inline additionalProperties + * + * @throws ApiException if the API call fails + */ + @Test + public void testInlineAdditionalPropertiesTest() throws Exception { + Map param = cache.getObject("/testInlineAdditionalProperties/param", Map.class); + api.testInlineAdditionalProperties(param); + } + + // Currently failing - see https://github.com/OpenAPITools/openapi-generator/issues/2193. + /** + * test json serialization of form data + * + * @throws ApiException if the API call fails + */ + @Test + @Ignore + public void testJsonFormDataTest() throws Exception { + String param = cache.getString("/testJsonFormData/param"); + String param2 = cache.getString("/testJsonFormData/param2"); + api.testJsonFormData(param, param2); + } + +} diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/test/java/org/openapitools/api/FakeClassnameTags123ApiTest.java b/samples/server/petstore/jaxrs-cxf-test-data/src/test/java/org/openapitools/api/FakeClassnameTags123ApiTest.java new file mode 100644 index 00000000000..1be1a84276e --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/test/java/org/openapitools/api/FakeClassnameTags123ApiTest.java @@ -0,0 +1,133 @@ +/** + * 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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package org.openapitools.api; + +import org.openapitools.model.Client; +import java.util.List; +import java.util.Map; +import org.junit.Test; +import org.junit.Before; +import static org.junit.Assert.*; + +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import org.apache.cxf.jaxrs.client.JAXRSClientFactory; +import org.apache.cxf.jaxrs.client.ClientConfiguration; +import org.apache.cxf.jaxrs.client.WebClient; +import org.apache.cxf.jaxrs.ext.multipart.Attachment; + + +import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider; +import com.fasterxml.jackson.jaxrs.xml.JacksonXMLProvider; +import org.apache.cxf.jaxrs.provider.MultipartProvider; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.junit.runner.RunWith; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.boot.web.server.LocalServerPort; +import java.io.File; +import java.util.Set; +import javax.validation.ConstraintViolation; +import javax.validation.Validation; +import javax.validation.Validator; +import javax.validation.ValidatorFactory; +import com.fasterxml.jackson.databind.node.JsonNodeFactory; +import com.fasterxml.jackson.databind.node.ObjectNode; +import org.junit.BeforeClass; +import org.openapitools.codegen.utils.JsonCache; + +/** + * 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: \" \\ + * + * API tests for FakeClassnameTags123Api. + */ +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) +public class FakeClassnameTags123ApiTest { + private static Validator validator; + private static JsonCache cache; + + @BeforeClass + public static void beforeClass() throws Exception { + File cacheFile = new File(System.getProperty("jaxrs.test.client.json", + "C:\\source\\GitHub\\demonfiddler\\openapi-generator\\samples\\server\\petstore\\jaxrs-cxf-test-data\\src\\main\\resources\\test-data.json")); + cache = JsonCache.Factory.instance.get("test-data").load(cacheFile).child("/org.openapitools.api/FakeClassnameTags123Api"); + + validator = Validation.buildDefaultValidatorFactory().getValidator(); + } + + @LocalServerPort + private int serverPort; + + private FakeClassnameTags123Api api; + + @Before + public void setup() { + List providers = Arrays.asList(new JacksonJsonProvider(), new JacksonXMLProvider(), new MultipartProvider()); + + api = JAXRSClientFactory.create("http://localhost:" + serverPort + "/services", FakeClassnameTags123Api.class, providers); + org.apache.cxf.jaxrs.client.Client client = WebClient.client(api); + + ClientConfiguration config = WebClient.getConfig(client); + } + + private void validate(Object o) { + assertNotNull(o); + Set> violations = validator.validate(o); + if (!violations.isEmpty()) { + StringBuilder message = new StringBuilder("Validation failed"); + for (ConstraintViolation violation : violations) + message.append("; ").append(violation.getPropertyPath()).append(": ").append(violation.getMessage()); + fail(message.toString()); + } + } + + + /** + * To test class name in snake case + * + * To test class name in snake case + * + * @throws ApiException if the API call fails + */ + @Test + public void testClassnameTest() throws Exception { + Client body = cache.getObject("/testClassname/body", Client.class); + Client response = api.testClassname(body); + // TODO: complete test assertions + validate(response); + } + +} diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/test/java/org/openapitools/api/PetApiTest.java b/samples/server/petstore/jaxrs-cxf-test-data/src/test/java/org/openapitools/api/PetApiTest.java new file mode 100644 index 00000000000..eab1b0f1ed1 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/test/java/org/openapitools/api/PetApiTest.java @@ -0,0 +1,251 @@ +/** + * 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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package org.openapitools.api; + +import org.openapitools.model.Category; +import java.io.File; +import java.util.List; +import java.util.Map; +import org.openapitools.model.ModelApiResponse; +import org.openapitools.model.Pet; +import org.openapitools.model.Tag; +import org.junit.Test; +import org.junit.Before; +import static org.junit.Assert.*; + +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import org.apache.cxf.jaxrs.client.JAXRSClientFactory; +import org.apache.cxf.jaxrs.client.ClientConfiguration; +import org.apache.cxf.jaxrs.client.WebClient; +import org.apache.cxf.jaxrs.ext.multipart.Attachment; + + +import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider; +import com.fasterxml.jackson.jaxrs.xml.JacksonXMLProvider; +import org.apache.cxf.jaxrs.provider.MultipartProvider; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.junit.runner.RunWith; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.boot.web.server.LocalServerPort; +import java.io.File; +import java.util.Set; +import javax.validation.ConstraintViolation; +import javax.validation.Validation; +import javax.validation.Validator; +import javax.validation.ValidatorFactory; +import com.fasterxml.jackson.databind.node.JsonNodeFactory; +import com.fasterxml.jackson.databind.node.ObjectNode; +import org.junit.BeforeClass; +import org.junit.Ignore; +import org.openapitools.codegen.utils.JsonCache; + +/** + * 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: \" \\ + * + * API tests for PetApi. + */ +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) +public class PetApiTest { + private static Validator validator; + private static JsonCache cache; + + @BeforeClass + public static void beforeClass() throws Exception { + File cacheFile = new File(System.getProperty("jaxrs.test.client.json", + "C:\\source\\GitHub\\demonfiddler\\openapi-generator\\samples\\server\\petstore\\jaxrs-cxf-test-data\\src\\main\\resources\\test-data.json")); + cache = JsonCache.Factory.instance.get("test-data").load(cacheFile).child("/org.openapitools.api/PetApi"); + + validator = Validation.buildDefaultValidatorFactory().getValidator(); + } + + @LocalServerPort + private int serverPort; + + private PetApi api; + + @Before + public void setup() { + List providers = Arrays.asList(new JacksonJsonProvider(), new JacksonXMLProvider(), new MultipartProvider()); + + api = JAXRSClientFactory.create("http://localhost:" + serverPort + "/services", PetApi.class, providers); + org.apache.cxf.jaxrs.client.Client client = WebClient.client(api); + + ClientConfiguration config = WebClient.getConfig(client); + } + + private void validate(Object o) { + assertNotNull(o); + Set> violations = validator.validate(o); + if (!violations.isEmpty()) { + StringBuilder message = new StringBuilder("Validation failed"); + for (ConstraintViolation violation : violations) + message.append("; ").append(violation.getPropertyPath()).append(": ").append(violation.getMessage()); + fail(message.toString()); + } + } + + + /** + * Add a new pet to the store + * + * @throws ApiException if the API call fails + */ + @Test + public void addPetTest() throws Exception { + Pet body = cache.getObject("/addPet/body", Pet.class); + api.addPet(body); + } + + /** + * Deletes a pet + * + * @throws ApiException if the API call fails + */ + @Test + public void deletePetTest() throws Exception { + Long petId = cache.getLong("/deletePet/petId"); + String apiKey = cache.getString("/deletePet/apiKey"); + api.deletePet(petId, apiKey); + } + + /** + * Finds Pets by status + * + * Multiple status values can be provided with comma separated strings + * + * @throws ApiException if the API call fails + */ + @Test + public void findPetsByStatusTest() throws Exception { + List status = cache.getObjects("/findPetsByStatus/status", String.class); + List response = api.findPetsByStatus(status); + // TODO: complete test assertions + validate(response); + } + + /** + * Finds Pets by tags + * + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * + * @throws ApiException if the API call fails + */ + @Test + public void findPetsByTagsTest() throws Exception { + List tags = cache.getObjects("/findPetsByTags/tags", String.class); + List response = api.findPetsByTags(tags); + // TODO: complete test assertions + validate(response); + } + + /** + * Find pet by ID + * + * Returns a single pet + * + * @throws ApiException if the API call fails + */ + @Test + public void getPetByIdTest() throws Exception { + Long petId = cache.getLong("/getPetById/petId"); + Pet response = api.getPetById(petId); + // TODO: complete test assertions + validate(response); + } + + /** + * Update an existing pet + * + * @throws ApiException if the API call fails + */ + @Test + public void updatePetTest() throws Exception { + Pet body = cache.getObject("/updatePet/body", Pet.class); + api.updatePet(body); + } + + // Currently failing - see https://github.com/OpenAPITools/openapi-generator/issues/2193. + /** + * Updates a pet in the store with form data + * + * @throws ApiException if the API call fails + */ + @Test + @Ignore + public void updatePetWithFormTest() throws Exception { + Long petId = cache.getLong("/updatePetWithForm/petId"); + String name = cache.getString("/updatePetWithForm/name"); + String status = cache.getString("/updatePetWithForm/status"); + api.updatePetWithForm(petId, name, status); + } + + // Currently failing - see https://github.com/OpenAPITools/openapi-generator/issues/2193. + /** + * uploads an image + * + * @throws ApiException if the API call fails + */ + @Test + @Ignore + public void uploadFileTest() throws Exception { + Long petId = cache.getLong("/uploadFile/petId"); + String additionalMetadata = cache.getString("/uploadFile/additionalMetadata"); + Attachment file = new Attachment("file", MediaType.TEXT_PLAIN, "Dummy attachment content"); + ModelApiResponse response = api.uploadFile(petId, additionalMetadata, file); + // TODO: complete test assertions + validate(response); + } + + // Currently failing - see https://github.com/OpenAPITools/openapi-generator/issues/2193. + /** + * uploads an image (required) + * + * @throws ApiException if the API call fails + */ + @Test + @Ignore + public void uploadFileWithRequiredFileTest() throws Exception { + Long petId = cache.getLong("/uploadFileWithRequiredFile/petId"); + Attachment requiredFile = new Attachment("requiredFile", MediaType.TEXT_PLAIN, "Dummy attachment content"); + String additionalMetadata = cache.getString("/uploadFileWithRequiredFile/additionalMetadata"); + ModelApiResponse response = api.uploadFileWithRequiredFile(petId, requiredFile, additionalMetadata); + // TODO: complete test assertions + validate(response); + } + +} diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/test/java/org/openapitools/api/SpringBootApplication.java b/samples/server/petstore/jaxrs-cxf-test-data/src/test/java/org/openapitools/api/SpringBootApplication.java new file mode 100644 index 00000000000..4f284a3ec39 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/test/java/org/openapitools/api/SpringBootApplication.java @@ -0,0 +1,25 @@ +package org.openapitools.api; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.SpringBootConfiguration; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; +import org.springframework.context.annotation.ImportResource; + +@ImportResource({"classpath:/ApplicationContext.xml"}) +@EnableAutoConfiguration +@SpringBootConfiguration +public class SpringBootApplication extends SpringBootServletInitializer { + + @Override + protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { + return application.sources(SpringBootApplication.class); + } + + public static void main(String[] args) { + SpringApplication.run(SpringBootApplication.class, args); + } + + +} \ No newline at end of file diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/test/java/org/openapitools/api/StoreApiTest.java b/samples/server/petstore/jaxrs-cxf-test-data/src/test/java/org/openapitools/api/StoreApiTest.java new file mode 100644 index 00000000000..3ffc74ae417 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/test/java/org/openapitools/api/StoreApiTest.java @@ -0,0 +1,174 @@ +/** + * 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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package org.openapitools.api; + +import java.util.List; +import java.util.Map; +import org.openapitools.model.Order; +import org.junit.Test; +import org.junit.Before; +import static org.junit.Assert.*; + +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import org.apache.cxf.jaxrs.client.JAXRSClientFactory; +import org.apache.cxf.jaxrs.client.ClientConfiguration; +import org.apache.cxf.jaxrs.client.WebClient; +import org.apache.cxf.jaxrs.ext.multipart.Attachment; + + +import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider; +import com.fasterxml.jackson.jaxrs.xml.JacksonXMLProvider; +import org.apache.cxf.jaxrs.provider.MultipartProvider; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.junit.runner.RunWith; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.boot.web.server.LocalServerPort; +import java.io.File; +import java.util.Set; +import javax.validation.ConstraintViolation; +import javax.validation.Validation; +import javax.validation.Validator; +import javax.validation.ValidatorFactory; +import com.fasterxml.jackson.databind.node.JsonNodeFactory; +import com.fasterxml.jackson.databind.node.ObjectNode; +import org.junit.BeforeClass; +import org.openapitools.codegen.utils.JsonCache; + +/** + * 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: \" \\ + * + * API tests for StoreApi. + */ +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) +public class StoreApiTest { + private static Validator validator; + private static JsonCache cache; + + @BeforeClass + public static void beforeClass() throws Exception { + File cacheFile = new File(System.getProperty("jaxrs.test.client.json", + "C:\\source\\GitHub\\demonfiddler\\openapi-generator\\samples\\server\\petstore\\jaxrs-cxf-test-data\\src\\main\\resources\\test-data.json")); + cache = JsonCache.Factory.instance.get("test-data").load(cacheFile).child("/org.openapitools.api/StoreApi"); + + validator = Validation.buildDefaultValidatorFactory().getValidator(); + } + + @LocalServerPort + private int serverPort; + + private StoreApi api; + + @Before + public void setup() { + List providers = Arrays.asList(new JacksonJsonProvider(), new JacksonXMLProvider(), new MultipartProvider()); + + api = JAXRSClientFactory.create("http://localhost:" + serverPort + "/services", StoreApi.class, providers); + org.apache.cxf.jaxrs.client.Client client = WebClient.client(api); + + ClientConfiguration config = WebClient.getConfig(client); + } + + private void validate(Object o) { + assertNotNull(o); + Set> violations = validator.validate(o); + if (!violations.isEmpty()) { + StringBuilder message = new StringBuilder("Validation failed"); + for (ConstraintViolation violation : violations) + message.append("; ").append(violation.getPropertyPath()).append(": ").append(violation.getMessage()); + fail(message.toString()); + } + } + + + /** + * Delete purchase order by ID + * + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * + * @throws ApiException if the API call fails + */ + @Test + public void deleteOrderTest() throws Exception { + String orderId = cache.getString("/deleteOrder/orderId"); + api.deleteOrder(orderId); + } + + /** + * 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 Exception { + + Map response = api.getInventory(); + // TODO: complete test assertions + validate(response); + } + + /** + * Find purchase order by ID + * + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * + * @throws ApiException if the API call fails + */ + @Test + public void getOrderByIdTest() throws Exception { + Long orderId = cache.getLong("/getOrderById/orderId"); + Order response = api.getOrderById(orderId); + // TODO: complete test assertions + validate(response); + } + + /** + * Place an order for a pet + * + * @throws ApiException if the API call fails + */ + @Test + public void placeOrderTest() throws Exception { + Order body = cache.getObject("/placeOrder/body", Order.class); + Order response = api.placeOrder(body); + // TODO: complete test assertions + validate(response); + } + +} diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/test/java/org/openapitools/api/UserApiTest.java b/samples/server/petstore/jaxrs-cxf-test-data/src/test/java/org/openapitools/api/UserApiTest.java new file mode 100644 index 00000000000..8d65b7b7fba --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/test/java/org/openapitools/api/UserApiTest.java @@ -0,0 +1,218 @@ +/** + * 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. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package org.openapitools.api; + +import java.util.List; +import java.util.Map; +import org.openapitools.model.User; +import org.junit.Test; +import org.junit.Before; +import static org.junit.Assert.*; + +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import org.apache.cxf.jaxrs.client.JAXRSClientFactory; +import org.apache.cxf.jaxrs.client.ClientConfiguration; +import org.apache.cxf.jaxrs.client.WebClient; +import org.apache.cxf.jaxrs.ext.multipart.Attachment; + + +import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider; +import com.fasterxml.jackson.jaxrs.xml.JacksonXMLProvider; +import org.apache.cxf.jaxrs.provider.MultipartProvider; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.junit.runner.RunWith; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.boot.web.server.LocalServerPort; +import java.io.File; +import java.util.Set; +import javax.validation.ConstraintViolation; +import javax.validation.Validation; +import javax.validation.Validator; +import javax.validation.ValidatorFactory; +import com.fasterxml.jackson.databind.node.JsonNodeFactory; +import com.fasterxml.jackson.databind.node.ObjectNode; +import org.junit.BeforeClass; +import org.openapitools.codegen.utils.JsonCache; + +/** + * 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: \" \\ + * + * API tests for UserApi. + */ +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) +public class UserApiTest { + private static Validator validator; + private static JsonCache cache; + + @BeforeClass + public static void beforeClass() throws Exception { + File cacheFile = new File(System.getProperty("jaxrs.test.client.json", + "C:\\source\\GitHub\\demonfiddler\\openapi-generator\\samples\\server\\petstore\\jaxrs-cxf-test-data\\src\\main\\resources\\test-data.json")); + cache = JsonCache.Factory.instance.get("test-data").load(cacheFile).child("/org.openapitools.api/UserApi"); + + validator = Validation.buildDefaultValidatorFactory().getValidator(); + } + + @LocalServerPort + private int serverPort; + + private UserApi api; + + @Before + public void setup() { + List providers = Arrays.asList(new JacksonJsonProvider(), new JacksonXMLProvider(), new MultipartProvider()); + + api = JAXRSClientFactory.create("http://localhost:" + serverPort + "/services", UserApi.class, providers); + org.apache.cxf.jaxrs.client.Client client = WebClient.client(api); + + ClientConfiguration config = WebClient.getConfig(client); + } + + private void validate(Object o) { + assertNotNull(o); + Set> violations = validator.validate(o); + if (!violations.isEmpty()) { + StringBuilder message = new StringBuilder("Validation failed"); + for (ConstraintViolation violation : violations) + message.append("; ").append(violation.getPropertyPath()).append(": ").append(violation.getMessage()); + fail(message.toString()); + } + } + + + /** + * Create user + * + * This can only be done by the logged in user. + * + * @throws ApiException if the API call fails + */ + @Test + public void createUserTest() throws Exception { + User body = cache.getObject("/createUser/body", User.class); + api.createUser(body); + } + + /** + * Creates list of users with given input array + * + * @throws ApiException if the API call fails + */ + @Test + public void createUsersWithArrayInputTest() throws Exception { + List body = cache.getObjects("/createUsersWithArrayInput/body", User.class); + api.createUsersWithArrayInput(body); + } + + /** + * Creates list of users with given input array + * + * @throws ApiException if the API call fails + */ + @Test + public void createUsersWithListInputTest() throws Exception { + List body = cache.getObjects("/createUsersWithListInput/body", User.class); + api.createUsersWithListInput(body); + } + + /** + * Delete user + * + * This can only be done by the logged in user. + * + * @throws ApiException if the API call fails + */ + @Test + public void deleteUserTest() throws Exception { + String username = cache.getString("/deleteUser/username"); + api.deleteUser(username); + } + + /** + * Get user by user name + * + * @throws ApiException if the API call fails + */ + @Test + public void getUserByNameTest() throws Exception { + String username = cache.getString("/getUserByName/username"); + User response = api.getUserByName(username); + // TODO: complete test assertions + validate(response); + } + + /** + * Logs user into the system + * + * @throws ApiException if the API call fails + */ + @Test + public void loginUserTest() throws Exception { + String username = cache.getString("/loginUser/username"); + String password = cache.getString("/loginUser/password"); + String response = api.loginUser(username, password); + // TODO: complete test assertions + validate(response); + } + + /** + * Logs out current logged in user session + * + * @throws ApiException if the API call fails + */ + @Test + public void logoutUserTest() throws Exception { + + api.logoutUser(); + } + + /** + * Updated user + * + * This can only be done by the logged in user. + * + * @throws ApiException if the API call fails + */ + @Test + public void updateUserTest() throws Exception { + String username = cache.getString("/updateUser/username"); + User body = cache.getObject("/updateUser/body", User.class); + api.updateUser(username, body); + } + +} diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/test/resources/application.properties b/samples/server/petstore/jaxrs-cxf-test-data/src/test/resources/application.properties new file mode 100644 index 00000000000..dae57151736 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/test/resources/application.properties @@ -0,0 +1 @@ +cxf.path=/ \ No newline at end of file diff --git a/samples/server/petstore/jaxrs-cxf-test-data/test-data-control.json b/samples/server/petstore/jaxrs-cxf-test-data/test-data-control.json new file mode 100644 index 00000000000..f368ad41cfc --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-test-data/test-data-control.json @@ -0,0 +1,144 @@ +{ + "org.openapitools.api" : { + "FakeApi" : { + "createXmlItem" : { + "xmlItem" : { + "wrappedArray" : { + "testItemCount" : 1 + }, + "nameArray" : { + "testItemCount" : 1 + }, + "nameWrappedArray" : { + "testItemCount" : 1 + }, + "prefixArray" : { + "testItemCount" : 1 + }, + "prefixWrappedArray" : { + "testItemCount" : 1 + }, + "namespaceArray" : { + "testItemCount" : 1 + }, + "namespaceWrappedArray" : { + "testItemCount" : 1 + }, + "prefixNsArray" : { + "testItemCount" : 1 + }, + "prefixNsWrappedArray" : { + "testItemCount" : 1 + } + } + }, + "testBodyWithFileSchema" : { + "body" : { + "files" : { + "testItemCount" : 1 + } + } + }, + "testEndpointParameters" : { + "_byte" : { + "testItemCount" : 1 + } + }, + "testEnumParameters" : { + "enumHeaderStringArray" : { + "testItemCount" : 1 + }, + "enumQueryStringArray" : { + "testItemCount" : 1 + }, + "enumFormStringArray" : { + "testItemCount" : 1 + } + }, + "testInlineAdditionalProperties" : { + "param" : { + "testItemCount" : 1 + } + } + }, + "PetApi" : { + "addPet" : { + "body" : { + "photoUrls" : { + "testItemCount" : 1 + }, + "tags" : { + "testItemCount" : 1 + } + } + }, + "findPetsByStatus" : { + "status" : { + "testItemCount" : 1 + }, + "response" : { + "testItemCount" : 1, + "photoUrls" : { + "testItemCount" : 1 + }, + "tags" : { + "testItemCount" : 1 + } + } + }, + "findPetsByTags" : { + "tags" : { + "testItemCount" : 1 + }, + "response" : { + "testItemCount" : 1, + "photoUrls" : { + "testItemCount" : 1 + }, + "tags" : { + "testItemCount" : 1 + } + } + }, + "getPetById" : { + "response" : { + "photoUrls" : { + "testItemCount" : 1 + }, + "tags" : { + "testItemCount" : 1 + } + } + }, + "updatePet" : { + "body" : { + "photoUrls" : { + "testItemCount" : 1 + }, + "tags" : { + "testItemCount" : 1 + } + } + } + }, + "StoreApi" : { + "getInventory" : { + "response" : { + "testItemCount" : 1 + } + } + }, + "UserApi" : { + "createUsersWithArrayInput" : { + "body" : { + "testItemCount" : 1 + } + }, + "createUsersWithListInput" : { + "body" : { + "testItemCount" : 1 + } + } + } + } +} \ No newline at end of file