├── .github ├── topissuebot.yml └── workflows │ ├── codeql-analysis.yml │ ├── maven-pulls.yml │ ├── maven-v1-pulls.yml │ ├── maven-v1.yml │ ├── maven.yml │ ├── next-snapshot-v1.yml │ ├── next-snapshot.yml │ ├── prepare-release-v1.yml │ ├── prepare-release.yml │ ├── release-v1.yml │ └── release.yml ├── .gitignore ├── .whitesource ├── CI ├── CI.md ├── ghApiClient.py ├── lastRelease.py ├── lastReleaseV1.py ├── post-nextsnap-v1.sh ├── post-nextsnap.sh ├── post-release-v1.sh ├── post-release.sh ├── pre-release-v1.sh ├── pre-release.sh ├── prepare-release-v1.sh ├── prepare-release.sh ├── publishRelease.py ├── publishReleaseV1.py ├── releaseNotes.py └── releaseNotesV1.py ├── LICENSE ├── README.md ├── pom.xml ├── scripts ├── bin │ ├── jetty-runner.jar │ └── swagger-editor.war ├── editor.sh ├── inflector.yaml ├── openapi.yaml ├── pom.xml └── web.xml ├── setup.sh └── src ├── main ├── java │ └── io │ │ └── swagger │ │ └── oas │ │ └── inflector │ │ ├── Constants.java │ │ ├── CustomMediaTypes.java │ │ ├── OpenAPIInflector.java │ │ ├── config │ │ ├── Configuration.java │ │ ├── ControllerFactory.java │ │ ├── DefaultControllerFactory.java │ │ ├── DirectionDeserializer.java │ │ ├── ExposedSpecOptions.java │ │ ├── FilterFactory.java │ │ └── OpenAPIProcessor.java │ │ ├── controllers │ │ ├── InflectResultController.java │ │ ├── OpenAPIOperationController.java │ │ └── OpenAPIResourceController.java │ │ ├── converters │ │ ├── ConversionException.java │ │ ├── Converter.java │ │ ├── DefaultConverter.java │ │ └── InputConverter.java │ │ ├── examples │ │ ├── ExampleBuilder.java │ │ ├── XmlExampleSerializer.java │ │ └── models │ │ │ ├── AbstractExample.java │ │ │ ├── ArrayExample.java │ │ │ ├── BigIntegerExample.java │ │ │ ├── BooleanExample.java │ │ │ ├── DecimalExample.java │ │ │ ├── DoubleExample.java │ │ │ ├── Example.java │ │ │ ├── FloatExample.java │ │ │ ├── IntegerExample.java │ │ │ ├── LongExample.java │ │ │ ├── NullExample.java │ │ │ ├── ObjectExample.java │ │ │ └── StringExample.java │ │ ├── models │ │ ├── ApiError.java │ │ ├── InflectResult.java │ │ ├── RequestContext.java │ │ └── ResponseContext.java │ │ ├── processors │ │ ├── AbstractExampleProvider.java │ │ ├── BinaryProcessor.java │ │ ├── EntityProcessor.java │ │ ├── EntityProcessorFactory.java │ │ ├── JacksonProcessor.java │ │ ├── JsonExampleDeserializer.java │ │ ├── JsonExampleProvider.java │ │ ├── JsonNodeExampleSerializer.java │ │ ├── JsonProvider.java │ │ ├── PlainExampleProvider.java │ │ ├── PlainProcessor.java │ │ ├── XMLExampleProvider.java │ │ └── YamlExampleProvider.java │ │ ├── schema │ │ └── SchemaValidator.java │ │ ├── utils │ │ ├── ApiErrorUtils.java │ │ ├── ApiException.java │ │ ├── CORSFilter.java │ │ ├── ContentTypeSelector.java │ │ ├── DefaultContentTypeProvider.java │ │ ├── DefaultContentTypeSelector.java │ │ ├── DefaultExceptionMapper.java │ │ ├── DefaultSpecFilter.java │ │ ├── ExtensionsUtil.java │ │ ├── ReflectionUtils.java │ │ └── VendorSpecFilter.java │ │ └── validators │ │ ├── DefaultValidator.java │ │ ├── NumericValidator.java │ │ ├── StringTypeValidator.java │ │ ├── ValidationError.java │ │ ├── ValidationException.java │ │ ├── ValidationMessage.java │ │ └── Validator.java ├── resources │ └── logback.xml └── webapp │ └── WEB-INF │ └── web.xml └── test ├── config ├── config1.yaml └── config2.yaml ├── java └── io │ └── swagger │ └── oas │ ├── inflector │ ├── OpenAPIInflectorTest.java │ ├── config │ │ ├── ConfigurationTest.java │ │ └── DirectionDeserializerTest.java │ ├── controllers │ │ └── OpenAPIOperationControllerTest.java │ └── utils │ │ └── ApiErrorUtilsTest.java │ ├── sample │ ├── controllers │ │ └── TestController.java │ ├── converters │ │ └── SampleConverter.java │ └── models │ │ ├── Category.java │ │ ├── Dog.java │ │ ├── Pet.java │ │ └── Tag.java │ └── test │ ├── ArraySerializableParamExtractionTest.java │ ├── BodyParamExtractionTest.java │ ├── ConfigurationLoaderTest.java │ ├── ResponseModelTest.java │ ├── SerializableParamExtractionTest.java │ ├── ValueCoercionTest.java │ ├── client │ ├── ApiClient.java │ ├── ApiException.java │ ├── StringUtil.java │ └── auth │ │ ├── ApiKeyAuth.java │ │ ├── Authentication.java │ │ ├── HttpBasicAuth.java │ │ └── OAuth.java │ ├── examples │ ├── ExampleBuilderTest.java │ └── ResponseExamplesTest.java │ ├── integration │ ├── FileUploadTestIT.java │ ├── RequestTestIT.java │ ├── SwaggerListingIT.java │ └── responses │ │ ├── ComplexResponseTestIT.java │ │ ├── OverloadedResponseTestIT.java │ │ ├── PrimitiveResponseTestIT.java │ │ ├── ResponseWithExceptionTestIT.java │ │ └── SchemaResponseIT.java │ ├── models │ ├── Address.java │ ├── ExtendedAddress.java │ ├── Person.java │ ├── ResponseContextSerializationTest.java │ └── User.java │ ├── processors │ ├── BinaryProcessorTest.java │ └── JacksonProcessorTest.java │ ├── schema │ └── SchemaValidationTest.java │ ├── utils │ ├── ExtensionsUtilTest.java │ └── ReflectionUtilsTest.java │ └── validators │ ├── DefaultValidatorTest.java │ ├── NumericValidatorTest.java │ └── StringTypeValidatorTest.java ├── resources └── io │ └── swagger │ └── oas │ └── inflector │ └── config │ ├── validation-as-false.yaml │ ├── validation-as-incomplete.yaml │ ├── validation-as-object-array.yaml │ ├── validation-as-object.yaml │ ├── validation-as-scalar.yaml │ ├── validation-as-set.yaml │ ├── validation-as-string-array.yaml │ └── validation-as-true.yaml └── swagger ├── additionalProperties.yaml ├── allOfAndRef.yaml ├── allOfAndRefResolveFully.yaml ├── array-example.yaml ├── example-types.yaml ├── issue-1177.yaml ├── issue-1261.yaml ├── issue-1263.yaml ├── issue-171.yaml ├── issue-300.yaml ├── issue252.yaml ├── nested-array-example.yaml ├── null-examples-oas3-no-flag.yaml ├── null-examples-oas3.yaml ├── oas3.yaml ├── oas3_array.yaml ├── oas3_password.yaml ├── oneOf-anyOf.yaml ├── sample1.yaml ├── sampleNull.json ├── swos-126.yaml └── write-only.yaml /.github/topissuebot.yml: -------------------------------------------------------------------------------- 1 | labelName: ":thumbsup: Top Issue!" 2 | labelColor: "f442c2" 3 | numberOfIssuesToLabel: 5 4 | -------------------------------------------------------------------------------- /.github/workflows/codeql-analysis.yml: -------------------------------------------------------------------------------- 1 | name: "Code scanning - action" 2 | 3 | on: 4 | push: 5 | branches: [master, v1] 6 | pull_request: 7 | # The branches below must be a subset of the branches above 8 | branches: [master, v1] 9 | schedule: 10 | - cron: '0 19 * * 1' 11 | 12 | jobs: 13 | CodeQL-Build: 14 | 15 | runs-on: ubuntu-latest 16 | 17 | steps: 18 | - name: Checkout repository 19 | uses: actions/checkout@v2 20 | with: 21 | # We must fetch at least the immediate parents so that if this is 22 | # a pull request then we can checkout the head. 23 | fetch-depth: 2 24 | 25 | # If this run was triggered by a pull request event, then checkout 26 | # the head of the pull request instead of the merge commit. 27 | - run: git checkout HEAD^2 28 | if: ${{ github.event_name == 'pull_request' }} 29 | 30 | # Initializes the CodeQL tools for scanning. 31 | - name: Initialize CodeQL 32 | uses: github/codeql-action/init@v1 33 | # Override language selection by uncommenting this and choosing your languages 34 | with: 35 | languages: java 36 | 37 | # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). 38 | # If this step fails, then you should remove it and run the build manually (see below) 39 | - name: Autobuild 40 | uses: github/codeql-action/autobuild@v1 41 | 42 | # ℹ️ Command-line programs to run using the OS shell. 43 | # 📚 https://git.io/JvXDl 44 | 45 | # ✏️ If the Autobuild fails above, remove it and uncomment the following three lines 46 | # and modify them (or add more) to build your code if your project 47 | # uses a compiled language 48 | 49 | #- run: | 50 | # make bootstrap 51 | # make release 52 | 53 | - name: Perform CodeQL Analysis 54 | uses: github/codeql-action/analyze@v1 55 | -------------------------------------------------------------------------------- /.github/workflows/maven-pulls.yml: -------------------------------------------------------------------------------- 1 | name: Build Test PR 2 | 3 | on: 4 | pull_request: 5 | branches: [ "master" ] 6 | 7 | jobs: 8 | build: 9 | 10 | runs-on: ubuntu-latest 11 | strategy: 12 | matrix: 13 | java: [ 8, 11 ] 14 | 15 | steps: 16 | - uses: actions/checkout@v4 17 | - name: Set up Java 18 | uses: actions/setup-java@v4 19 | with: 20 | java-version: ${{ matrix.java }} 21 | distribution: temurin 22 | server-id: central 23 | - name: Cache local Maven repository 24 | uses: actions/cache@v4 25 | with: 26 | path: ~/.m2/repository 27 | key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }} 28 | restore-keys: | 29 | ${{ runner.os }}-maven- 30 | - name: Build with Maven 31 | run: | 32 | mvn --no-transfer-progress -B verify --file pom.xml 33 | -------------------------------------------------------------------------------- /.github/workflows/maven-v1-pulls.yml: -------------------------------------------------------------------------------- 1 | name: Build Test PR v1 2 | 3 | on: 4 | pull_request: 5 | branches: [ "v1" ] 6 | 7 | jobs: 8 | build: 9 | 10 | runs-on: ubuntu-latest 11 | strategy: 12 | matrix: 13 | java: [ 8 ] 14 | 15 | steps: 16 | - uses: actions/checkout@v2 17 | - name: Set up Java 18 | uses: actions/setup-java@v2 19 | with: 20 | java-version: ${{ matrix.java }} 21 | distribution: 'zulu' 22 | - name: Cache local Maven repository 23 | uses: actions/cache@v2 24 | with: 25 | path: ~/.m2/repository 26 | key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }} 27 | restore-keys: | 28 | ${{ runner.os }}-maven- 29 | - name: Build with Maven 30 | run: mvn -B verify --file pom.xml 31 | -------------------------------------------------------------------------------- /.github/workflows/maven-v1.yml: -------------------------------------------------------------------------------- 1 | name: Build Test Deploy v1 2 | 3 | on: 4 | push: 5 | branches: [ "v1" ] 6 | 7 | jobs: 8 | build: 9 | 10 | runs-on: ubuntu-latest 11 | strategy: 12 | matrix: 13 | java: [ 8 ] 14 | 15 | steps: 16 | - uses: actions/checkout@v2 17 | - name: Set up Java 18 | uses: actions/setup-java@v2 19 | with: 20 | java-version: ${{ matrix.java }} 21 | distribution: 'zulu' 22 | server-id: ossrh 23 | server-username: MAVEN_USERNAME 24 | server-password: MAVEN_PASSWORD 25 | - name: Cache local Maven repository 26 | uses: actions/cache@v2 27 | with: 28 | path: ~/.m2/repository 29 | key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }} 30 | restore-keys: | 31 | ${{ runner.os }}-maven- 32 | - name: Build with Maven, Deploy snapshot to maven central 33 | run: | 34 | mvn --no-transfer-progress -B verify --file pom.xml 35 | export MY_POM_VERSION=`mvn -q -Dexec.executable="echo" -Dexec.args='${projects.version}' --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec` 36 | echo "POM VERSION" ${MY_POM_VERSION} 37 | if [[ $MY_POM_VERSION =~ ^.*SNAPSHOT$ ]]; 38 | then 39 | mvn --no-transfer-progress -B clean deploy 40 | else 41 | echo "not deploying release: " ${MY_POM_VERSION} 42 | fi 43 | env: 44 | MAVEN_USERNAME: ${{ secrets.OSSRH_USERNAME }} 45 | MAVEN_PASSWORD: ${{ secrets.OSSRH_TOKEN }} 46 | -------------------------------------------------------------------------------- /.github/workflows/maven.yml: -------------------------------------------------------------------------------- 1 | name: Build Test Deploy master 2 | 3 | on: 4 | push: 5 | branches: [ "master" ] 6 | 7 | jobs: 8 | build: 9 | 10 | runs-on: ubuntu-latest 11 | strategy: 12 | matrix: 13 | java: [ 8, 11 ] 14 | 15 | steps: 16 | - uses: actions/checkout@v4 17 | - name: Set up Java 18 | uses: actions/setup-java@v4 19 | with: 20 | java-version: ${{ matrix.java }} 21 | distribution: temurin 22 | server-id: central 23 | server-username: MAVEN_USERNAME 24 | server-password: MAVEN_PASSWORD 25 | - name: Cache local Maven repository 26 | uses: actions/cache@v4 27 | with: 28 | path: ~/.m2/repository 29 | key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }} 30 | restore-keys: | 31 | ${{ runner.os }}-maven- 32 | - name: Build with Maven, Deploy snapshot to maven central 33 | run: | 34 | export MY_POM_VERSION=`mvn -q -Dexec.executable="echo" -Dexec.args='${projects.version}' --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec` 35 | echo "POM VERSION" ${MY_POM_VERSION} 36 | if [[ $MY_POM_VERSION =~ ^.*SNAPSHOT$ ]]; 37 | then 38 | mvn --no-transfer-progress -B verify --file pom.xml 39 | export MY_JAVA_VERSION=`java -version 2>&1 | head -1 | cut -d'"' -f2 | sed '/^1\./s///' | cut -d'.' -f1` 40 | echo "JAVA VERSION" ${MY_JAVA_VERSION} 41 | if [[ ${MY_JAVA_VERSION} == "8" ]]; 42 | then 43 | export MY_POM_VERSION=`mvn -q -Dexec.executable="echo" -Dexec.args='${projects.version}' --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec` 44 | echo "POM VERSION" ${MY_POM_VERSION} 45 | mvn --no-transfer-progress -B clean deploy 46 | else 47 | echo "not deploying on java version: " ${MY_JAVA_VERSION} 48 | fi 49 | else 50 | echo "not building and maven publishing project as it is a release version: " ${MY_JAVA_VERSION} 51 | fi 52 | env: 53 | MAVEN_USERNAME: ${{ secrets.MAVEN_CENTRAL_USERNAME }} 54 | MAVEN_PASSWORD: ${{ secrets.MAVEN_CENTRAL_PASSWORD }} 55 | -------------------------------------------------------------------------------- /.github/workflows/next-snapshot-v1.yml: -------------------------------------------------------------------------------- 1 | name: Next Snapshot V1 2 | 3 | on: 4 | workflow_dispatch: 5 | branches: ["v1"] 6 | 7 | jobs: 8 | build: 9 | 10 | runs-on: ubuntu-latest 11 | 12 | steps: 13 | - uses: actions/checkout@v2 14 | - uses: tibdex/github-app-token@v1 15 | id: generate-token 16 | with: 17 | app_id: ${{ secrets.APP_ID }} 18 | private_key: ${{ secrets.APP_PRIVATE_KEY }} 19 | - name: Set up Python 3.10 20 | uses: actions/setup-python@v4 21 | with: 22 | python-version: '3.10' 23 | - name: Set up Java 8 24 | uses: actions/setup-java@v2 25 | with: 26 | java-version: 8 27 | distribution: 'zulu' 28 | server-id: ossrh 29 | server-username: MAVEN_USERNAME 30 | server-password: MAVEN_PASSWORD 31 | - name: Cache local Maven repository 32 | uses: actions/cache@v2 33 | with: 34 | path: ~/.m2/repository 35 | key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }} 36 | restore-keys: | 37 | ${{ runner.os }}-maven- 38 | - name: Run pre release script 39 | id: preRelease 40 | run: | 41 | # export GPG_TTY=$(tty) 42 | export MY_POM_VERSION=`mvn -q -Dexec.executable="echo" -Dexec.args='${projects.version}' --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec` 43 | if [[ $MY_POM_VERSION =~ ^.*SNAPSHOT$ ]]; 44 | then 45 | echo "not releasing snapshot version: " ${MY_POM_VERSION} 46 | echo "RELEASE_OK=no" >> $GITHUB_ENV 47 | else 48 | . ./CI/pre-release-v1.sh 49 | echo "RELEASE_OK=yes" >> $GITHUB_ENV 50 | fi 51 | echo "SC_VERSION=$SC_VERSION" >> $GITHUB_ENV 52 | echo "SC_NEXT_VERSION=$SC_NEXT_VERSION" >> $GITHUB_ENV 53 | echo "SC_LAST_RELEASE=$SC_LAST_RELEASE" >> $GITHUB_ENV 54 | - name: configure git user email 55 | run: | 56 | git config --global user.email "action@github.com" 57 | git config --global user.name "GitHub Action" 58 | git config --global hub.protocol https 59 | git remote set-url origin https://\${{ secrets.GITHUB_TOKEN }}:x-oauth-basic@github.com/swagger-api/swagger-inflector.git 60 | - name: Checkout v1 61 | uses: actions/checkout@v2 62 | with: 63 | ref: "v1" 64 | fetch-depth: 0 65 | - name: Run next snapshot script 66 | id: postRelease 67 | if: env.RELEASE_OK == 'yes' 68 | run: | 69 | . ./CI/post-nextsnap-v1.sh 70 | - name: Create Next Snapshot Pull Request 71 | uses: peter-evans/create-pull-request@v4 72 | if: env.RELEASE_OK == 'yes' 73 | with: 74 | token: ${{ steps.generate-token.outputs.token }} 75 | commit-message: bump snapshot ${{ env.SC_NEXT_VERSION }}-SNAPSHOT 76 | title: 'bump snapshot ${{ env.SC_NEXT_VERSION }}-SNAPSHOT' 77 | branch: bump-snap-${{ env.SC_NEXT_VERSION }}-SNAPSHOT 78 | 79 | env: 80 | ACTIONS_ALLOW_UNSECURE_COMMANDS: true 81 | MAVEN_USERNAME: ${{ secrets.OSSRH_USERNAME }} 82 | MAVEN_PASSWORD: ${{ secrets.OSSRH_TOKEN }} 83 | GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} 84 | SC_VERSION: 85 | SC_NEXT_VERSION: 86 | GPG_PRIVATE_KEY: ${{ secrets.OSSRH_GPG_PRIVATE_KEY }} 87 | GPG_PASSPHRASE: ${{ secrets.OSSRH_GPG_PRIVATE_PASSPHRASE }} 88 | -------------------------------------------------------------------------------- /.github/workflows/next-snapshot.yml: -------------------------------------------------------------------------------- 1 | name: Next Snapshot 2 | 3 | on: 4 | workflow_dispatch: 5 | branches: ["master"] 6 | 7 | jobs: 8 | build: 9 | 10 | runs-on: ubuntu-latest 11 | 12 | steps: 13 | - uses: actions/checkout@v4 14 | - uses: tibdex/github-app-token@v1 15 | id: generate-token 16 | with: 17 | app_id: ${{ secrets.APP_ID }} 18 | private_key: ${{ secrets.APP_PRIVATE_KEY }} 19 | - name: Set up Python 3.10 20 | uses: actions/setup-python@v4 21 | with: 22 | python-version: '3.10' 23 | - name: Set up Java 24 | uses: actions/setup-java@v4 25 | with: 26 | java-version: 8 27 | distribution: temurin 28 | server-id: central 29 | server-username: MAVEN_USERNAME 30 | server-password: MAVEN_PASSWORD 31 | - name: Cache local Maven repository 32 | uses: actions/cache@v2 33 | with: 34 | path: ~/.m2/repository 35 | key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }} 36 | restore-keys: | 37 | ${{ runner.os }}-maven- 38 | - name: Run pre release script 39 | id: preRelease 40 | run: | 41 | # export GPG_TTY=$(tty) 42 | export MY_POM_VERSION=`mvn -q -Dexec.executable="echo" -Dexec.args='${projects.version}' --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec` 43 | if [[ $MY_POM_VERSION =~ ^.*SNAPSHOT$ ]]; 44 | then 45 | echo "not releasing snapshot version: " ${MY_POM_VERSION} 46 | echo "RELEASE_OK=no" >> $GITHUB_ENV 47 | else 48 | . ./CI/pre-release.sh 49 | echo "RELEASE_OK=yes" >> $GITHUB_ENV 50 | fi 51 | echo "SC_VERSION=$SC_VERSION" >> $GITHUB_ENV 52 | echo "SC_NEXT_VERSION=$SC_NEXT_VERSION" >> $GITHUB_ENV 53 | echo "SC_LAST_RELEASE=$SC_LAST_RELEASE" >> $GITHUB_ENV 54 | - name: configure git user email 55 | run: | 56 | git config --global user.email "action@github.com" 57 | git config --global user.name "GitHub Action" 58 | git config --global hub.protocol https 59 | git remote set-url origin https://\${{ secrets.GITHUB_TOKEN }}:x-oauth-basic@github.com/swagger-api/swagger-inflector.git 60 | - name: Checkout master 61 | uses: actions/checkout@v2 62 | with: 63 | ref: "master" 64 | fetch-depth: 0 65 | - name: Run next snapshot script 66 | id: postRelease 67 | if: env.RELEASE_OK == 'yes' 68 | run: | 69 | . ./CI/post-nextsnap.sh 70 | - name: Create Next Snapshot Pull Request 71 | uses: peter-evans/create-pull-request@v4 72 | if: env.RELEASE_OK == 'yes' 73 | with: 74 | token: ${{ steps.generate-token.outputs.token }} 75 | commit-message: bump snapshot ${{ env.SC_NEXT_VERSION }}-SNAPSHOT 76 | title: 'bump snapshot ${{ env.SC_NEXT_VERSION }}-SNAPSHOT' 77 | branch: bump-snap-${{ env.SC_NEXT_VERSION }}-SNAPSHOT 78 | 79 | env: 80 | ACTIONS_ALLOW_UNSECURE_COMMANDS: true 81 | MAVEN_USERNAME: ${{ secrets.MAVEN_CENTRAL_USERNAME }} 82 | MAVEN_PASSWORD: ${{ secrets.MAVEN_CENTRAL_PASSWORD }} 83 | GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} 84 | SC_VERSION: 85 | SC_NEXT_VERSION: 86 | GPG_PRIVATE_KEY: ${{ secrets.OSSRH_GPG_PRIVATE_KEY }} 87 | GPG_PASSPHRASE: ${{ secrets.OSSRH_GPG_PRIVATE_PASSPHRASE }} 88 | -------------------------------------------------------------------------------- /.github/workflows/prepare-release-v1.yml: -------------------------------------------------------------------------------- 1 | name: Prepare Release V1 2 | 3 | on: 4 | workflow_dispatch: 5 | branches: ["v1"] 6 | 7 | jobs: 8 | build: 9 | 10 | runs-on: ubuntu-latest 11 | 12 | steps: 13 | - uses: actions/checkout@v2 14 | - uses: tibdex/github-app-token@v1 15 | id: generate-token 16 | with: 17 | app_id: ${{ secrets.APP_ID }} 18 | private_key: ${{ secrets.APP_PRIVATE_KEY }} 19 | - name: Set up Python 3.10 20 | uses: actions/setup-python@v4 21 | with: 22 | python-version: '3.10' 23 | - name: Set up Java 8 24 | uses: actions/setup-java@v2 25 | with: 26 | java-version: 8 27 | distribution: 'zulu' 28 | server-id: ossrh 29 | server-username: MAVEN_USERNAME 30 | server-password: MAVEN_PASSWORD 31 | - name: Cache local Maven repository 32 | uses: actions/cache@v2 33 | with: 34 | path: ~/.m2/repository 35 | key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }} 36 | restore-keys: | 37 | ${{ runner.os }}-maven- 38 | - name: Run prepare release script 39 | id: prepare-release 40 | run: | 41 | export MY_POM_VERSION=`mvn -q -Dexec.executable="echo" -Dexec.args='${projects.version}' --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec` 42 | if [[ $MY_POM_VERSION =~ ^.*SNAPSHOT$ ]]; 43 | then 44 | . ./CI/prepare-release-v1.sh 45 | echo "PREPARE_RELEASE_OK=yes" >> $GITHUB_ENV 46 | else 47 | echo "not preparing release for release version: " ${MY_POM_VERSION} 48 | echo "PREPARE_RELEASE_OK=no" >> $GITHUB_ENV 49 | fi 50 | echo "SC_VERSION=$SC_VERSION" >> $GITHUB_ENV 51 | echo "SC_NEXT_VERSION=$SC_NEXT_VERSION" >> $GITHUB_ENV 52 | - name: Create Prepare Release Pull Request 53 | uses: peter-evans/create-pull-request@v4 54 | if: env.PREPARE_RELEASE_OK == 'yes' 55 | with: 56 | token: ${{ steps.generate-token.outputs.token }} 57 | commit-message: prepare release ${{ env.SC_VERSION }} 58 | title: 'prepare release ${{ env.SC_VERSION }}' 59 | branch: prepare-release-${{ env.SC_VERSION }} 60 | env: 61 | ACTIONS_ALLOW_UNSECURE_COMMANDS: true 62 | MAVEN_USERNAME: ${{ secrets.OSSRH_USERNAME }} 63 | MAVEN_PASSWORD: ${{ secrets.OSSRH_TOKEN }} 64 | GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} 65 | SC_VERSION: 66 | SC_NEXT_VERSION: 67 | -------------------------------------------------------------------------------- /.github/workflows/prepare-release.yml: -------------------------------------------------------------------------------- 1 | name: Prepare Release 2 | 3 | on: 4 | workflow_dispatch: 5 | branches: ["master"] 6 | 7 | jobs: 8 | build: 9 | 10 | runs-on: ubuntu-latest 11 | 12 | steps: 13 | - uses: actions/checkout@v4 14 | - uses: tibdex/github-app-token@v1 15 | id: generate-token 16 | with: 17 | app_id: ${{ secrets.APP_ID }} 18 | private_key: ${{ secrets.APP_PRIVATE_KEY }} 19 | - name: Set up Python 3.10 20 | uses: actions/setup-python@v4 21 | with: 22 | python-version: '3.10' 23 | - name: Set up Java 8 24 | uses: actions/setup-java@v4 25 | with: 26 | java-version: 8 27 | distribution: temurin 28 | server-id: central 29 | server-username: MAVEN_USERNAME 30 | server-password: MAVEN_PASSWORD 31 | - name: Cache local Maven repository 32 | uses: actions/cache@v4 33 | with: 34 | path: ~/.m2/repository 35 | key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }} 36 | restore-keys: | 37 | ${{ runner.os }}-maven- 38 | - name: Run prepare release script 39 | id: prepare-release 40 | run: | 41 | export MY_POM_VERSION=`mvn -q -Dexec.executable="echo" -Dexec.args='${projects.version}' --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec` 42 | if [[ $MY_POM_VERSION =~ ^.*SNAPSHOT$ ]]; 43 | then 44 | . ./CI/prepare-release.sh 45 | echo "PREPARE_RELEASE_OK=yes" >> $GITHUB_ENV 46 | else 47 | echo "not preparing release for release version: " ${MY_POM_VERSION} 48 | echo "PREPARE_RELEASE_OK=no" >> $GITHUB_ENV 49 | fi 50 | echo "SC_VERSION=$SC_VERSION" >> $GITHUB_ENV 51 | echo "SC_NEXT_VERSION=$SC_NEXT_VERSION" >> $GITHUB_ENV 52 | - name: Create Prepare Release Pull Request 53 | uses: peter-evans/create-pull-request@v4 54 | if: env.PREPARE_RELEASE_OK == 'yes' 55 | with: 56 | token: ${{ steps.generate-token.outputs.token }} 57 | commit-message: prepare release ${{ env.SC_VERSION }} 58 | title: 'prepare release ${{ env.SC_VERSION }}' 59 | branch: prepare-release-${{ env.SC_VERSION }} 60 | env: 61 | ACTIONS_ALLOW_UNSECURE_COMMANDS: true 62 | MAVEN_USERNAME: ${{ secrets.MAVEN_CENTRAL_USERNAME }} 63 | MAVEN_PASSWORD: ${{ secrets.MAVEN_CENTRAL_PASSWORD }} 64 | GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} 65 | SC_VERSION: 66 | SC_NEXT_VERSION: 67 | -------------------------------------------------------------------------------- /.github/workflows/release-v1.yml: -------------------------------------------------------------------------------- 1 | name: Release V1 2 | 3 | on: 4 | workflow_dispatch: 5 | branches: ["v1"] 6 | 7 | jobs: 8 | build: 9 | 10 | runs-on: ubuntu-latest 11 | 12 | steps: 13 | - uses: actions/checkout@v2 14 | - uses: tibdex/github-app-token@v1 15 | id: generate-token 16 | with: 17 | app_id: ${{ secrets.APP_ID }} 18 | private_key: ${{ secrets.APP_PRIVATE_KEY }} 19 | - name: Set up Python 3.10 20 | uses: actions/setup-python@v4 21 | with: 22 | python-version: '3.10' 23 | - name: Set up Java 8 24 | uses: actions/setup-java@v2 25 | with: 26 | java-version: 8 27 | distribution: 'zulu' 28 | server-id: ossrh 29 | server-username: MAVEN_USERNAME 30 | server-password: MAVEN_PASSWORD 31 | - name: Cache local Maven repository 32 | uses: actions/cache@v2 33 | with: 34 | path: ~/.m2/repository 35 | key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }} 36 | restore-keys: | 37 | ${{ runner.os }}-maven- 38 | - name: Run pre release script 39 | id: preRelease 40 | run: | 41 | # export GPG_TTY=$(tty) 42 | export MY_POM_VERSION=`mvn -q -Dexec.executable="echo" -Dexec.args='${projects.version}' --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec` 43 | if [[ $MY_POM_VERSION =~ ^.*SNAPSHOT$ ]]; 44 | then 45 | echo "not releasing snapshot version: " ${MY_POM_VERSION} 46 | echo "RELEASE_OK=no" >> $GITHUB_ENV 47 | else 48 | . ./CI/pre-release-v1.sh 49 | echo "RELEASE_OK=yes" >> $GITHUB_ENV 50 | fi 51 | echo "SC_VERSION=$SC_VERSION" >> $GITHUB_ENV 52 | echo "SC_NEXT_VERSION=$SC_NEXT_VERSION" >> $GITHUB_ENV 53 | echo "SC_LAST_RELEASE=$SC_LAST_RELEASE" >> $GITHUB_ENV 54 | - name: configure git user email 55 | run: | 56 | git config --global user.email "action@github.com" 57 | git config --global user.name "GitHub Action" 58 | git config --global hub.protocol https 59 | git remote set-url origin https://\${{ secrets.GITHUB_TOKEN }}:x-oauth-basic@github.com/swagger-api/swagger-inflector.git 60 | - name: Run maven deploy/release (action-maven-publish) 61 | uses: samuelmeuli/action-maven-publish@v1 62 | if: env.RELEASE_OK == 'yes' 63 | with: 64 | gpg_private_key: ${{ secrets.OSSRH_GPG_PRIVATE_KEY }} 65 | gpg_passphrase: ${{ secrets.OSSRH_GPG_PRIVATE_PASSPHRASE }} 66 | nexus_username: ${{ secrets.OSSRH_USERNAME }} 67 | nexus_password: ${{ secrets.OSSRH_TOKEN }} 68 | maven_profiles: "release" 69 | - name: Run post release script 70 | id: postRelease 71 | if: env.RELEASE_OK == 'yes' 72 | run: | 73 | . ./CI/post-release-v1.sh 74 | - name: Create Next Snapshot Pull Request 75 | uses: peter-evans/create-pull-request@v4 76 | if: env.RELEASE_OK == 'yes' 77 | with: 78 | token: ${{ steps.generate-token.outputs.token }} 79 | commit-message: bump snapshot ${{ env.SC_NEXT_VERSION }}-SNAPSHOT 80 | title: 'bump snapshot ${{ env.SC_NEXT_VERSION }}-SNAPSHOT' 81 | branch: bump-snap-${{ env.SC_NEXT_VERSION }}-SNAPSHOT 82 | 83 | env: 84 | ACTIONS_ALLOW_UNSECURE_COMMANDS: true 85 | MAVEN_USERNAME: ${{ secrets.OSSRH_USERNAME }} 86 | MAVEN_PASSWORD: ${{ secrets.OSSRH_TOKEN }} 87 | GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} 88 | SC_VERSION: 89 | SC_NEXT_VERSION: 90 | GPG_PRIVATE_KEY: ${{ secrets.OSSRH_GPG_PRIVATE_KEY }} 91 | GPG_PASSPHRASE: ${{ secrets.OSSRH_GPG_PRIVATE_PASSPHRASE }} 92 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Release 2 | 3 | on: 4 | workflow_dispatch: 5 | branches: ["master"] 6 | 7 | jobs: 8 | build: 9 | 10 | runs-on: ubuntu-latest 11 | 12 | steps: 13 | - uses: actions/checkout@v4 14 | - uses: tibdex/github-app-token@v1 15 | id: generate-token 16 | with: 17 | app_id: ${{ secrets.APP_ID }} 18 | private_key: ${{ secrets.APP_PRIVATE_KEY }} 19 | - name: Set up Python 3.10 20 | uses: actions/setup-python@v4 21 | with: 22 | python-version: '3.10' 23 | - name: Set up Java 8 24 | uses: actions/setup-java@v4 25 | with: 26 | java-version: 8 27 | distribution: temurin 28 | server-id: central 29 | server-username: MAVEN_USERNAME 30 | server-password: MAVEN_PASSWORD 31 | gpg-private-key: ${{ secrets.OSSRH_GPG_PRIVATE_KEY }} 32 | - name: Cache local Maven repository 33 | uses: actions/cache@v4 34 | with: 35 | path: ~/.m2/repository 36 | key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }} 37 | restore-keys: | 38 | ${{ runner.os }}-maven- 39 | - name: Run pre release script 40 | id: preRelease 41 | run: | 42 | # export GPG_TTY=$(tty) 43 | export MY_POM_VERSION=`mvn -q -Dexec.executable="echo" -Dexec.args='${projects.version}' --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec` 44 | if [[ $MY_POM_VERSION =~ ^.*SNAPSHOT$ ]]; 45 | then 46 | echo "not releasing snapshot version: " ${MY_POM_VERSION} 47 | echo "RELEASE_OK=no" >> $GITHUB_ENV 48 | else 49 | . ./CI/pre-release.sh 50 | echo "RELEASE_OK=yes" >> $GITHUB_ENV 51 | fi 52 | echo "SC_VERSION=$SC_VERSION" >> $GITHUB_ENV 53 | echo "SC_NEXT_VERSION=$SC_NEXT_VERSION" >> $GITHUB_ENV 54 | echo "SC_LAST_RELEASE=$SC_LAST_RELEASE" >> $GITHUB_ENV 55 | - name: configure git user email 56 | run: | 57 | git config --global user.email "action@github.com" 58 | git config --global user.name "GitHub Action" 59 | git config --global hub.protocol https 60 | git remote set-url origin https://\${{ secrets.GITHUB_TOKEN }}:x-oauth-basic@github.com/swagger-api/swagger-inflector.git 61 | - name: Run maven deploy/release 62 | if: env.RELEASE_OK == 'yes' 63 | run: | 64 | mvn --no-transfer-progress -B -Prelease deploy 65 | - name: Run post release script 66 | id: postRelease 67 | if: env.RELEASE_OK == 'yes' 68 | run: | 69 | . ./CI/post-release.sh 70 | - name: Create Next Snapshot Pull Request 71 | uses: peter-evans/create-pull-request@v4 72 | if: env.RELEASE_OK == 'yes' 73 | with: 74 | token: ${{ steps.generate-token.outputs.token }} 75 | commit-message: bump snapshot ${{ env.SC_NEXT_VERSION }}-SNAPSHOT 76 | title: 'bump snapshot ${{ env.SC_NEXT_VERSION }}-SNAPSHOT' 77 | branch: bump-snap-${{ env.SC_NEXT_VERSION }}-SNAPSHOT 78 | 79 | env: 80 | ACTIONS_ALLOW_UNSECURE_COMMANDS: true 81 | MAVEN_USERNAME: ${{ secrets.MAVEN_CENTRAL_USERNAME }} 82 | MAVEN_PASSWORD: ${{ secrets.MAVEN_CENTRAL_PASSWORD }} 83 | GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} 84 | SC_VERSION: 85 | SC_NEXT_VERSION: 86 | GPG_PRIVATE_KEY: ${{ secrets.OSSRH_GPG_PRIVATE_KEY }} 87 | GPG_PASSPHRASE: ${{ secrets.OSSRH_GPG_PRIVATE_PASSPHRASE }} 88 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .idea/ 3 | *.class 4 | hs_err_pid* 5 | target/ 6 | dependency-reduced-pom.xml 7 | .settings 8 | .project 9 | .classpath 10 | *.pyc 11 | **/*.pyc 12 | /bin/ 13 | *.ipr 14 | *.iws 15 | .DS_Store 16 | **/test-output/* 17 | -------------------------------------------------------------------------------- /.whitesource: -------------------------------------------------------------------------------- 1 | { 2 | "settingsInheritedFrom": "swagger-api/whitesource-config@main", 3 | "scanSettings": { 4 | "baseBranches": ["master", "v1"] 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /CI/CI.md: -------------------------------------------------------------------------------- 1 | ## Continuous integration 2 | 3 | ### Build, test and deploy 4 | Swagger Inflector uses Github actions to run jobs/checks building, testing and deploying snapshots on push and PR events. 5 | 6 | These github actions are configured in `.github/workflows`: 7 | 8 | * maven.yml : Build Test Deploy master 9 | * maven-pulls.yml Build Test PR 10 | * maven-v1.yml : Build Test Deploy v1 (must exist in in `v1` branch) 11 | * maven-v1-pulls.yml Build Test PR v1 (must exist in in `v1` branch) 12 | 13 | 14 | These actions use available actions in combination with short bash scripts. 15 | 16 | ### Release 17 | 18 | Releases are semi-automated and consist in 2 actions using available public actions in combination with bash and python scripts. 19 | **TODO**: Python code is used for historical reasons to execute GitHub APIs calls, in general a more consistent environment would 20 | be more maintainable e.g. implementing a custom JavaScript or Docker Container GitHub Action and/or a bash only script(s). 21 | 22 | #### Workflow summary 23 | 24 | 1. execute `prepare-release.yml` / `Prepare Release` for `master` branch 25 | 1. check and merge the Prepare Release PR pushed by previous step. Delete the branch 26 | 1. execute `release.yml` / `Release` for `master` branch 27 | 1. check and merge the next snaphot PR pushed by previous step. Delete the branch 28 | 29 | #### Prepare Release 30 | 31 | The first action to execute is `prepare-release.yml` / `Prepare Release` for master, and 32 | `prepare-release-v1.yml` / `Prepare Release V1` for `v1` branch. 33 | 34 | This is triggered by manually executing the action, selecting `Actions` in project GitHub UI, then `Prepare Release` workflow 35 | and clicking `Run Workflow` (or `Prepare Release V1` and selecting `v1` in the dropdown) 36 | 37 | `Prepare Release` takes care of: 38 | 39 | * create release notes out of merged PRs 40 | * Draft a release with related tag 41 | * bump versions to release, and update all affected files 42 | * build and test maven 43 | * push a Pull Request with the changes for human check. 44 | 45 | After the PR checks complete, the PR can me merged, and the second phase `Release` started. 46 | 47 | #### Release 48 | 49 | Once prepare release PR has been merged, the second phase is provided by `release.yml` / `Release` actions for master, and 50 | `release-v1.yml` / `Release V1` for `v1` branch. 51 | 52 | This is triggered by manually executing the action, selecting `Actions` in project GitHub UI, then `Release` workflow 53 | and clicking `Run Workflow` (or `Release V1` and selecting `v1` in the dropdown) 54 | 55 | `Release` takes care of: 56 | 57 | * build and test maven 58 | * deploy/publish to maven central 59 | * publish the previously prepared GitHub release / tag 60 | * push PR for next snapshot 61 | 62 | 63 | ### Secrets 64 | 65 | GitHub Actions make use of `Secrets` which can be configured either with Repo or Organization scope; the needed secrets are the following: 66 | 67 | * `APP_ID` and APP_PRIVATE_KEY`: these are the values provided by an account configured GitHub App, allowing to obtain a GitHub token 68 | different from the default used in GitHub Actions (which does not allow to "chain" actions).Actions 69 | 70 | The GitHub App must be configured as detailed in [this doc](https://github.com/peter-evans/create-pull-request/blob/master/docs/concepts-guidelines.md#authenticating-with-github-app-generated-tokens). 71 | 72 | See also [here](https://github.com/peter-evans/create-pull-request/blob/master/docs/concepts-guidelines.md#triggering-further-workflow-runs) 73 | 74 | * `OSSRH_GPG_PRIVATE_KEY` and `OSSRH_GPG_PRIVATE_PASSPHRASE` : gpg key and passphrase to be used for sonatype releases 75 | GPG private key and passphrase defined to be used for sonatype deployments, as detailed in 76 | https://central.sonatype.org/pages/working-with-pgp-signatures.html (I'd say with email matching the one of the sonatype account of point 1 77 | 78 | * `OSSRH_USERNAME` and `OSSRH_TOKEN`: sonatype user/token 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | -------------------------------------------------------------------------------- /CI/ghApiClient.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | import os 4 | import time 5 | import urllib.request, urllib.error, urllib.parse 6 | import http.client 7 | import json 8 | 9 | GH_BASE_URL = "https://api.github.com/" 10 | 11 | GH_TOKEN = os.environ['GH_TOKEN'] 12 | GH_AUTH = "Bearer %s" % GH_TOKEN 13 | 14 | def readUrl(name): 15 | try: 16 | request = urllib.request.Request(GH_BASE_URL + name) 17 | request.add_header("Authorization", GH_AUTH) 18 | content = urllib.request.urlopen(request).read() 19 | jcont = json.loads(content) 20 | return jcont 21 | except urllib.error.HTTPError as e: 22 | print(('HTTPError = ' + str(e.code))) 23 | raise e 24 | except urllib.error.URLError as e: 25 | print(('URLError = ' + str(e.reason))) 26 | raise e 27 | except http.client.HTTPException as e: 28 | print(('HTTPException = ' + str(e))) 29 | raise e 30 | except Exception: 31 | import traceback 32 | print(('generic exception: ' + traceback.format_exc())) 33 | raise IOError 34 | 35 | def postUrl(name, body): 36 | global GH_BASE_URL 37 | try: 38 | time.sleep(0.05) 39 | request = urllib.request.Request(GH_BASE_URL + name) 40 | request.add_header("Authorization", GH_AUTH) 41 | request.add_header("Accept", "application/vnd.github.v3+json") 42 | data = body.encode('utf-8') 43 | content = urllib.request.urlopen(request, data).read() 44 | jcont = json.loads(content) 45 | return jcont 46 | except urllib.error.HTTPError as e: 47 | print(('HTTPError = ' + str(e.code))) 48 | print((str(e))) 49 | raise e 50 | except urllib.error.URLError as e: 51 | print(('URLError = ' + str(e.reason))) 52 | raise e 53 | except http.client.HTTPException as e: 54 | print(('HTTPException = ' + str(e))) 55 | raise e 56 | except Exception: 57 | import traceback 58 | print(('generic exception: ' + traceback.format_exc())) 59 | raise IOError 60 | -------------------------------------------------------------------------------- /CI/lastRelease.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | import ghApiClient 4 | 5 | def getLastReleaseTag(): 6 | content = ghApiClient.readUrl('repos/swagger-api/swagger-inflector/releases') 7 | for l in content: 8 | draft = l["draft"] 9 | tag = l["tag_name"] 10 | if str(draft) != 'True' and tag.startswith("v2"): 11 | return tag[1:] 12 | 13 | # main 14 | def main(): 15 | result = getLastReleaseTag() 16 | print(result) 17 | 18 | # here start main 19 | main() 20 | 21 | -------------------------------------------------------------------------------- /CI/lastReleaseV1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | import ghApiClient 4 | 5 | def getLastReleaseTag(): 6 | content = ghApiClient.readUrl('repos/swagger-api/swagger-inflector/releases') 7 | for l in content: 8 | draft = l["draft"] 9 | tag = l["tag_name"] 10 | if str(draft) != 'True' and tag.startswith("v1"): 11 | return tag[1:] 12 | 13 | # main 14 | def main(): 15 | result = getLastReleaseTag() 16 | print(result) 17 | 18 | # here start main 19 | main() 20 | 21 | -------------------------------------------------------------------------------- /CI/post-nextsnap-v1.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | CUR=$(pwd) 4 | TMPDIR="$(dirname -- "${0}")" 5 | 6 | SC_RELEASE_TAG="v$SC_VERSION" 7 | 8 | ##################### 9 | ### update the version to next snapshot in maven project with set version 10 | ##################### 11 | mvn versions:set -DnewVersion="${SC_NEXT_VERSION}-SNAPSHOT" 12 | mvn versions:commit 13 | 14 | ##################### 15 | ### update all other versions in files around to the new release, including readme ### 16 | ##################### 17 | sc_find="$SC_LAST_RELEASE" 18 | sc_replace="$SC_VERSION" 19 | sed -i -e "s/$sc_find/$sc_replace/g" $CUR/README.md 20 | 21 | sc_find="$SC_VERSION-SNAPSHOT<\/version>" 22 | sc_replace="$SC_VERSION<\/version>" 23 | sed -i -e "s/$sc_find/$sc_replace/g" $CUR/scripts/pom.xml 24 | 25 | -------------------------------------------------------------------------------- /CI/post-nextsnap.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | CUR=$(pwd) 4 | TMPDIR="$(dirname -- "${0}")" 5 | 6 | SC_RELEASE_TAG="v$SC_VERSION" 7 | 8 | ##################### 9 | ### update the version to next snapshot in maven project with set version 10 | ##################### 11 | mvn versions:set -DnewVersion="${SC_NEXT_VERSION}-SNAPSHOT" 12 | mvn versions:commit 13 | 14 | ##################### 15 | ### update all other versions in files around to the new release, including readme ### 16 | ##################### 17 | sc_find="$SC_LAST_RELEASE" 18 | sc_replace="$SC_VERSION" 19 | sed -i -e "s/$sc_find/$sc_replace/g" $CUR/README.md 20 | 21 | sc_find="$SC_VERSION-SNAPSHOT<\/version>" 22 | sc_replace="$SC_VERSION<\/version>" 23 | sed -i -e "s/$sc_find/$sc_replace/g" $CUR/scripts/pom.xml 24 | 25 | -------------------------------------------------------------------------------- /CI/post-release-v1.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | CUR=$(pwd) 4 | TMPDIR="$(dirname -- "${0}")" 5 | 6 | SC_RELEASE_TAG="v$SC_VERSION" 7 | 8 | ##################### 9 | ### publish pre-prepared release (tag is created) 10 | ##################### 11 | python $CUR/CI/publishReleaseV1.py "$SC_RELEASE_TAG" 12 | 13 | ##################### 14 | ### update the version to next snapshot in maven project with set version 15 | ##################### 16 | mvn versions:set -DnewVersion="${SC_NEXT_VERSION}-SNAPSHOT" 17 | mvn versions:commit 18 | -------------------------------------------------------------------------------- /CI/post-release.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | CUR=$(pwd) 4 | TMPDIR="$(dirname -- "${0}")" 5 | 6 | SC_RELEASE_TAG="v$SC_VERSION" 7 | 8 | ##################### 9 | ### publish pre-prepared release (tag is created) 10 | ##################### 11 | python $CUR/CI/publishRelease.py "$SC_RELEASE_TAG" 12 | 13 | ##################### 14 | ### update the version to next snapshot in maven project with set version 15 | ##################### 16 | mvn versions:set -DnewVersion="${SC_NEXT_VERSION}-SNAPSHOT" 17 | mvn versions:commit 18 | 19 | ##################### 20 | ### update all other versions in files around to the new release, including readme ### 21 | ##################### 22 | sc_find="$SC_VERSION" 23 | sc_replace="${SC_NEXT_VERSION}-SNAPSHOT" 24 | sed -i -e "s/$sc_find/$sc_replace/g" $CUR/README.md 25 | 26 | sc_find="$SC_VERSION<\/version>" 27 | sc_replace="${SC_NEXT_VERSION}-SNAPSHOT<\/version>" 28 | sed -i -e "s/$sc_find/$sc_replace/g" $CUR/scripts/pom.xml 29 | 30 | -------------------------------------------------------------------------------- /CI/pre-release-v1.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | CUR=$(pwd) 4 | 5 | export SC_VERSION=`mvn -q -Dexec.executable="echo" -Dexec.args='${parsedVersion.majorVersion}.${parsedVersion.minorVersion}.${parsedVersion.incrementalVersion}' --non-recursive build-helper:parse-version org.codehaus.mojo:exec-maven-plugin:1.3.1:exec` 6 | export SC_NEXT_VERSION=`mvn -q -Dexec.executable="echo" -Dexec.args='${parsedVersion.majorVersion}.${parsedVersion.minorVersion}.${parsedVersion.nextIncrementalVersion}' --non-recursive build-helper:parse-version org.codehaus.mojo:exec-maven-plugin:1.3.1:exec` 7 | SC_QUALIFIER=`mvn -q -Dexec.executable="echo" -Dexec.args='${parsedVersion.qualifier}' --non-recursive build-helper:parse-version org.codehaus.mojo:exec-maven-plugin:1.3.1:exec` 8 | #SC_LAST_RELEASE=`mvn -q -Dexec.executable="echo" -Dexec.args='${releasedVersion.version}' --non-recursive org.codehaus.mojo:build-helper-maven-plugin:3.2.0:released-version org.codehaus.mojo:exec-maven-plugin:1.3.1:exec` 9 | SC_LAST_RELEASE=`python $CUR/CI/lastReleaseV1.py` 10 | 11 | 12 | SC_RELEASE_TAG="v$SC_VERSION" 13 | 14 | 15 | ##################### 16 | ### build and test maven ### 17 | ##################### 18 | mvn --no-transfer-progress -B install --file pom.xml 19 | -------------------------------------------------------------------------------- /CI/pre-release.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | CUR=$(pwd) 4 | 5 | export SC_VERSION=`mvn -q -Dexec.executable="echo" -Dexec.args='${parsedVersion.majorVersion}.${parsedVersion.minorVersion}.${parsedVersion.incrementalVersion}' --non-recursive build-helper:parse-version org.codehaus.mojo:exec-maven-plugin:1.3.1:exec` 6 | export SC_NEXT_VERSION=`mvn -q -Dexec.executable="echo" -Dexec.args='${parsedVersion.majorVersion}.${parsedVersion.minorVersion}.${parsedVersion.nextIncrementalVersion}' --non-recursive build-helper:parse-version org.codehaus.mojo:exec-maven-plugin:1.3.1:exec` 7 | SC_QUALIFIER=`mvn -q -Dexec.executable="echo" -Dexec.args='${parsedVersion.qualifier}' --non-recursive build-helper:parse-version org.codehaus.mojo:exec-maven-plugin:1.3.1:exec` 8 | #SC_LAST_RELEASE=`mvn -q -Dexec.executable="echo" -Dexec.args='${releasedVersion.version}' --non-recursive org.codehaus.mojo:build-helper-maven-plugin:3.2.0:released-version org.codehaus.mojo:exec-maven-plugin:1.3.1:exec` 9 | SC_LAST_RELEASE=`python $CUR/CI/lastRelease.py` 10 | 11 | 12 | SC_RELEASE_TAG="v$SC_VERSION" 13 | 14 | 15 | ##################### 16 | ### build and test maven ### 17 | ##################### 18 | mvn --no-transfer-progress -B install --file pom.xml 19 | -------------------------------------------------------------------------------- /CI/prepare-release-v1.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | CUR=$(pwd) 4 | 5 | export SC_VERSION=`mvn -q -Dexec.executable="echo" -Dexec.args='${parsedVersion.majorVersion}.${parsedVersion.minorVersion}.${parsedVersion.incrementalVersion}' --non-recursive build-helper:parse-version org.codehaus.mojo:exec-maven-plugin:1.3.1:exec` 6 | export SC_NEXT_VERSION=`mvn -q -Dexec.executable="echo" -Dexec.args='${parsedVersion.majorVersion}.${parsedVersion.minorVersion}.${parsedVersion.nextIncrementalVersion}' --non-recursive build-helper:parse-version org.codehaus.mojo:exec-maven-plugin:1.3.1:exec` 7 | SC_QUALIFIER=`mvn -q -Dexec.executable="echo" -Dexec.args='${parsedVersion.qualifier}' --non-recursive build-helper:parse-version org.codehaus.mojo:exec-maven-plugin:1.3.1:exec` 8 | #SC_LAST_RELEASE=`mvn -q -Dexec.executable="echo" -Dexec.args='${releasedVersion.version}' --non-recursive org.codehaus.mojo:build-helper-maven-plugin:3.2.0:released-version org.codehaus.mojo:exec-maven-plugin:1.3.1:exec` 9 | SC_LAST_RELEASE=`python $CUR/CI/lastReleaseV1.py` 10 | 11 | 12 | 13 | SC_RELEASE_TITLE="Swagger-inflector $SC_VERSION released!" 14 | SC_RELEASE_TAG="v$SC_VERSION" 15 | 16 | 17 | ##################### 18 | ### draft release Notes with next release after last release, with tag 19 | ##################### 20 | python $CUR/CI/releaseNotesV1.py "$SC_LAST_RELEASE" "$SC_RELEASE_TITLE" "$SC_RELEASE_TAG" 21 | 22 | ##################### 23 | ### update the version to release in maven project with set version 24 | ##################### 25 | mvn versions:set -DnewVersion=$SC_VERSION 26 | mvn versions:commit 27 | 28 | ##################### 29 | ### update all other versions in files around to the new release, including readme ### 30 | ##################### 31 | sc_find="$SC_LAST_RELEASE" 32 | sc_replace="$SC_VERSION" 33 | sed -i -e "s/$sc_find/$sc_replace/g" $CUR/README.md 34 | 35 | sc_find="$SC_VERSION-SNAPSHOT<\/version>" 36 | sc_replace="$SC_VERSION<\/version>" 37 | sed -i -e "s/$sc_find/$sc_replace/g" $CUR/scripts/pom.xml 38 | 39 | ##################### 40 | ### build and test maven ### 41 | ##################### 42 | mvn --no-transfer-progress -B install --file pom.xml 43 | 44 | -------------------------------------------------------------------------------- /CI/prepare-release.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | CUR=$(pwd) 4 | 5 | export SC_VERSION=`mvn -q -Dexec.executable="echo" -Dexec.args='${parsedVersion.majorVersion}.${parsedVersion.minorVersion}.${parsedVersion.incrementalVersion}' --non-recursive build-helper:parse-version org.codehaus.mojo:exec-maven-plugin:1.3.1:exec` 6 | export SC_NEXT_VERSION=`mvn -q -Dexec.executable="echo" -Dexec.args='${parsedVersion.majorVersion}.${parsedVersion.minorVersion}.${parsedVersion.nextIncrementalVersion}' --non-recursive build-helper:parse-version org.codehaus.mojo:exec-maven-plugin:1.3.1:exec` 7 | SC_QUALIFIER=`mvn -q -Dexec.executable="echo" -Dexec.args='${parsedVersion.qualifier}' --non-recursive build-helper:parse-version org.codehaus.mojo:exec-maven-plugin:1.3.1:exec` 8 | #SC_LAST_RELEASE=`mvn -q -Dexec.executable="echo" -Dexec.args='${releasedVersion.version}' --non-recursive org.codehaus.mojo:build-helper-maven-plugin:3.2.0:released-version org.codehaus.mojo:exec-maven-plugin:1.3.1:exec` 9 | SC_LAST_RELEASE=`python $CUR/CI/lastRelease.py` 10 | 11 | 12 | 13 | SC_RELEASE_TITLE="Swagger-inflector $SC_VERSION released!" 14 | SC_RELEASE_TAG="v$SC_VERSION" 15 | 16 | 17 | ##################### 18 | ### draft release Notes with next release after last release, with tag 19 | ##################### 20 | python $CUR/CI/releaseNotes.py "$SC_LAST_RELEASE" "$SC_RELEASE_TITLE" "$SC_RELEASE_TAG" 21 | 22 | ##################### 23 | ### update the version to release in maven project with set version 24 | ##################### 25 | mvn versions:set -DnewVersion=$SC_VERSION 26 | mvn versions:commit 27 | 28 | ##################### 29 | ### update all other versions in files around to the new release, including readme ### 30 | ##################### 31 | sc_find="$SC_LAST_RELEASE" 32 | sc_replace="$SC_VERSION" 33 | sed -i -e "s/$sc_find/$sc_replace/g" $CUR/README.md 34 | 35 | sc_find="$SC_VERSION-SNAPSHOT<\/version>" 36 | sc_replace="$SC_VERSION<\/version>" 37 | sed -i -e "s/$sc_find/$sc_replace/g" $CUR/scripts/pom.xml 38 | 39 | 40 | 41 | ##################### 42 | ### build and test maven ### 43 | ##################### 44 | mvn --no-transfer-progress -B install --file pom.xml 45 | 46 | -------------------------------------------------------------------------------- /CI/publishRelease.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | import sys 4 | import ghApiClient 5 | 6 | def lastReleaseId(tag): 7 | content = ghApiClient.readUrl('repos/swagger-api/swagger-inflector/releases') 8 | for l in content: 9 | draft = l["draft"] 10 | draft_tag = l["tag_name"] 11 | if str(draft) == 'True' and tag == draft_tag: 12 | return l["id"] 13 | 14 | def publishRelease(tag): 15 | id = lastReleaseId(tag) 16 | payload = "{\"tag_name\":\"" + tag + "\", " 17 | payload += "\"draft\":" + "false" + ", " 18 | payload += "\"target_commitish\":\"" + "master" + "\"}" 19 | content = ghApiClient.postUrl('repos/swagger-api/swagger-inflector/releases/' + str(id), payload) 20 | return content 21 | 22 | # main 23 | def main(tag): 24 | publishRelease (tag) 25 | 26 | # here start main 27 | main(sys.argv[1]) 28 | 29 | -------------------------------------------------------------------------------- /CI/publishReleaseV1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | import sys 4 | import ghApiClient 5 | 6 | def lastReleaseId(tag): 7 | content = ghApiClient.readUrl('repos/swagger-api/swagger-inflector/releases') 8 | for l in content: 9 | draft = l["draft"] 10 | draft_tag = l["tag_name"] 11 | if str(draft) == 'True' and tag == draft_tag: 12 | return l["id"] 13 | 14 | def publishRelease(tag): 15 | id = lastReleaseId(tag) 16 | payload = "{\"tag_name\":\"" + tag + "\", " 17 | payload += "\"draft\":" + "false" + ", " 18 | payload += "\"target_commitish\":\"" + "v1" + "\"}" 19 | content = ghApiClient.postUrl('repos/swagger-api/swagger-inflector/releases/' + str(id), payload) 20 | return content 21 | 22 | # main 23 | def main(tag): 24 | publishRelease (tag) 25 | 26 | # here start main 27 | main(sys.argv[1]) 28 | 29 | -------------------------------------------------------------------------------- /CI/releaseNotes.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | import sys 4 | import json 5 | from datetime import datetime 6 | import ghApiClient 7 | 8 | def allPulls(releaseDate): 9 | 10 | result = "" 11 | 12 | baseurl = "https://api.github.com/repos/swagger-api/swagger-inflector/pulls/" 13 | content = ghApiClient.readUrl('repos/swagger-api/swagger-inflector/pulls?state=closed&base=master&per_page=100') 14 | for l in content: 15 | stripped = l["url"][len(baseurl):] 16 | mergedAt = l["merged_at"] 17 | if mergedAt is not None: 18 | if datetime.strptime(mergedAt, '%Y-%m-%dT%H:%M:%SZ') > releaseDate: 19 | if not l['title'].startswith("bump snap"): 20 | result += '\n' 21 | result += "* " + l['title'] + " (#" + stripped + ")" 22 | return result 23 | 24 | 25 | def lastReleaseDate(tag): 26 | content = ghApiClient.readUrl('repos/swagger-api/swagger-inflector/releases/tags/' + tag) 27 | publishedAt = content["published_at"] 28 | return datetime.strptime(publishedAt, '%Y-%m-%dT%H:%M:%SZ') 29 | 30 | 31 | def addRelease(release_title, tag, content): 32 | payload = "{\"tag_name\":\"" + tag + "\", " 33 | payload += "\"name\":" + json.dumps(release_title) + ", " 34 | payload += "\"body\":" + json.dumps(content) + ", " 35 | payload += "\"draft\":" + "true" + ", " 36 | payload += "\"prerelease\":" + "false" + ", " 37 | payload += "\"target_commitish\":\"" + "master" + "\"}" 38 | content = ghApiClient.postUrl('repos/swagger-api/swagger-inflector/releases', payload) 39 | return content 40 | 41 | def getReleases(): 42 | content = ghApiClient.readUrl('repos/swagger-api/swagger-inflector/releases') 43 | return content 44 | 45 | # main 46 | def main(last_release, release_title, tag): 47 | result = allPulls(lastReleaseDate('v' + last_release)) 48 | addRelease (release_title, tag, result) 49 | 50 | # here start main 51 | main(sys.argv[1], sys.argv[2], sys.argv[3]) 52 | 53 | -------------------------------------------------------------------------------- /CI/releaseNotesV1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | import sys 4 | import json 5 | from datetime import datetime 6 | import ghApiClient 7 | 8 | def allPulls(releaseDate): 9 | 10 | result = "" 11 | 12 | baseurl = "https://api.github.com/repos/swagger-api/swagger-inflector/pulls/" 13 | content = ghApiClient.readUrl('repos/swagger-api/swagger-inflector/pulls?state=closed&base=v1&per_page=100') 14 | for l in content: 15 | stripped = l["url"][len(baseurl):] 16 | mergedAt = l["merged_at"] 17 | if mergedAt is not None: 18 | if datetime.strptime(mergedAt, '%Y-%m-%dT%H:%M:%SZ') > releaseDate: 19 | if not l['title'].startswith("bump snap"): 20 | result += '\n' 21 | result += "* " + l['title'] + " (#" + stripped + ")" 22 | return result 23 | 24 | 25 | def lastReleaseDate(tag): 26 | content = ghApiClient.readUrl('repos/swagger-api/swagger-inflector/releases/tags/' + tag) 27 | publishedAt = content["published_at"] 28 | return datetime.strptime(publishedAt, '%Y-%m-%dT%H:%M:%SZ') 29 | 30 | 31 | def addRelease(release_title, tag, content): 32 | payload = "{\"tag_name\":\"" + tag + "\", " 33 | payload += "\"name\":" + json.dumps(release_title) + ", " 34 | payload += "\"body\":" + json.dumps(content) + ", " 35 | payload += "\"draft\":" + "true" + ", " 36 | payload += "\"prerelease\":" + "false" + ", " 37 | payload += "\"target_commitish\":\"" + "v1" + "\"}" 38 | content = ghApiClient.postUrl('repos/swagger-api/swagger-inflector/releases', payload) 39 | return content 40 | 41 | def getReleases(): 42 | content = ghApiClient.readUrl('repos/swagger-api/swagger-inflector/releases') 43 | return content 44 | 45 | # main 46 | def main(last_release, release_title, tag): 47 | result = allPulls(lastReleaseDate('v' + last_release)) 48 | addRelease (release_title, tag, result) 49 | 50 | # here start main 51 | main(sys.argv[1], sys.argv[2], sys.argv[3]) 52 | 53 | -------------------------------------------------------------------------------- /scripts/bin/jetty-runner.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swagger-api/swagger-inflector/5c56ccf5334d96beac8d024e29ede39137bcf88c/scripts/bin/jetty-runner.jar -------------------------------------------------------------------------------- /scripts/bin/swagger-editor.war: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swagger-api/swagger-inflector/5c56ccf5334d96beac8d024e29ede39137bcf88c/scripts/bin/swagger-editor.war -------------------------------------------------------------------------------- /scripts/editor.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | java -Dconfig=editor/inflector.yaml -jar editor/jetty-runner.jar --port 8000 editor/swagger-editor.war -------------------------------------------------------------------------------- /scripts/inflector.yaml: -------------------------------------------------------------------------------- 1 | controllerPackage: io.swagger.oas.sample.controllers 2 | modelPackage: io.swagger.oas.sample.models 3 | swaggerUrl: ./src/main/swagger/openapi.yaml 4 | 5 | # add any model mappings you like if you have existing models to use 6 | #modelMappings: 7 | # Pet: io.swagger.sample.models.Pet 8 | 9 | entityProcessors: 10 | - json 11 | - xml 12 | 13 | # set the environment to development | staging | production 14 | environment: development -------------------------------------------------------------------------------- /scripts/openapi.yaml: -------------------------------------------------------------------------------- 1 | openapi: '3.0.3' 2 | info: 3 | version: "1.0.0" 4 | title: Sample API 5 | servers: 6 | - url: http://localhost:8080/v2 7 | paths: 8 | /people: 9 | get: 10 | tags: 11 | - People 12 | description: | 13 | Gets `Person` objects. 14 | Optional query param of **size** determines 15 | parameters: 16 | - name: size 17 | in: query 18 | description: Size of array 19 | required: true 20 | schema: 21 | type: integer 22 | format: int32 23 | responses: 24 | # Response code 25 | 200: 26 | description: Successful response 27 | content: 28 | 'application/json': 29 | schema: 30 | type: array 31 | items: 32 | $ref: '#/components/schemas/Person' 33 | 34 | components: 35 | schemas: 36 | Person: 37 | type: object 38 | properties: 39 | firstname: 40 | type: string 41 | lastname: 42 | type: string 43 | single: 44 | type: boolean 45 | -------------------------------------------------------------------------------- /scripts/web.xml: -------------------------------------------------------------------------------- 1 | 2 | 17 | 18 | 21 | 22 | swagger-inflector 23 | org.glassfish.jersey.servlet.ServletContainer 24 | 25 | javax.ws.rs.Application 26 | io.swagger.oas.inflector.OpenAPIInflector 27 | 28 | 1 29 | 30 | 31 | swagger-inflector 32 | /* 33 | 34 | 35 | CORSFilter 36 | io.swagger.oas.inflector.utils.CORSFilter 37 | 38 | 39 | CORSFilter 40 | /* 41 | 42 | -------------------------------------------------------------------------------- /setup.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | PROJECT=$project 3 | FORK=${FORK:-"swagger-api/swagger-inflector/master"} 4 | 5 | if [ "$PROJECT" == "" ] 6 | then 7 | echo "set a project name like so:" 8 | echo "" 9 | echo "project=my-project" 10 | echo "" 11 | echo "and try again" 12 | exit 13 | fi 14 | 15 | echo "fetching setup files from $FORK" 16 | 17 | # setup dirs 18 | mkdir -p editor 19 | mkdir -p src/main/swagger 20 | mkdir -p src/main/webapp/WEB-INF 21 | 22 | if [ ! -f editor/swagger-editor.war ]; then 23 | echo "...fetching editor webapp" 24 | curl -sL "https://raw.githubusercontent.com/$FORK/scripts/bin/swagger-editor.war" -o editor/swagger-editor.war 25 | curl -sL "https://raw.githubusercontent.com/$FORK/scripts/bin/jetty-runner.jar" -o editor/jetty-runner.jar 26 | fi 27 | 28 | echo "...fetching editor scripts" 29 | curl -sL "https://raw.githubusercontent.com/$FORK/scripts/editor.sh" -o ./editor.sh 30 | 31 | echo "...fetching sample swagger description" 32 | wget --quiet --no-check-certificate "https://raw.githubusercontent.com/$FORK/scripts/openapi.yaml" -O src/main/swagger/openapi.yaml 33 | 34 | 35 | echo "...fetching inflector configuration" 36 | curl -sL "https://raw.githubusercontent.com/$FORK/scripts/inflector.yaml" -o ./inflector.yaml 37 | 38 | echo "...fetching project pom" 39 | curl -sL "https://raw.githubusercontent.com/$FORK/scripts/pom.xml" -o ./pom.xml 40 | 41 | echo "...fetching web.xml" 42 | curl -sL "https://raw.githubusercontent.com/$FORK/scripts/web.xml" -o src/main/webapp/WEB-INF/web.xml 43 | chmod a+x ./editor.sh 44 | 45 | rp="s/SAMPLE_PROJECT/$PROJECT/g" 46 | sed -i -- $rp pom.xml 47 | rm pom.xml-- 48 | 49 | echo "done! You can run swagger editor as follows:" 50 | echo "./editor.sh" 51 | echo "then open a browser at open http://localhost:8000" 52 | 53 | echo "" 54 | echo "you can run your server as follows:" 55 | echo "mvn package jetty:run" 56 | echo "" 57 | echo "and your swagger listing will be at http://localhost:8080/{basePath}/openapi.json" 58 | echo "" 59 | -------------------------------------------------------------------------------- /src/main/java/io/swagger/oas/inflector/Constants.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 SmartBear Software 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package io.swagger.oas.inflector; 18 | 19 | public class Constants { 20 | public static final String X_SWAGGER_ROUTER_CONTROLLER = VendorExtension.X_SWAGGER_ROUTER_CONTROLLER.getValue(); 21 | public static final String X_SWAGGER_ROUTER_MODEL = VendorExtension.X_SWAGGER_ROUTER_MODEL.getValue(); 22 | public static final String X_INFLECTOR_HIDDEN = "x-inflector-hidden"; 23 | public static final String X_INFLECTOR_NULL_EXAMPLE = "x-inflector-null-example"; 24 | public static final String X_INFLECTOR_SKIP_INPUT_VALIDATION = "x-skip-input-validation"; 25 | public static final String X_INFLECTOR_SKIP_OUPUT_VALIDATION = "x-skip-output-validation"; 26 | 27 | public enum VendorExtension { 28 | X_SWAGGER_ROUTER_CONTROLLER("x-swagger-router-controller"), 29 | X_SWAGGER_ROUTER_MODEL("x-swagger-router-model"); 30 | 31 | private String value; 32 | 33 | VendorExtension(String value) { 34 | this.value = value; 35 | } 36 | 37 | public String getValue() { 38 | return value; 39 | } 40 | 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/io/swagger/oas/inflector/CustomMediaTypes.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 SmartBear Software 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package io.swagger.oas.inflector; 18 | 19 | import javax.ws.rs.core.MediaType; 20 | 21 | public class CustomMediaTypes { 22 | 23 | private CustomMediaTypes() { 24 | } 25 | 26 | public static MediaType APPLICATION_YAML = new MediaType("application", "yaml"); 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/io/swagger/oas/inflector/config/ControllerFactory.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 SmartBear Software 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package io.swagger.oas.inflector.config; 18 | 19 | 20 | import io.swagger.v3.oas.models.Operation; 21 | 22 | /** 23 | * Behaviour for instantiating controllers - provide your custom implementation to the Configuration 24 | * class for hooking into DI frameworks, script engines, etc 25 | */ 26 | 27 | public interface ControllerFactory { 28 | 29 | /** 30 | * Instantiates the provided controller class 31 | * 32 | * @param cls the class to instantiate 33 | * @param operation the operation to instantiate 34 | * @return an instance of the class 35 | * @throws IllegalAccessException The class cannot be initialized 36 | * @throws InstantiationException The class cannot be initialized 37 | */ 38 | 39 | Object instantiateController(Class cls, Operation operation) throws IllegalAccessException, InstantiationException; 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/io/swagger/oas/inflector/config/DefaultControllerFactory.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 SmartBear Software 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package io.swagger.oas.inflector.config; 18 | 19 | 20 | import io.swagger.v3.oas.models.Operation; 21 | 22 | /** 23 | * Default ControllerFactory implementation that just calls newInstance 24 | */ 25 | 26 | public class DefaultControllerFactory implements ControllerFactory { 27 | 28 | /** 29 | * Instantiates the provided class calling cls.newInstance() 30 | * 31 | * @param cls the class to be instantiated 32 | * @param operation the operation to instantiate 33 | * @return an instance of the provided class 34 | * @throws IllegalAccessException The class cannot be initialized 35 | * @throws InstantiationException The class cannot be initialized 36 | */ 37 | 38 | @Override 39 | public Object instantiateController(Class cls, Operation operation) throws IllegalAccessException, InstantiationException { 40 | return cls.newInstance(); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/io/swagger/oas/inflector/config/DirectionDeserializer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 SmartBear Software 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package io.swagger.oas.inflector.config; 18 | 19 | import com.fasterxml.jackson.core.JsonParser; 20 | import com.fasterxml.jackson.core.JsonToken; 21 | import com.fasterxml.jackson.databind.DeserializationContext; 22 | import com.fasterxml.jackson.databind.JsonDeserializer; 23 | import com.fasterxml.jackson.databind.exc.InvalidDefinitionException; 24 | 25 | import java.io.IOException; 26 | import java.util.EnumSet; 27 | import java.util.Set; 28 | 29 | public class DirectionDeserializer extends JsonDeserializer> { 30 | 31 | @Override 32 | public Set deserialize(JsonParser jp, 33 | DeserializationContext ctxt) throws IOException { 34 | final JsonToken token = jp.getCurrentToken(); 35 | if (token == JsonToken.VALUE_FALSE) { 36 | return EnumSet.noneOf(Configuration.Direction.class); 37 | } else if (token == JsonToken.VALUE_TRUE) { 38 | return EnumSet.allOf(Configuration.Direction.class); 39 | } else if (token == JsonToken.START_ARRAY) { 40 | final Set items = EnumSet.noneOf(Configuration.Direction.class); 41 | while (true) { 42 | final JsonToken next = jp.nextToken(); 43 | if (next == JsonToken.VALUE_STRING) { 44 | final String name = jp.getText(); 45 | items.add(Configuration.Direction.valueOf(name)); 46 | } else if (next == JsonToken.END_ARRAY) { 47 | return items; 48 | } else { 49 | break; 50 | } 51 | } 52 | } 53 | throw InvalidDefinitionException.from(jp, String.format("Failed to deserialize %s", jp.getText()), ctxt.constructType(Configuration.Direction.class)); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/main/java/io/swagger/oas/inflector/config/ExposedSpecOptions.java: -------------------------------------------------------------------------------- 1 | package io.swagger.oas.inflector.config; 2 | 3 | import io.swagger.v3.parser.core.models.ParseOptions; 4 | 5 | public class ExposedSpecOptions { 6 | private ParseOptions parseOptions; 7 | private boolean hideInflectorExtensions = true; 8 | private boolean useOriginalNotParsed = false; 9 | private boolean mergeRootPath = true; 10 | 11 | public ExposedSpecOptions() { 12 | this.parseOptions = new ParseOptions(); 13 | } 14 | 15 | public ParseOptions getParseOptions() { 16 | return parseOptions; 17 | } 18 | 19 | public void setParseOptions(ParseOptions parseOptions) { 20 | this.parseOptions = parseOptions; 21 | } 22 | 23 | public boolean isHideInflectorExtensions() { 24 | return hideInflectorExtensions; 25 | } 26 | 27 | public void setHideInflectorExtensions(boolean hideInflectorExtensions) { 28 | this.hideInflectorExtensions = hideInflectorExtensions; 29 | } 30 | 31 | public boolean isUseOriginalNotParsed() { 32 | return useOriginalNotParsed; 33 | } 34 | 35 | public void setUseOriginalNotParsed(boolean useOriginalNotParsed) { 36 | this.useOriginalNotParsed = useOriginalNotParsed; 37 | } 38 | 39 | public boolean isMergeRootPath() { 40 | return mergeRootPath; 41 | } 42 | 43 | public void setMergeRootPath(boolean mergeRootPath) { 44 | this.mergeRootPath = mergeRootPath; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/main/java/io/swagger/oas/inflector/config/FilterFactory.java: -------------------------------------------------------------------------------- 1 | package io.swagger.oas.inflector.config; 2 | 3 | import io.swagger.v3.core.filter.OpenAPISpecFilter; 4 | 5 | public class FilterFactory { 6 | protected static OpenAPISpecFilter FILTER = null; 7 | 8 | public static OpenAPISpecFilter getFilter() { 9 | return FILTER; 10 | } 11 | 12 | public static void setFilter(OpenAPISpecFilter filter) { 13 | FILTER = filter; 14 | } 15 | } -------------------------------------------------------------------------------- /src/main/java/io/swagger/oas/inflector/config/OpenAPIProcessor.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 SmartBear Software 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package io.swagger.oas.inflector.config; 18 | 19 | 20 | import io.swagger.v3.oas.models.OpenAPI; 21 | 22 | public interface OpenAPIProcessor { 23 | 24 | void process(OpenAPI openAPI); 25 | 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/io/swagger/oas/inflector/controllers/InflectResultController.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 SmartBear Software 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package io.swagger.oas.inflector.controllers; 18 | 19 | import io.swagger.oas.inflector.models.InflectResult; 20 | import org.glassfish.jersey.process.Inflector; 21 | 22 | import javax.ws.rs.container.ContainerRequestContext; 23 | import javax.ws.rs.core.Response; 24 | 25 | public class InflectResultController implements Inflector { 26 | private InflectResult result; 27 | 28 | public InflectResultController(InflectResult result) { 29 | this.result = result; 30 | } 31 | 32 | @Override 33 | public Response apply(ContainerRequestContext arg0) { 34 | return Response.ok().entity(result).build(); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/io/swagger/oas/inflector/converters/ConversionException.java: -------------------------------------------------------------------------------- 1 | package io.swagger.oas.inflector.converters; 2 | 3 | import io.swagger.oas.inflector.validators.ValidationMessage; 4 | 5 | public class ConversionException extends Exception { 6 | private static final long serialVersionUID = 1567596767061436973L; 7 | 8 | public ConversionException() {} 9 | 10 | private ValidationMessage message; 11 | 12 | public ConversionException message(ValidationMessage message) { 13 | this.message = message; 14 | return this; 15 | } 16 | 17 | public ValidationMessage getError() { 18 | return message; 19 | } 20 | } -------------------------------------------------------------------------------- /src/main/java/io/swagger/oas/inflector/converters/Converter.java: -------------------------------------------------------------------------------- 1 | package io.swagger.oas.inflector.converters; 2 | 3 | 4 | 5 | import io.swagger.v3.oas.models.media.Schema; 6 | import io.swagger.v3.oas.models.parameters.Parameter; 7 | import io.swagger.v3.oas.models.parameters.RequestBody; 8 | 9 | import java.util.Iterator; 10 | import java.util.List; 11 | import java.util.Map; 12 | 13 | public interface Converter { 14 | Object convert(List value, Parameter parameter, Class cls, Map definitions, Iterator chain) throws ConversionException; 15 | Object convert(List value, RequestBody body, Class cls, Map definitions, Iterator chain) throws ConversionException; 16 | Object convert(List value, RequestBody body, Class cls, Class innerClass, Map definitions, Iterator chain) throws ConversionException; 17 | 18 | } -------------------------------------------------------------------------------- /src/main/java/io/swagger/oas/inflector/examples/models/AbstractExample.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 SmartBear Software 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package io.swagger.oas.inflector.examples.models; 18 | 19 | public abstract class AbstractExample implements Example { 20 | private String name = null; 21 | private String namespace = null; 22 | private String prefix = null; 23 | private Boolean attribute = false; 24 | private Boolean wrapped = false; 25 | private String wrappedName = null; 26 | private String typeName; 27 | 28 | public String getTypeName() { 29 | return typeName; 30 | } 31 | public void setTypeName(String typeName) { 32 | this.typeName = typeName; 33 | } 34 | 35 | public String getName() { 36 | return name; 37 | } 38 | 39 | public void setName(String name) { 40 | this.name = name; 41 | } 42 | 43 | public String getNamespace() { 44 | return namespace; 45 | } 46 | 47 | public void setNamespace(String namespace) { 48 | this.namespace = namespace; 49 | } 50 | 51 | public String getPrefix() { 52 | return prefix; 53 | } 54 | 55 | public void setPrefix(String prefix) { 56 | this.prefix = prefix; 57 | } 58 | 59 | public Boolean getAttribute() { 60 | return attribute; 61 | } 62 | 63 | public void setAttribute(Boolean attribute) { 64 | this.attribute = attribute; 65 | } 66 | 67 | public Boolean getWrapped() { 68 | return wrapped; 69 | } 70 | 71 | public void setWrapped(Boolean wrapped) { 72 | this.wrapped = wrapped; 73 | } 74 | 75 | public String getWrappedName() { 76 | return wrappedName; 77 | } 78 | 79 | public void setWrappedName(String wrappedName) { 80 | this.wrappedName = wrappedName; 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /src/main/java/io/swagger/oas/inflector/examples/models/ArrayExample.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 SmartBear Software 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package io.swagger.oas.inflector.examples.models; 18 | 19 | import com.fasterxml.jackson.databind.annotation.JsonDeserialize; 20 | import io.swagger.oas.inflector.processors.JsonExampleDeserializer; 21 | 22 | import java.util.ArrayList; 23 | import java.util.List; 24 | 25 | @JsonDeserialize(using = JsonExampleDeserializer.class) 26 | public class ArrayExample extends AbstractExample { 27 | List values = null; 28 | 29 | public ArrayExample() { 30 | super.setTypeName("array"); 31 | } 32 | 33 | public void add(Example value) { 34 | if (values == null) { 35 | values = new ArrayList<>(); 36 | } 37 | values.add(value); 38 | } 39 | 40 | public String asString() { 41 | StringBuilder builder = new StringBuilder(); 42 | builder.append("["); 43 | if(values != null) { 44 | for(int i = 0; i < values.size(); i++) { 45 | Example example = values.get(i); 46 | builder.append(example.asString()); 47 | if(i > 0) { 48 | builder.append(","); 49 | } 50 | } 51 | } 52 | builder.append("]"); 53 | 54 | return builder.toString(); 55 | } 56 | 57 | public List getItems() { 58 | if (values == null) { 59 | return new ArrayList<>(); 60 | } 61 | return values; 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/main/java/io/swagger/oas/inflector/examples/models/BigIntegerExample.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 SmartBear Software 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package io.swagger.oas.inflector.examples.models; 18 | 19 | import java.math.BigInteger; 20 | 21 | public class BigIntegerExample extends AbstractExample { 22 | private BigInteger value; 23 | 24 | public BigIntegerExample() { 25 | super.setTypeName("biginteger"); 26 | } 27 | 28 | public BigIntegerExample(BigInteger value) { 29 | this(); 30 | this.value = value; 31 | } 32 | 33 | public String asString() { 34 | return value.toString(); 35 | } 36 | 37 | public BigInteger getValue() { 38 | return value != null ? value : new BigInteger("1180591620717411303424"); 39 | } 40 | 41 | public void setValue(BigInteger value) { 42 | this.value = value; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/io/swagger/oas/inflector/examples/models/BooleanExample.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 SmartBear Software 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package io.swagger.oas.inflector.examples.models; 18 | 19 | public class BooleanExample extends AbstractExample { 20 | private Boolean value; 21 | 22 | public BooleanExample() { 23 | super.setTypeName("boolean"); 24 | } 25 | 26 | public BooleanExample(boolean value) { 27 | this(); 28 | this.value = value; 29 | } 30 | 31 | public String asString() { 32 | return getValue().toString(); 33 | } 34 | 35 | public Boolean getValue() { 36 | return value != null ? value : false; 37 | } 38 | 39 | public void setValue(Boolean value) { 40 | this.value = value; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/io/swagger/oas/inflector/examples/models/DecimalExample.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 SmartBear Software 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package io.swagger.oas.inflector.examples.models; 18 | 19 | import java.math.BigDecimal; 20 | 21 | public class DecimalExample extends AbstractExample { 22 | private BigDecimal value; 23 | 24 | public DecimalExample() { 25 | super.setTypeName("decimal"); 26 | } 27 | public DecimalExample(BigDecimal value) { 28 | this(); 29 | this.value = value; 30 | } 31 | 32 | public String asString() { 33 | return value.toPlainString(); 34 | } 35 | 36 | public BigDecimal getValue() { 37 | return value != null ? value : new BigDecimal(1.23); 38 | } 39 | 40 | public void setValue(BigDecimal value) { 41 | this.value = value; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/io/swagger/oas/inflector/examples/models/DoubleExample.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 SmartBear Software 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package io.swagger.oas.inflector.examples.models; 18 | 19 | public class DoubleExample extends AbstractExample { 20 | private Double value; 21 | 22 | public DoubleExample() { 23 | super.setTypeName("double"); 24 | } 25 | public DoubleExample(double value) { 26 | this(); 27 | this.value = value; 28 | } 29 | 30 | public String asString() { 31 | return String.valueOf(getValue()); 32 | } 33 | 34 | public Double getValue() { 35 | return value != null ? value : 4.56; 36 | } 37 | 38 | public void setValue(Double value) { 39 | this.value = value; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/io/swagger/oas/inflector/examples/models/Example.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 SmartBear Software 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package io.swagger.oas.inflector.examples.models; 18 | 19 | import javax.xml.bind.annotation.XmlAttribute; 20 | 21 | public interface Example { 22 | String getName(); 23 | void setName(String name); 24 | 25 | @XmlAttribute 26 | String getNamespace(); 27 | void setNamespace(String namespace); 28 | 29 | @XmlAttribute 30 | String getPrefix(); 31 | void setPrefix(String prefix); 32 | 33 | Boolean getAttribute(); 34 | void setAttribute(Boolean attribute); 35 | 36 | Boolean getWrapped(); 37 | void setWrapped(Boolean wrapped); 38 | 39 | String getWrappedName(); 40 | void setWrappedName(String name); 41 | 42 | String asString(); 43 | String getTypeName(); 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/io/swagger/oas/inflector/examples/models/FloatExample.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 SmartBear Software 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package io.swagger.oas.inflector.examples.models; 18 | 19 | public class FloatExample extends AbstractExample { 20 | private Float value; 21 | 22 | public FloatExample() { 23 | super.setTypeName("float"); 24 | } 25 | public FloatExample(float value) { 26 | this(); 27 | this.value = value; 28 | } 29 | 30 | public String asString() { 31 | return String.valueOf(getValue()); 32 | } 33 | 34 | public Float getValue() { 35 | return value != null ? value : 3.14f; 36 | } 37 | 38 | public void setValue(Float value) { 39 | this.value = value; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/io/swagger/oas/inflector/examples/models/IntegerExample.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 SmartBear Software 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package io.swagger.oas.inflector.examples.models; 18 | 19 | public class IntegerExample extends AbstractExample { 20 | private Integer value; 21 | 22 | public IntegerExample() { 23 | super.setTypeName("integer"); 24 | } 25 | public IntegerExample(int value) { 26 | this(); 27 | this.value = value; 28 | } 29 | 30 | public Integer asInt() { 31 | return value; 32 | } 33 | 34 | public String asString() { 35 | return String.valueOf(getValue()); 36 | } 37 | 38 | public Integer getValue() { 39 | return value != null ? value : 12; 40 | } 41 | 42 | public void setValue(Integer value) { 43 | this.value = value; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/io/swagger/oas/inflector/examples/models/LongExample.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 SmartBear Software 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package io.swagger.oas.inflector.examples.models; 18 | 19 | public class LongExample extends AbstractExample { 20 | private Long value; 21 | 22 | public LongExample() { 23 | super.setTypeName("long"); 24 | } 25 | public LongExample(long value) { 26 | this(); 27 | this.value = value; 28 | } 29 | 30 | public String asString() { 31 | return String.valueOf(getValue()); 32 | } 33 | 34 | public Long getValue() { 35 | return value != null ? value : 12345; 36 | } 37 | 38 | public void setValue(Long value) { 39 | this.value = value; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/io/swagger/oas/inflector/examples/models/NullExample.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 SmartBear Software 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package io.swagger.oas.inflector.examples.models; 18 | 19 | 20 | public class NullExample extends AbstractExample { 21 | 22 | public NullExample() { 23 | super.setTypeName("string"); 24 | } 25 | 26 | public String asString() { 27 | return null; 28 | } 29 | 30 | public Object getValue() { 31 | return null; 32 | } 33 | 34 | public void setValue(Object value) { 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/io/swagger/oas/inflector/examples/models/ObjectExample.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 SmartBear Software 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package io.swagger.oas.inflector.examples.models; 18 | 19 | import com.fasterxml.jackson.databind.annotation.JsonDeserialize; 20 | import io.swagger.oas.inflector.processors.JsonExampleDeserializer; 21 | 22 | import java.util.HashSet; 23 | import java.util.LinkedHashMap; 24 | import java.util.Map; 25 | import java.util.Set; 26 | 27 | @JsonDeserialize(using = JsonExampleDeserializer.class) 28 | public class ObjectExample extends AbstractExample { 29 | private Map values; 30 | 31 | public ObjectExample() { 32 | super.setTypeName("object"); 33 | } 34 | 35 | public void put(String key, Example value) { 36 | if (values == null) { 37 | values = new LinkedHashMap<>(); 38 | } 39 | values.put(key, value); 40 | } 41 | 42 | public void putAll(Map values) { 43 | for(String key : values.keySet()) { 44 | this.put(key, values.get(key)); 45 | } 46 | } 47 | 48 | public Set keySet() { 49 | if (values == null) { 50 | return new HashSet<>(); 51 | } 52 | return values.keySet(); 53 | } 54 | 55 | public Object get(String key) { 56 | if (values != null) { 57 | return values.get(key); 58 | } 59 | return null; 60 | } 61 | 62 | public String asString() { 63 | if (values == null) { 64 | return null; 65 | } 66 | return "NOT IMPLEMENTED"; 67 | } 68 | 69 | public Map getValues() { 70 | return values; 71 | } 72 | 73 | public void setValues(Map values) { 74 | this.values = values; 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /src/main/java/io/swagger/oas/inflector/examples/models/StringExample.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 SmartBear Software 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package io.swagger.oas.inflector.examples.models; 18 | 19 | import com.fasterxml.jackson.databind.annotation.JsonDeserialize; 20 | import io.swagger.oas.inflector.processors.JsonExampleDeserializer; 21 | 22 | @JsonDeserialize(using = JsonExampleDeserializer.class) 23 | public class StringExample extends AbstractExample { 24 | private String value; 25 | 26 | public StringExample() { 27 | super.setTypeName("string"); 28 | } 29 | public StringExample(String value) { 30 | this(); 31 | this.value = value; 32 | } 33 | 34 | public String textValue() { 35 | return value; 36 | } 37 | 38 | public String asString() { 39 | return value != null ? value : "null"; 40 | } 41 | 42 | public String getValue() { 43 | return value; 44 | } 45 | 46 | public void setValue(String value) { 47 | this.value = value; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/io/swagger/oas/inflector/models/ApiError.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 SmartBear Software 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package io.swagger.oas.inflector.models; 18 | 19 | public class ApiError { 20 | private int code; 21 | private String message; 22 | 23 | public ApiError code(int code) { 24 | this.code = code; 25 | return this; 26 | } 27 | 28 | public ApiError message(String message) { 29 | this.message = message; 30 | return this; 31 | } 32 | 33 | public int getCode() { 34 | return code; 35 | } 36 | 37 | public void setCode(int code) { 38 | this.code = code; 39 | } 40 | 41 | public String getMessage() { 42 | return message; 43 | } 44 | 45 | public void setMessage(String message) { 46 | this.message = message; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/io/swagger/oas/inflector/models/ResponseContext.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 SmartBear Software 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package io.swagger.oas.inflector.models; 18 | 19 | import javax.ws.rs.core.MediaType; 20 | import javax.ws.rs.core.MultivaluedHashMap; 21 | import javax.ws.rs.core.MultivaluedMap; 22 | import javax.ws.rs.core.NewCookie; 23 | import javax.ws.rs.core.Response.Status; 24 | import java.util.ArrayList; 25 | import java.util.List; 26 | 27 | public class ResponseContext { 28 | private MultivaluedMap headers = new MultivaluedHashMap(); 29 | private List cookies = new ArrayList<>(); 30 | private MediaType contentType; 31 | private int status = Status.OK.getStatusCode(); 32 | private Object entity; 33 | 34 | public ResponseContext header(String key, String value) { 35 | this.headers.add(key, value); 36 | return this; 37 | } 38 | 39 | public ResponseContext cookie(NewCookie cookie) { 40 | this.cookies.add(cookie); 41 | return this; 42 | } 43 | 44 | public ResponseContext contentType(MediaType contentType) { 45 | this.contentType = contentType; 46 | return this; 47 | } 48 | 49 | public ResponseContext contentType(String contentType) { 50 | this.contentType = MediaType.valueOf(contentType); 51 | return this; 52 | } 53 | 54 | public ResponseContext status(Status status) { 55 | this.status = status.getStatusCode(); 56 | return this; 57 | } 58 | 59 | public ResponseContext status(int status) { 60 | this.status = status; 61 | return this; 62 | } 63 | 64 | public ResponseContext entity(Object entity) { 65 | this.entity = entity; 66 | return this; 67 | } 68 | 69 | public MultivaluedMap getHeaders() { 70 | return headers; 71 | } 72 | 73 | public void setHeaders(MultivaluedMap headers) { 74 | this.headers = headers; 75 | } 76 | 77 | public List getCookies() { 78 | return cookies; 79 | } 80 | 81 | public void setCookies(List cookies) { 82 | this.cookies = cookies; 83 | } 84 | 85 | public MediaType getContentType() { 86 | return contentType; 87 | } 88 | 89 | public void setContentType(MediaType contentType) { 90 | this.contentType = contentType; 91 | } 92 | 93 | public int getStatus() { 94 | return status; 95 | } 96 | 97 | public void setStatus(int status) { 98 | this.status = status; 99 | } 100 | 101 | public Object getEntity() { 102 | return entity; 103 | } 104 | 105 | public void setEntity(Object entity) { 106 | this.entity = entity; 107 | } 108 | } 109 | -------------------------------------------------------------------------------- /src/main/java/io/swagger/oas/inflector/processors/AbstractExampleProvider.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 SmartBear Software 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package io.swagger.oas.inflector.processors; 18 | 19 | import io.swagger.oas.inflector.examples.models.Example; 20 | import io.swagger.v3.core.util.Json; 21 | 22 | import java.lang.annotation.Annotation; 23 | import java.lang.reflect.Type; 24 | 25 | import javax.ws.rs.Produces; 26 | import javax.ws.rs.core.MediaType; 27 | import javax.ws.rs.ext.MessageBodyWriter; 28 | import javax.ws.rs.ext.Provider; 29 | 30 | import org.slf4j.Logger; 31 | import org.slf4j.LoggerFactory; 32 | 33 | import com.fasterxml.jackson.databind.module.SimpleModule; 34 | 35 | @Provider 36 | @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, "application/yaml"}) 37 | public abstract class AbstractExampleProvider implements MessageBodyWriter { 38 | static boolean prettyPrint = false; 39 | Logger LOGGER = LoggerFactory.getLogger(AbstractExampleProvider.class); 40 | 41 | static { 42 | SimpleModule simpleModule = new SimpleModule(); 43 | simpleModule.addSerializer(new JsonNodeExampleSerializer()); 44 | Json.mapper().registerModule(simpleModule); 45 | } 46 | 47 | public static void setPrettyPrint(boolean shouldPrettyPrint) { 48 | prettyPrint = shouldPrettyPrint; 49 | } 50 | 51 | @Override 52 | public boolean isWriteable(Class type, Type genericType, Annotation[] annotations, 53 | MediaType mediaType) { 54 | return Example.class.isAssignableFrom(type); 55 | } 56 | 57 | @Override 58 | public long getSize(Example data, Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { 59 | return -1; 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/main/java/io/swagger/oas/inflector/processors/EntityProcessor.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 SmartBear Software 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package io.swagger.oas.inflector.processors; 18 | 19 | import com.fasterxml.jackson.databind.JavaType; 20 | import io.swagger.oas.inflector.controllers.OpenAPIOperationController; 21 | import io.swagger.oas.inflector.converters.ConversionException; 22 | import io.swagger.v3.oas.models.parameters.RequestBody; 23 | 24 | import javax.ws.rs.core.MediaType; 25 | import java.io.InputStream; 26 | import java.util.List; 27 | 28 | public interface EntityProcessor { 29 | boolean supports(MediaType mediaType); 30 | 31 | List getSupportedMediaTypes(); 32 | 33 | void enableType(MediaType type); 34 | 35 | Object process(MediaType mediaType, InputStream entityStream, Class cls) throws ConversionException; 36 | 37 | Object process(MediaType mediaType, InputStream entityStream, Class cls, OpenAPIOperationController controller) throws ConversionException; 38 | 39 | Object process(MediaType mediaType, InputStream entityStream, JavaType javaType); 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/io/swagger/oas/inflector/processors/EntityProcessorFactory.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 SmartBear Software 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package io.swagger.oas.inflector.processors; 18 | 19 | import io.swagger.oas.inflector.controllers.OpenAPIOperationController; 20 | import io.swagger.oas.inflector.converters.ConversionException; 21 | import io.swagger.v3.oas.models.parameters.RequestBody; 22 | import org.slf4j.Logger; 23 | import org.slf4j.LoggerFactory; 24 | 25 | import javax.ws.rs.core.MediaType; 26 | import java.io.InputStream; 27 | import java.util.ArrayList; 28 | import java.util.List; 29 | 30 | public class EntityProcessorFactory { 31 | private static final Logger LOGGER = LoggerFactory.getLogger(EntityProcessorFactory.class); 32 | 33 | private static List PROCESSORS = new ArrayList(); 34 | 35 | static { 36 | // handles yaml, json, xml 37 | PROCESSORS.add(new JacksonProcessor()); 38 | PROCESSORS.add(new BinaryProcessor()); 39 | PROCESSORS.add(new PlainProcessor()); 40 | } 41 | 42 | public static void addProcessor(Class cls, MediaType type) { 43 | for(EntityProcessor entityProcessor : PROCESSORS) { 44 | if(entityProcessor.getClass().equals(cls)) { 45 | entityProcessor.enableType(type); 46 | return; 47 | } 48 | } 49 | try { 50 | EntityProcessor processor = (EntityProcessor) cls.newInstance(); 51 | PROCESSORS.add(processor); 52 | processor.enableType(type); 53 | } 54 | catch (Exception e) { 55 | LOGGER.debug("unable to add processor " + cls.getName()); 56 | } 57 | } 58 | 59 | public static Object readValue(MediaType mediaType, InputStream entityStream, Class class1) throws ConversionException { 60 | for (EntityProcessor p : getProcessors()) { 61 | if (p.supports(mediaType)) { 62 | return p.process(mediaType, entityStream, class1); 63 | } 64 | } 65 | return null; 66 | } 67 | 68 | public static Object readValue(MediaType mediaType, InputStream entityStream, Class class1, OpenAPIOperationController controller) throws ConversionException { 69 | for (EntityProcessor p : getProcessors()) { 70 | if (p.supports(mediaType)) { 71 | return p.process(mediaType, entityStream, class1, controller); 72 | } 73 | } 74 | return null; 75 | } 76 | 77 | public static List getProcessors() { 78 | return PROCESSORS; 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /src/main/java/io/swagger/oas/inflector/processors/JsonExampleProvider.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 SmartBear Software 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package io.swagger.oas.inflector.processors; 18 | 19 | import io.swagger.oas.inflector.examples.models.Example; 20 | import io.swagger.v3.core.util.Json; 21 | 22 | import javax.ws.rs.Produces; 23 | import javax.ws.rs.core.MediaType; 24 | import javax.ws.rs.core.MultivaluedMap; 25 | import javax.ws.rs.ext.MessageBodyWriter; 26 | import javax.ws.rs.ext.Provider; 27 | import java.io.IOException; 28 | import java.io.OutputStream; 29 | import java.lang.annotation.Annotation; 30 | import java.lang.reflect.Type; 31 | 32 | @Provider 33 | @Produces({MediaType.APPLICATION_JSON}) 34 | public class JsonExampleProvider extends AbstractExampleProvider implements MessageBodyWriter { 35 | @Override 36 | public void writeTo(Example data, 37 | Class type, 38 | Type genericType, 39 | Annotation[] annotations, 40 | MediaType mediaType, 41 | MultivaluedMap headers, 42 | OutputStream out) throws IOException { 43 | if (mediaType.isCompatible(MediaType.APPLICATION_JSON_TYPE)) { 44 | if (prettyPrint) { 45 | out.write(Json.pretty().writeValueAsString(data).getBytes("utf-8")); 46 | } else { 47 | out.write(Json.mapper().writeValueAsString(data).getBytes("utf-8")); 48 | } 49 | } 50 | } 51 | } 52 | 53 | -------------------------------------------------------------------------------- /src/main/java/io/swagger/oas/inflector/processors/JsonProvider.java: -------------------------------------------------------------------------------- 1 | package io.swagger.oas.inflector.processors; 2 | 3 | import com.fasterxml.jackson.databind.ObjectMapper; 4 | import com.fasterxml.jackson.databind.SerializationFeature; 5 | import io.swagger.v3.core.util.Json; 6 | 7 | import javax.ws.rs.ext.ContextResolver; 8 | import javax.ws.rs.ext.Provider; 9 | 10 | @Provider 11 | public class JsonProvider implements ContextResolver { 12 | private final ObjectMapper objectMapper; 13 | private boolean prettyPrint; 14 | 15 | public JsonProvider() { 16 | objectMapper = Json.mapper(); 17 | } 18 | 19 | public JsonProvider(boolean prettyPrint) { 20 | this(); 21 | this.prettyPrint = prettyPrint; 22 | } 23 | 24 | @Override 25 | public ObjectMapper getContext(Class type) { 26 | if(this.prettyPrint) { 27 | objectMapper.enable(SerializationFeature.INDENT_OUTPUT); 28 | } 29 | 30 | return objectMapper; 31 | } 32 | } -------------------------------------------------------------------------------- /src/main/java/io/swagger/oas/inflector/processors/PlainExampleProvider.java: -------------------------------------------------------------------------------- 1 | package io.swagger.oas.inflector.processors; 2 | 3 | 4 | import io.swagger.oas.inflector.examples.models.Example; 5 | 6 | import javax.ws.rs.Produces; 7 | import javax.ws.rs.core.MediaType; 8 | import javax.ws.rs.core.MultivaluedMap; 9 | import javax.ws.rs.ext.MessageBodyWriter; 10 | import javax.ws.rs.ext.Provider; 11 | import java.io.IOException; 12 | import java.io.OutputStream; 13 | import java.lang.annotation.Annotation; 14 | import java.lang.reflect.Type; 15 | 16 | 17 | 18 | @Provider 19 | @Produces({MediaType.TEXT_PLAIN}) 20 | public class PlainExampleProvider extends AbstractExampleProvider implements MessageBodyWriter { 21 | @Override 22 | public void writeTo(Example data, 23 | Class type, 24 | Type genericType, 25 | Annotation[] annotations, 26 | MediaType mediaType, 27 | MultivaluedMap headers, 28 | OutputStream out) throws IOException { 29 | if (mediaType.isCompatible(MediaType.TEXT_PLAIN_TYPE)) { 30 | out.write(data.asString().getBytes("utf-8")); 31 | } 32 | } 33 | } 34 | 35 | -------------------------------------------------------------------------------- /src/main/java/io/swagger/oas/inflector/processors/PlainProcessor.java: -------------------------------------------------------------------------------- 1 | package io.swagger.oas.inflector.processors; 2 | 3 | import com.fasterxml.jackson.databind.JavaType; 4 | import io.swagger.oas.inflector.controllers.OpenAPIOperationController; 5 | import io.swagger.oas.inflector.converters.ConversionException; 6 | import io.swagger.oas.inflector.validators.ValidationError; 7 | import io.swagger.oas.inflector.validators.ValidationMessage; 8 | import org.apache.commons.io.IOUtils; 9 | import org.slf4j.Logger; 10 | import org.slf4j.LoggerFactory; 11 | 12 | import javax.ws.rs.core.MediaType; 13 | import java.io.IOException; 14 | import java.io.InputStream; 15 | import java.util.ArrayList; 16 | import java.util.List; 17 | 18 | public class PlainProcessor implements EntityProcessor { 19 | private static final Logger LOGGER = LoggerFactory.getLogger(PlainProcessor.class); 20 | private static List SUPPORTED_TYPES = new ArrayList<>(); 21 | 22 | static { 23 | SUPPORTED_TYPES.add(MediaType.TEXT_PLAIN_TYPE); 24 | } 25 | 26 | @Override 27 | public List getSupportedMediaTypes() { 28 | return new ArrayList(SUPPORTED_TYPES); 29 | } 30 | 31 | @Override 32 | public void enableType(MediaType type) { 33 | MediaType t = type; 34 | if(t != null) { 35 | if(!SUPPORTED_TYPES.contains(t)) { 36 | SUPPORTED_TYPES.add(type); 37 | } 38 | } 39 | } 40 | 41 | @Override 42 | public boolean supports(MediaType mediaType) { 43 | return SUPPORTED_TYPES.contains(mediaType); 44 | } 45 | 46 | @Override 47 | public Object process(MediaType mediaType, InputStream entityStream, Class cls, OpenAPIOperationController controller) throws ConversionException { 48 | return process(mediaType,entityStream,cls); 49 | } 50 | 51 | @Override 52 | public Object process(MediaType mediaType, InputStream entityStream, Class cls) throws ConversionException { 53 | try { 54 | return IOUtils.toString(entityStream); 55 | } catch (IOException e) { 56 | LOGGER.trace("unable to extract entity from content-type `" + mediaType + "` to String", e); 57 | throw new ConversionException() 58 | .message(new ValidationMessage() 59 | .code(ValidationError.UNACCEPTABLE_VALUE) 60 | .message("unable to convert input to " + cls.getCanonicalName())); 61 | } 62 | } 63 | 64 | @Override 65 | public Object process(MediaType mediaType, InputStream entityStream, JavaType javaType) { 66 | try { 67 | return IOUtils.toString(entityStream); 68 | } catch (IOException e) { 69 | LOGGER.error("unable to extract entity from content-type `" + mediaType + "` to String", e); 70 | } 71 | return null; 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /src/main/java/io/swagger/oas/inflector/processors/XMLExampleProvider.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 SmartBear Software 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package io.swagger.oas.inflector.processors; 18 | 19 | import io.swagger.oas.inflector.examples.XmlExampleSerializer; 20 | import io.swagger.oas.inflector.examples.models.Example; 21 | 22 | import javax.ws.rs.Produces; 23 | import javax.ws.rs.core.MediaType; 24 | import javax.ws.rs.core.MultivaluedMap; 25 | import javax.ws.rs.ext.MessageBodyWriter; 26 | import javax.ws.rs.ext.Provider; 27 | import java.io.IOException; 28 | import java.io.OutputStream; 29 | import java.lang.annotation.Annotation; 30 | import java.lang.reflect.Type; 31 | import java.util.List; 32 | 33 | @Provider 34 | @Produces({MediaType.APPLICATION_XML}) 35 | public class XMLExampleProvider extends AbstractExampleProvider implements MessageBodyWriter { 36 | 37 | @Override 38 | public boolean isWriteable(Class type, Type genericType, 39 | Annotation[] annotations, MediaType mediaType) { 40 | List processors = EntityProcessorFactory.getProcessors(); 41 | for(EntityProcessor p : processors) { 42 | if (p.supports(mediaType)) { 43 | return true; 44 | } 45 | } 46 | return false; 47 | } 48 | 49 | @Override 50 | public void writeTo(Example data, 51 | Class type, 52 | Type genericType, 53 | Annotation[] annotations, 54 | MediaType mediaType, 55 | MultivaluedMap headers, 56 | OutputStream out) throws IOException { 57 | if (mediaType.isCompatible(MediaType.APPLICATION_XML_TYPE)) { 58 | out.write(new XmlExampleSerializer().serialize(data).getBytes("utf-8")); 59 | } 60 | } 61 | } 62 | 63 | -------------------------------------------------------------------------------- /src/main/java/io/swagger/oas/inflector/processors/YamlExampleProvider.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 SmartBear Software 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package io.swagger.oas.inflector.processors; 18 | 19 | import io.swagger.oas.inflector.examples.models.Example; 20 | import io.swagger.v3.core.util.Yaml; 21 | 22 | import java.io.IOException; 23 | import java.io.OutputStream; 24 | import java.lang.annotation.Annotation; 25 | import java.lang.reflect.Type; 26 | 27 | import javax.ws.rs.Produces; 28 | import javax.ws.rs.core.MediaType; 29 | import javax.ws.rs.core.MultivaluedMap; 30 | import javax.ws.rs.ext.MessageBodyWriter; 31 | import javax.ws.rs.ext.Provider; 32 | 33 | @Provider 34 | @Produces({"application/yaml"}) 35 | public class YamlExampleProvider extends AbstractExampleProvider implements MessageBodyWriter { 36 | @Override 37 | public void writeTo(Example data, 38 | Class type, 39 | Type genericType, 40 | Annotation[] annotations, 41 | MediaType mediaType, 42 | MultivaluedMap headers, 43 | OutputStream out) throws IOException { 44 | if (mediaType.toString().startsWith("application/yaml")) { 45 | headers.remove("Content-Type"); 46 | headers.add("Content-Type", "application/yaml"); 47 | out.write(Yaml.mapper().writeValueAsString(data).getBytes("utf-8")); 48 | } 49 | } 50 | } 51 | 52 | -------------------------------------------------------------------------------- /src/main/java/io/swagger/oas/inflector/schema/SchemaValidator.java: -------------------------------------------------------------------------------- 1 | package io.swagger.oas.inflector.schema; 2 | 3 | import com.fasterxml.jackson.databind.JsonNode; 4 | import com.github.fge.jsonschema.core.exceptions.ProcessingException; 5 | import com.github.fge.jsonschema.core.report.ProcessingReport; 6 | import com.github.fge.jsonschema.main.JsonSchema; 7 | import com.github.fge.jsonschema.main.JsonSchemaFactory; 8 | import io.swagger.v3.core.util.Json; 9 | import org.slf4j.Logger; 10 | import org.slf4j.LoggerFactory; 11 | 12 | import java.io.IOException; 13 | import java.util.HashMap; 14 | import java.util.Map; 15 | 16 | public class SchemaValidator { 17 | static Map SCHEMA_CACHE = new HashMap(); 18 | private static final Logger LOGGER = LoggerFactory.getLogger(SchemaValidator.class); 19 | 20 | public enum Direction{ 21 | INPUT, 22 | OUTPUT 23 | } 24 | 25 | public static boolean validate(Object argument, String schema, Direction direction) { 26 | try { 27 | JsonNode schemaObject = Json.mapper().readTree(schema); 28 | JsonSchemaFactory factory = JsonSchemaFactory.byDefault(); 29 | JsonNode content = Json.mapper().convertValue(argument, JsonNode.class); 30 | com.github.fge.jsonschema.main.JsonSchema jsonSchema = factory.getJsonSchema(schemaObject); 31 | 32 | ProcessingReport report = jsonSchema.validate(content); 33 | if(!report.isSuccess()) { 34 | if(direction.equals(Direction.INPUT)) { 35 | LOGGER.warn("input: " + content.toString() + "\n" + "does not match schema: \n" + schema); 36 | } 37 | else { 38 | LOGGER.warn("response: " + content.toString() + "\n" + "does not match schema: \n" + schema); 39 | } 40 | } 41 | return report.isSuccess(); 42 | } 43 | catch (Exception e) { 44 | LOGGER.error("can't validate model against schema", e); 45 | } 46 | 47 | return true; 48 | } 49 | 50 | public static com.github.fge.jsonschema.main.JsonSchema getValidationSchema(String schema) throws IOException, ProcessingException { 51 | schema = schema.trim(); 52 | 53 | JsonSchema output = SCHEMA_CACHE.get(schema); 54 | 55 | if(output == null) { 56 | JsonNode schemaObject = Json.mapper().readTree(schema); 57 | JsonSchemaFactory factory = JsonSchemaFactory.byDefault(); 58 | com.github.fge.jsonschema.main.JsonSchema jsonSchema = factory.getJsonSchema(schemaObject); 59 | SCHEMA_CACHE.put(schema, jsonSchema); 60 | output = jsonSchema; 61 | } 62 | return output; 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/main/java/io/swagger/oas/inflector/utils/ApiErrorUtils.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 SmartBear Software 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package io.swagger.oas.inflector.utils; 18 | 19 | import io.swagger.oas.inflector.models.ApiError; 20 | 21 | import javax.ws.rs.core.Response; 22 | import java.util.concurrent.ThreadLocalRandom; 23 | 24 | public class ApiErrorUtils { 25 | 26 | public static ApiError createInternalError() { 27 | final String message = String.format("There was an error processing your request." 28 | + " It has been logged (ID: %016x)", ThreadLocalRandom.current().nextLong()); 29 | return new ApiError().code(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()) 30 | .message(message); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/io/swagger/oas/inflector/utils/ApiException.java: -------------------------------------------------------------------------------- 1 | package io.swagger.oas.inflector.utils; 2 | 3 | import io.swagger.oas.inflector.models.ApiError; 4 | 5 | public class ApiException extends RuntimeException { 6 | private static final long serialVersionUID = -753474495606091043L; 7 | 8 | private ApiError error; 9 | 10 | public ApiException() { 11 | } 12 | 13 | public ApiException(ApiError error) { 14 | super(error.getMessage()); 15 | this.error = error; 16 | } 17 | 18 | public ApiException(ApiError error, Throwable cause) { 19 | super(error.getMessage(), cause); 20 | this.error = error; 21 | } 22 | 23 | public ApiError getError() { 24 | return error; 25 | } 26 | 27 | public void setError(ApiError error) { 28 | this.error = error; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/io/swagger/oas/inflector/utils/CORSFilter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 SmartBear Software 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package io.swagger.oas.inflector.utils; 18 | 19 | import javax.servlet.FilterChain; 20 | import javax.servlet.FilterConfig; 21 | import javax.servlet.ServletException; 22 | import javax.servlet.ServletRequest; 23 | import javax.servlet.ServletResponse; 24 | import javax.servlet.http.HttpServletResponse; 25 | import java.io.IOException; 26 | 27 | public class CORSFilter implements javax.servlet.Filter { 28 | @Override 29 | public void doFilter(ServletRequest request, ServletResponse response, 30 | FilterChain chain) throws IOException, ServletException { 31 | HttpServletResponse res = (HttpServletResponse) response; 32 | res.addHeader("Access-Control-Allow-Origin", "*"); 33 | res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT"); 34 | res.addHeader("Access-Control-Allow-Headers", "Content-Type, api_key, Authorization"); 35 | res.addHeader("Access-Control-Expose-Headers", "Content-Disposition"); 36 | chain.doFilter(request, response); 37 | } 38 | 39 | @Override 40 | public void destroy() { 41 | } 42 | 43 | @Override 44 | public void init(FilterConfig filterConfig) throws ServletException { 45 | } 46 | } -------------------------------------------------------------------------------- /src/main/java/io/swagger/oas/inflector/utils/ContentTypeSelector.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 SmartBear Software 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package io.swagger.oas.inflector.utils; 18 | 19 | import java.util.List; 20 | 21 | import javax.ws.rs.core.MediaType; 22 | import javax.ws.rs.core.Response; 23 | 24 | public interface ContentTypeSelector { 25 | 26 | boolean apply(List acceptable, Response.ResponseBuilder builder); 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/io/swagger/oas/inflector/utils/DefaultContentTypeProvider.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 SmartBear Software 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package io.swagger.oas.inflector.utils; 18 | 19 | import javax.ws.rs.core.MediaType; 20 | import javax.ws.rs.ext.ContextResolver; 21 | 22 | public class DefaultContentTypeProvider implements ContextResolver { 23 | private final ContentTypeSelector selector; 24 | 25 | public DefaultContentTypeProvider(MediaType type) { 26 | this(new DefaultContentTypeSelector(type)); 27 | } 28 | 29 | public DefaultContentTypeProvider(ContentTypeSelector selector) { 30 | this.selector = selector; 31 | } 32 | 33 | @Override 34 | public ContentTypeSelector getContext(Class type) { 35 | return selector; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/io/swagger/oas/inflector/utils/DefaultContentTypeSelector.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2006 SmartBear Software 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package io.swagger.oas.inflector.utils; 18 | 19 | import io.swagger.oas.inflector.CustomMediaTypes; 20 | 21 | import javax.ws.rs.core.MediaType; 22 | import javax.ws.rs.core.Response; 23 | import java.util.Arrays; 24 | import java.util.Collections; 25 | import java.util.List; 26 | import java.util.Set; 27 | import java.util.TreeSet; 28 | 29 | public class DefaultContentTypeSelector implements ContentTypeSelector { 30 | private final MediaType type; 31 | private final Set overriden; 32 | 33 | public DefaultContentTypeSelector(MediaType type) { 34 | this(type, CustomMediaTypes.APPLICATION_YAML.getSubtype()); 35 | } 36 | 37 | public DefaultContentTypeSelector(MediaType type, String... overriden) { 38 | this.type = type; 39 | final Set tmp = new TreeSet<>(String.CASE_INSENSITIVE_ORDER); 40 | tmp.add(MediaType.MEDIA_TYPE_WILDCARD); 41 | tmp.addAll(Arrays.asList(overriden)); 42 | this.overriden = Collections.unmodifiableSet(tmp); 43 | } 44 | 45 | @Override 46 | public boolean apply(List acceptable, Response.ResponseBuilder builder) { 47 | for (MediaType item : acceptable) { 48 | if (!overriden.contains(item.getSubtype())) { 49 | return false; 50 | } 51 | } 52 | builder.type(type); 53 | return true; 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/main/java/io/swagger/oas/inflector/utils/DefaultSpecFilter.java: -------------------------------------------------------------------------------- 1 | package io.swagger.oas.inflector.utils; 2 | 3 | import io.swagger.oas.inflector.Constants; 4 | import io.swagger.v3.core.model.ApiDescription; 5 | import io.swagger.v3.core.filter.AbstractSpecFilter; 6 | import io.swagger.v3.oas.models.Operation; 7 | import io.swagger.v3.oas.models.media.Schema; 8 | import io.swagger.v3.oas.models.parameters.Parameter; 9 | 10 | 11 | import java.util.List; 12 | import java.util.Map; 13 | import java.util.Optional; 14 | 15 | public class DefaultSpecFilter extends AbstractSpecFilter { 16 | 17 | @Override 18 | public Optional filterOperation(Operation operation, ApiDescription api, Map> params, Map cookies, Map> headers) { 19 | if(operation.getExtensions() != null && operation.getExtensions().containsKey(Constants.X_INFLECTOR_HIDDEN)) { 20 | return Optional.empty(); 21 | } 22 | return Optional.of(operation); 23 | 24 | } 25 | 26 | @Override 27 | public Optional filterParameter(Parameter parameter, Operation operation, ApiDescription api, Map> params, Map cookies, Map> headers) { 28 | if(parameter.getExtensions() != null && parameter.getExtensions().containsKey(Constants.X_INFLECTOR_HIDDEN)) { 29 | return Optional.empty(); 30 | } 31 | return Optional.of(parameter); 32 | 33 | } 34 | 35 | @Override 36 | public Optional filterSchemaProperty(Schema property, Schema model, String propertyName, Map> params, Map cookies, Map> headers) { 37 | if(property.getExtensions() != null && property.getExtensions().containsKey(Constants.X_INFLECTOR_HIDDEN)) { 38 | return Optional.empty(); 39 | } 40 | return Optional.of(property); 41 | } 42 | 43 | @Override 44 | public boolean isRemovingUnreferencedDefinitions() { 45 | return false; 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/io/swagger/oas/inflector/utils/VendorSpecFilter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 SmartBear Software 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package io.swagger.oas.inflector.utils; 18 | 19 | 20 | import io.swagger.oas.inflector.Constants; 21 | import io.swagger.v3.core.filter.OpenAPISpecFilter; 22 | import io.swagger.v3.core.filter.SpecFilter; 23 | import io.swagger.v3.oas.models.Operation; 24 | import io.swagger.v3.oas.models.media.Schema; 25 | 26 | import java.util.List; 27 | import java.util.Map; 28 | 29 | public class VendorSpecFilter extends SpecFilter { 30 | 31 | @Override 32 | public Map filterComponentsSchema(OpenAPISpecFilter filter, Map definitions, 33 | Map> params, Map cookies, Map> headers) { 34 | final Map filteredDefinitions = super.filterComponentsSchema(filter, definitions, params, cookies, 35 | headers); 36 | 37 | if( filteredDefinitions != null ) { 38 | for (Schema model : filteredDefinitions.values()) { 39 | if(model != null && model.getExtensions() != null) { 40 | filterVendorExtensions(model.getExtensions()); 41 | } 42 | } 43 | } 44 | 45 | return filteredDefinitions; 46 | } 47 | 48 | @Override 49 | public Operation filterOperation(OpenAPISpecFilter filter, Operation op, String path, String key , 50 | Map> params, Map cookies, Map> headers) { 51 | final Operation operation = super.filterOperation(filter, op, path, key, params, cookies, headers); 52 | 53 | if(operation != null) { 54 | if (operation.getExtensions() != null) { 55 | filterVendorExtensions(operation.getExtensions()); 56 | } 57 | } 58 | 59 | return operation; 60 | } 61 | 62 | private void filterVendorExtensions(Map vendorExtensions) { 63 | for (Constants.VendorExtension vendorExtension : Constants.VendorExtension.values()) { 64 | vendorExtensions.remove(vendorExtension.getValue()); 65 | } 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/main/java/io/swagger/oas/inflector/validators/DefaultValidator.java: -------------------------------------------------------------------------------- 1 | package io.swagger.oas.inflector.validators; 2 | 3 | 4 | 5 | import io.swagger.v3.oas.models.parameters.Parameter; 6 | import io.swagger.v3.oas.models.parameters.RequestBody; 7 | 8 | import java.util.Iterator; 9 | 10 | public class DefaultValidator implements Validator { 11 | public void validate(Object argument, Parameter parameter, Iterator chain) throws ValidationException { 12 | if (Boolean.TRUE.equals(parameter.getRequired())) { 13 | if(argument == null) { 14 | throw new ValidationException() 15 | .message(new ValidationMessage() 16 | .code(ValidationError.MISSING_REQUIRED) 17 | .message("missing required " + parameter.getIn() + " parameter `" + parameter.getName() + "`")); 18 | } 19 | } 20 | if(chain.hasNext()) { 21 | chain.next().validate(argument, parameter, chain); 22 | return; 23 | } 24 | 25 | return; 26 | } 27 | 28 | public void validate(Object argument, RequestBody body, Iterator chain) throws ValidationException { 29 | if (Boolean.TRUE.equals(body.getRequired())) { 30 | if(argument == null) { 31 | throw new ValidationException() 32 | .message(new ValidationMessage() 33 | .code(ValidationError.MISSING_REQUIRED) 34 | .message("missing required parameter")); 35 | } 36 | } 37 | if(chain.hasNext()) { 38 | chain.next().validate(argument, body, chain); 39 | return; 40 | } 41 | 42 | return; 43 | } 44 | } -------------------------------------------------------------------------------- /src/main/java/io/swagger/oas/inflector/validators/ValidationError.java: -------------------------------------------------------------------------------- 1 | package io.swagger.oas.inflector.validators; 2 | 3 | public enum ValidationError { 4 | MISSING_REQUIRED, 5 | VALUE_UNDER_MINIMUM, 6 | VALUE_OVER_MAXIMUM, 7 | INVALID_FORMAT, 8 | UNACCEPTABLE_VALUE 9 | } -------------------------------------------------------------------------------- /src/main/java/io/swagger/oas/inflector/validators/ValidationException.java: -------------------------------------------------------------------------------- 1 | package io.swagger.oas.inflector.validators; 2 | 3 | public class ValidationException extends Exception { 4 | private static final long serialVersionUID = 1785425151365385107L; 5 | private ValidationMessage message; 6 | 7 | public ValidationException message(ValidationMessage message) { 8 | this.message = message; 9 | return this; 10 | } 11 | 12 | public ValidationMessage getValidationMessage() { 13 | return message; 14 | } 15 | } -------------------------------------------------------------------------------- /src/main/java/io/swagger/oas/inflector/validators/ValidationMessage.java: -------------------------------------------------------------------------------- 1 | package io.swagger.oas.inflector.validators; 2 | 3 | public class ValidationMessage { 4 | private ValidationError code; 5 | private String message; 6 | 7 | public ValidationMessage code(ValidationError code) { 8 | this.code = code; 9 | return this; 10 | } 11 | public ValidationMessage message(String message) { 12 | this.message = message; 13 | return this; 14 | } 15 | 16 | public ValidationError getCode() { 17 | return code; 18 | } 19 | public void setCode(ValidationError code) { 20 | this.code = code; 21 | } 22 | 23 | public String getMessage() { 24 | return message; 25 | } 26 | public void setMessage(String message) { 27 | this.message = message; 28 | } 29 | } -------------------------------------------------------------------------------- /src/main/java/io/swagger/oas/inflector/validators/Validator.java: -------------------------------------------------------------------------------- 1 | package io.swagger.oas.inflector.validators; 2 | 3 | 4 | import io.swagger.v3.oas.models.parameters.Parameter; 5 | import io.swagger.v3.oas.models.parameters.RequestBody; 6 | 7 | import java.util.Iterator; 8 | 9 | public interface Validator { 10 | void validate(Object argument, Parameter parameter, Iterator next) throws ValidationException; 11 | void validate(Object argument, RequestBody body, Iterator next) throws ValidationException; 12 | } -------------------------------------------------------------------------------- /src/main/resources/logback.xml: -------------------------------------------------------------------------------- 1 | 2 | 17 | 18 | 19 | 20 | 21 | %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /src/main/webapp/WEB-INF/web.xml: -------------------------------------------------------------------------------- 1 | 2 | 17 | 18 | 21 | 22 | swagger-inflector 23 | org.glassfish.jersey.servlet.ServletContainer 24 | 25 | javax.ws.rs.Application 26 | io.swagger.oas.inflector.OpenAPIInflector 27 | 28 | 1 29 | 30 | 31 | swagger-inflector 32 | /* 33 | 34 | 35 | CORSFilter 36 | io.swagger.oas.inflector.utils.CORSFilter 37 | 38 | 39 | CORSFilter 40 | /* 41 | 42 | -------------------------------------------------------------------------------- /src/test/config/config1.yaml: -------------------------------------------------------------------------------- 1 | controllerPackage: io.swagger.oas.sample.controllers 2 | modelPackage: io.swagger.oas.sample.models 3 | swaggerUrl: ./src/test/swagger/oas3.yaml 4 | modelMappings: 5 | User: io.swagger.oas.test.models.User 6 | swaggerBase: /swagger 7 | 8 | # allows environment to be develop, staging, production. Production will not start if 9 | # unimplemented models or methods are detected 10 | environment: development 11 | 12 | validatePayloads: true 13 | 14 | # loads all by default, or pick and choose 15 | entityProcessors: 16 | - json 17 | - xml 18 | - yaml 19 | - plain 20 | 21 | # Allows to configure the examples 22 | exampleProcessors: 23 | - sequence 24 | 25 | # loads all by default, or pick and choose 26 | inputValidators: 27 | - requiredFieldValidator 28 | - numericValidator 29 | - stringValidator 30 | 31 | # loads all by default, or pick and choose 32 | inputConverters: 33 | - io.swagger.oas.sample.converters.SampleConverter 34 | - defaultConverter 35 | 36 | swaggerProcessors: 37 | - io.swagger.oas.test.integration.SwaggerListingIT$SwaggerProcessorImpl 38 | -------------------------------------------------------------------------------- /src/test/config/config2.yaml: -------------------------------------------------------------------------------- 1 | controllerPackage: io.swagger.oas.sample.controllers 2 | modelPackage: io.swagger.oas.sample.models 3 | swaggerUrl: ./src/test/swagger/oas3.yaml 4 | modelMappings: 5 | User: io.swagger.oas.test.models.User 6 | swaggerBase: /swagger 7 | 8 | # allows environment to be develop, staging, production. Production will not start if 9 | # unimplemented models or methods are detected 10 | environment: development 11 | 12 | validatePayloads: true 13 | 14 | # loads all by default, or pick and choose 15 | entityProcessors: 16 | - json 17 | - xml 18 | - yaml 19 | - plain 20 | 21 | # Allows to configure the examples 22 | exampleProcessors: 23 | - sequence 24 | 25 | #Allows to configure the exposed spec 26 | exposedSpecOptions: 27 | parseOptions: 28 | resolve: true 29 | resolveFully: true 30 | hideInflectorExtensions: false 31 | 32 | # loads all by default, or pick and choose 33 | inputValidators: 34 | - requiredFieldValidator 35 | - numericValidator 36 | - stringValidator 37 | 38 | # loads all by default, or pick and choose 39 | inputConverters: 40 | - io.swagger.oas.sample.converters.SampleConverter 41 | - defaultConverter 42 | 43 | swaggerProcessors: 44 | - io.swagger.oas.test.integration.SwaggerListingIT$SwaggerProcessorImpl 45 | -------------------------------------------------------------------------------- /src/test/java/io/swagger/oas/inflector/OpenAPIInflectorTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 SmartBear Software 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.swagger.oas.inflector; 17 | 18 | import com.fasterxml.jackson.annotation.JsonInclude; 19 | import com.fasterxml.jackson.databind.ObjectMapper; 20 | import com.fasterxml.jackson.databind.SerializationFeature; 21 | import io.swagger.oas.inflector.config.Configuration; 22 | import io.swagger.oas.inflector.processors.JsonProvider; 23 | import io.swagger.v3.core.util.Json; 24 | import org.testng.annotations.BeforeTest; 25 | import org.testng.annotations.Test; 26 | 27 | import static org.testng.Assert.*; 28 | 29 | 30 | public class OpenAPIInflectorTest { 31 | 32 | Configuration config; 33 | 34 | @BeforeTest 35 | public void before() 36 | { 37 | System.setProperty("config", "src/test/config/config1.yaml"); 38 | config = Configuration.read(); 39 | } 40 | 41 | @Test 42 | public void testLoadWithDefaultObjectMapper() throws Exception { 43 | OpenAPIInflector inflector = new OpenAPIInflector(config); 44 | assertEquals(Json.mapper(),inflector.getObjectMapper()); 45 | assertTrue(inflector.isRegistered(JsonProvider.class)); 46 | 47 | } 48 | 49 | @Test 50 | public void testLoadWithCustomObjectMapper() throws Exception { 51 | // ensure that pretty print is enabled 52 | config.setPrettyPrint(true); 53 | 54 | ObjectMapper objectMapper = new ObjectMapper(); 55 | objectMapper.setSerializationInclusion(JsonInclude.Include.NON_ABSENT); 56 | objectMapper.enable(SerializationFeature.INDENT_OUTPUT); 57 | 58 | OpenAPIInflector inflector = new OpenAPIInflector(config,objectMapper); 59 | 60 | assertEquals(objectMapper,inflector.getObjectMapper()); 61 | assertNotEquals(Json.mapper(),inflector.getObjectMapper()); 62 | // This class SHOULD NOT be registered since the custom mapper 63 | // is providing this functionality. 64 | assertFalse(inflector.isRegistered(JsonProvider.class)); 65 | } 66 | 67 | } 68 | -------------------------------------------------------------------------------- /src/test/java/io/swagger/oas/inflector/config/DirectionDeserializerTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 SmartBear Software 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package io.swagger.oas.inflector.config; 18 | 19 | import com.fasterxml.jackson.databind.JsonMappingException; 20 | import com.fasterxml.jackson.databind.annotation.JsonDeserialize; 21 | import io.swagger.v3.core.util.Yaml; 22 | import org.testng.Assert; 23 | import org.testng.annotations.DataProvider; 24 | import org.testng.annotations.Test; 25 | 26 | import java.io.InputStream; 27 | import java.util.EnumSet; 28 | import java.util.Set; 29 | 30 | public class DirectionDeserializerTest { 31 | private static final String BOOLEAN = "boolean"; 32 | private static final String BAD = "bad"; 33 | 34 | @Test 35 | public void testFromArray() throws Exception { 36 | try (InputStream in = DirectionDeserializerTest.class.getResourceAsStream( 37 | "validation-as-set.yaml")) { 38 | final Holder holder = Yaml.mapper().readValue(in, Holder.class); 39 | Assert.assertEquals(holder.getValue(), EnumSet.of(Configuration.Direction.IN)); 40 | } 41 | } 42 | 43 | @Test(dataProvider = BOOLEAN) 44 | public void testFromBoolean(String source, 45 | Set expected) throws Exception { 46 | try (InputStream in = DirectionDeserializerTest.class.getResourceAsStream(source)) { 47 | final Holder holder = Yaml.mapper().readValue(in, Holder.class); 48 | Assert.assertEquals(holder.getValue(), expected); 49 | } 50 | } 51 | 52 | @Test(dataProvider = BAD, expectedExceptions = {JsonMappingException.class}) 53 | public void testFailures(String source) throws Exception { 54 | try (InputStream in = DirectionDeserializerTest.class.getResourceAsStream(source)) { 55 | Yaml.mapper().readValue(in, Holder.class); 56 | } 57 | } 58 | 59 | @DataProvider(name = BOOLEAN) 60 | private Object[][] listFilesWithBoolean() { 61 | return new Object[][] { 62 | {"validation-as-false.yaml", EnumSet.noneOf(Configuration.Direction.class)}, 63 | {"validation-as-true.yaml", EnumSet.allOf(Configuration.Direction.class)} 64 | }; 65 | } 66 | 67 | @DataProvider(name = BAD) 68 | private Object[][] listBadFiles() { 69 | return new Object[][] { 70 | {"validation-as-incomplete.yaml"}, 71 | {"validation-as-object.yaml"}, 72 | {"validation-as-object-array.yaml"}, 73 | {"validation-as-scalar.yaml"}, 74 | {"validation-as-string-array.yaml"}, 75 | }; 76 | } 77 | 78 | private static class Holder { 79 | private Set value; 80 | 81 | Set getValue() { 82 | return value; 83 | } 84 | 85 | @JsonDeserialize(using = DirectionDeserializer.class) 86 | public void setValue(Set value) { 87 | this.value = value; 88 | } 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /src/test/java/io/swagger/oas/inflector/utils/ApiErrorUtilsTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 SmartBear Software 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package io.swagger.oas.inflector.utils; 18 | 19 | import io.swagger.oas.inflector.models.ApiError; 20 | import org.testng.Assert; 21 | import org.testng.annotations.Test; 22 | 23 | public class ApiErrorUtilsTest { 24 | @Test 25 | public void testInternalError() { 26 | final ApiError first = ApiErrorUtils.createInternalError(); 27 | Assert.assertEquals(first.getCode(), 500); 28 | final ApiError second = ApiErrorUtils.createInternalError(); 29 | Assert.assertEquals(second.getCode(), first.getCode()); 30 | Assert.assertNotEquals(second.getMessage(), first.getMessage()); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/test/java/io/swagger/oas/sample/converters/SampleConverter.java: -------------------------------------------------------------------------------- 1 | package io.swagger.oas.sample.converters; 2 | 3 | import io.swagger.oas.inflector.converters.ConversionException; 4 | import io.swagger.oas.inflector.converters.Converter; 5 | import io.swagger.v3.oas.models.media.Schema; 6 | import io.swagger.v3.oas.models.parameters.Parameter; 7 | import io.swagger.v3.oas.models.parameters.RequestBody; 8 | 9 | 10 | import java.util.Iterator; 11 | import java.util.List; 12 | import java.util.Map; 13 | 14 | public class SampleConverter implements Converter { 15 | public Object convert(List value, Parameter parameter, Class cls, Map definitions, Iterator chain) 16 | throws ConversionException { 17 | if(chain.hasNext()) { 18 | return chain.next().convert(value, parameter, cls, definitions, chain); 19 | } 20 | return null; 21 | } 22 | public Object convert(List value, RequestBody body, Class cls, Map definitions, Iterator chain) 23 | throws ConversionException { 24 | if(chain.hasNext()) { 25 | return chain.next().convert(value, body, cls, definitions, chain); 26 | } 27 | return null; 28 | } 29 | 30 | public Object convert(List value, RequestBody body, Class cls, Class innerClass, Map definitions, Iterator chain) throws ConversionException { 31 | if(chain.hasNext()) { 32 | return chain.next().convert(value, body, cls, innerClass, definitions, chain); 33 | } 34 | return null; 35 | } 36 | } -------------------------------------------------------------------------------- /src/test/java/io/swagger/oas/sample/models/Category.java: -------------------------------------------------------------------------------- 1 | package io.swagger.oas.sample.models; 2 | 3 | import javax.xml.bind.annotation.XmlElement; 4 | import javax.xml.bind.annotation.XmlRootElement; 5 | 6 | @XmlRootElement(name = "Category") 7 | public class Category { 8 | private long id; 9 | private String name; 10 | 11 | @XmlElement(name = "id") 12 | public long getId() { 13 | return id; 14 | } 15 | 16 | public void setId(long id) { 17 | this.id = id; 18 | } 19 | 20 | @XmlElement(name = "name") 21 | public String getName() { 22 | return name; 23 | } 24 | 25 | public void setName(String name) { 26 | this.name = name; 27 | } 28 | } -------------------------------------------------------------------------------- /src/test/java/io/swagger/oas/sample/models/Dog.java: -------------------------------------------------------------------------------- 1 | package io.swagger.oas.sample.models; 2 | 3 | import javax.xml.bind.annotation.XmlElement; 4 | 5 | public class Dog { 6 | 7 | public Dog id(Long id) { 8 | this.id = id; 9 | return this; 10 | } 11 | 12 | public Dog name(String name) { 13 | this.name = name; 14 | return this; 15 | } 16 | 17 | public Dog dogType(String dogType) { 18 | this.dogType = dogType; 19 | return this; 20 | } 21 | 22 | @XmlElement 23 | public Long id; 24 | 25 | @XmlElement 26 | public String name; 27 | 28 | @XmlElement 29 | public String dogType; 30 | } -------------------------------------------------------------------------------- /src/test/java/io/swagger/oas/sample/models/Pet.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2018 SmartBear Software 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package io.swagger.oas.sample.models; 18 | 19 | import io.swagger.v3.oas.annotations.media.Schema; 20 | 21 | import javax.xml.bind.annotation.XmlElement; 22 | import javax.xml.bind.annotation.XmlElementWrapper; 23 | import javax.xml.bind.annotation.XmlRootElement; 24 | import java.util.ArrayList; 25 | import java.util.List; 26 | 27 | @XmlRootElement(name = "Pet") 28 | public class Pet { 29 | private Long id; 30 | private Category category; 31 | private String name; 32 | private List photoUrls = new ArrayList<>(); 33 | private List tags = new ArrayList<>(); 34 | private String status; 35 | 36 | @XmlElement(name = "id") 37 | public long getId() { 38 | return id; 39 | } 40 | 41 | public void setId(final Long id) { 42 | this.id = id; 43 | } 44 | 45 | @XmlElement(name = "category") 46 | public Category getCategory() { 47 | return category; 48 | } 49 | 50 | public void setCategory(final Category category) { 51 | this.category = category; 52 | } 53 | 54 | @XmlElement(name = "name") 55 | public String getName() { 56 | return name; 57 | } 58 | 59 | public void setName(final String name) { 60 | this.name = name; 61 | } 62 | 63 | @XmlElementWrapper(name = "photoUrls") 64 | @XmlElement(name = "photoUrl") 65 | public List getPhotoUrls() { 66 | return photoUrls; 67 | } 68 | 69 | public void setPhotoUrls(final List photoUrls) { 70 | this.photoUrls = photoUrls; 71 | } 72 | 73 | @XmlElementWrapper(name = "tags") 74 | @XmlElement(name = "tag") 75 | public List getTags() { 76 | return tags; 77 | } 78 | 79 | public void setTags(final List tags) { 80 | this.tags = tags; 81 | } 82 | 83 | @XmlElement(name = "status") 84 | @Schema(description = "pet status in the store", allowableValues = "available,pending,sold") 85 | public String getStatus() { 86 | return status; 87 | } 88 | 89 | public void setStatus(final String status) { 90 | this.status = status; 91 | } 92 | } -------------------------------------------------------------------------------- /src/test/java/io/swagger/oas/sample/models/Tag.java: -------------------------------------------------------------------------------- 1 | package io.swagger.oas.sample.models; 2 | 3 | 4 | import javax.xml.bind.annotation.XmlElement; 5 | import javax.xml.bind.annotation.XmlRootElement; 6 | 7 | @XmlRootElement(name = "Tag") 8 | public class Tag { 9 | private long id; 10 | private String name; 11 | 12 | @XmlElement(name = "id") 13 | public long getId() { 14 | return id; 15 | } 16 | 17 | public void setId(long id) { 18 | this.id = id; 19 | } 20 | 21 | @XmlElement(name = "name") 22 | public String getName() { 23 | return name; 24 | } 25 | 26 | public void setName(String name) { 27 | this.name = name; 28 | } 29 | } -------------------------------------------------------------------------------- /src/test/java/io/swagger/oas/test/ConfigurationLoaderTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 SmartBear Software 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package io.swagger.oas.test; 18 | 19 | import org.testng.annotations.Test; 20 | 21 | import static org.junit.Assert.assertFalse; 22 | import static org.junit.Assert.assertTrue; 23 | import static org.testng.Assert.assertNotNull; 24 | 25 | public class ConfigurationLoaderTest { 26 | @Test 27 | public void testLoadSampleConfiguration() throws Exception { 28 | System.setProperty("config", "src/test/config/config2.yaml"); 29 | io.swagger.oas.inflector.config.Configuration config = io.swagger.oas.inflector.config.Configuration.read(); 30 | assertNotNull(config); 31 | assertTrue(config.getExposedSpecOptions().getParseOptions().isResolve()); 32 | assertFalse(config.getExposedSpecOptions().isHideInflectorExtensions()); 33 | } 34 | 35 | @Test 36 | public void testExposedSpecFromFileDefaults() throws Exception { 37 | System.setProperty("config", "src/test/config/config1.yaml"); 38 | io.swagger.oas.inflector.config.Configuration config = io.swagger.oas.inflector.config.Configuration.read(); 39 | assertNotNull(config); 40 | assertFalse(config.getExposedSpecOptions().getParseOptions().isResolve()); 41 | assertTrue(config.getExposedSpecOptions().isHideInflectorExtensions()); 42 | } 43 | 44 | 45 | } 46 | -------------------------------------------------------------------------------- /src/test/java/io/swagger/oas/test/ResponseModelTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 SmartBear Software 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package io.swagger.oas.test; 18 | 19 | import io.swagger.v3.core.converter.ModelConverters; 20 | import io.swagger.oas.inflector.examples.ExampleBuilder; 21 | import io.swagger.oas.inflector.examples.models.IntegerExample; 22 | import io.swagger.oas.inflector.examples.models.ObjectExample; 23 | import io.swagger.oas.inflector.examples.models.StringExample; 24 | 25 | import io.swagger.v3.oas.models.media.IntegerSchema; 26 | import io.swagger.v3.oas.models.media.Schema; 27 | import io.swagger.v3.oas.models.media.StringSchema; 28 | import io.swagger.oas.test.models.User; 29 | import io.swagger.v3.core.util.Json; 30 | import org.testng.annotations.Test; 31 | 32 | import java.util.Map; 33 | 34 | import static org.testng.Assert.assertEquals; 35 | import static org.testng.Assert.assertNotNull; 36 | import static org.testng.Assert.assertTrue; 37 | 38 | public class ResponseModelTest { 39 | @Test 40 | public void testConvertStringProperty() throws Exception { 41 | StringSchema p = new StringSchema(); 42 | 43 | Object o = ExampleBuilder.fromSchema(p, null); 44 | assertNotNull(o); 45 | assertTrue(o instanceof StringExample); 46 | assertEquals(((StringExample) o).textValue(), "string"); 47 | } 48 | 49 | @Test 50 | public void testConvertStringPropertyWithExample() throws Exception { 51 | Schema p = new StringSchema() 52 | .example("fun"); 53 | 54 | Object o = ExampleBuilder.fromSchema(p, null); 55 | assertNotNull(o); 56 | assertTrue(o instanceof StringExample); 57 | assertEquals(((StringExample) o).textValue(), "fun"); 58 | } 59 | 60 | @Test 61 | public void testConvertIntegerProperty() throws Exception { 62 | IntegerSchema p = new IntegerSchema(); 63 | 64 | Object o = ExampleBuilder.fromSchema(p, null); 65 | assertNotNull(o); 66 | assertTrue(o instanceof IntegerExample); 67 | assertEquals(((IntegerExample) o).asInt(), new Integer(0)); 68 | } 69 | 70 | @Test 71 | public void testConvertIntegerPropertyWithExample() throws Exception { 72 | Schema p = new IntegerSchema() 73 | .example(3); 74 | 75 | Object o = ExampleBuilder.fromSchema(p, null); 76 | assertNotNull(o); 77 | assertTrue(o instanceof IntegerExample); 78 | assertEquals(((IntegerExample) o).asInt(), new Integer(3)); 79 | } 80 | 81 | @Test 82 | public void testComplexModel() throws Exception { 83 | Schema property = new Schema().$ref("User"); 84 | Map definitions = ModelConverters.getInstance().readAll(User.class); 85 | Object o = ExampleBuilder.fromSchema(property, definitions); 86 | 87 | ObjectExample n = Json.mapper().convertValue(o, ObjectExample.class); 88 | assertNotNull(n); 89 | } 90 | } -------------------------------------------------------------------------------- /src/test/java/io/swagger/oas/test/client/ApiException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 SmartBear Software 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package io.swagger.oas.test.client; 18 | 19 | import java.util.List; 20 | import java.util.Map; 21 | 22 | public class ApiException extends Exception { 23 | /** 24 | * 25 | */ 26 | private static final long serialVersionUID = 1L; 27 | private int code = 0; 28 | private String message = null; 29 | private Map> responseHeaders = null; 30 | private String responseBody = null; 31 | 32 | public ApiException() { 33 | } 34 | 35 | public ApiException(int code, String message) { 36 | this.code = code; 37 | this.message = message; 38 | } 39 | 40 | public ApiException(int code, String message, Map> responseHeaders, String responseBody) { 41 | this.code = code; 42 | this.message = message; 43 | this.responseHeaders = responseHeaders; 44 | this.responseBody = responseBody; 45 | } 46 | 47 | public int getCode() { 48 | return code; 49 | } 50 | 51 | public String getMessage() { 52 | return message; 53 | } 54 | 55 | /** 56 | * Get the HTTP response headers. 57 | */ 58 | public Map> getResponseHeaders() { 59 | return responseHeaders; 60 | } 61 | 62 | /** 63 | * Get the HTTP response body. 64 | */ 65 | public String getResponseBody() { 66 | return responseBody; 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /src/test/java/io/swagger/oas/test/client/StringUtil.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 SmartBear Software 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package io.swagger.oas.test.client; 18 | 19 | public class StringUtil { 20 | /** 21 | * Check if the given array contains the given value (with case-insensitive comparison). 22 | * 23 | * @param array The array 24 | * @param value The value to search 25 | * @return true if the array contains the value 26 | */ 27 | public static boolean containsIgnoreCase(String[] array, String value) { 28 | for (String str : array) { 29 | if (value == null && str == null) { 30 | return true; 31 | } 32 | if (value != null && value.equalsIgnoreCase(str)) { 33 | return true; 34 | } 35 | } 36 | return false; 37 | } 38 | 39 | /** 40 | * Join an array of strings with the given separator. 41 | *

42 | * Note: This might be replaced by utility method from commons-lang or guava someday 43 | * if one of those libraries is added as dependency. 44 | *

45 | * 46 | * @param array The array of strings 47 | * @param separator The separator 48 | * @return the resulting string 49 | */ 50 | public static String join(String[] array, String separator) { 51 | int len = array.length; 52 | if (len == 0) { 53 | return ""; 54 | } 55 | 56 | StringBuilder out = new StringBuilder(); 57 | out.append(array[0]); 58 | for (int i = 1; i < len; i++) { 59 | out.append(separator).append(array[i]); 60 | } 61 | return out.toString(); 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/test/java/io/swagger/oas/test/client/auth/ApiKeyAuth.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 SmartBear Software 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package io.swagger.oas.test.client.auth; 18 | 19 | import java.util.Map; 20 | 21 | public class ApiKeyAuth implements Authentication { 22 | private final String location; 23 | private final String paramName; 24 | 25 | private String apiKey; 26 | private String apiKeyPrefix; 27 | 28 | public ApiKeyAuth(String location, String paramName) { 29 | this.location = location; 30 | this.paramName = paramName; 31 | } 32 | 33 | public String getLocation() { 34 | return location; 35 | } 36 | 37 | public String getParamName() { 38 | return paramName; 39 | } 40 | 41 | public String getApiKey() { 42 | return apiKey; 43 | } 44 | 45 | public void setApiKey(String apiKey) { 46 | this.apiKey = apiKey; 47 | } 48 | 49 | public String getApiKeyPrefix() { 50 | return apiKeyPrefix; 51 | } 52 | 53 | public void setApiKeyPrefix(String apiKeyPrefix) { 54 | this.apiKeyPrefix = apiKeyPrefix; 55 | } 56 | 57 | @Override 58 | public void applyToParams(Map queryParams, Map headerParams) { 59 | String value; 60 | if (apiKeyPrefix != null) { 61 | value = apiKeyPrefix + " " + apiKey; 62 | } else { 63 | value = apiKey; 64 | } 65 | if (location == "query") { 66 | queryParams.put(paramName, value); 67 | } else if (location == "header") { 68 | headerParams.put(paramName, value); 69 | } 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /src/test/java/io/swagger/oas/test/client/auth/Authentication.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 SmartBear Software 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package io.swagger.oas.test.client.auth; 18 | 19 | import java.util.Map; 20 | 21 | public interface Authentication { 22 | /** 23 | * Apply authentication settings to header and query params. 24 | */ 25 | void applyToParams(Map queryParams, Map headerParams); 26 | } 27 | -------------------------------------------------------------------------------- /src/test/java/io/swagger/oas/test/client/auth/HttpBasicAuth.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 SmartBear Software 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package io.swagger.oas.test.client.auth; 18 | 19 | import javax.xml.bind.DatatypeConverter; 20 | import java.io.UnsupportedEncodingException; 21 | import java.util.Map; 22 | 23 | public class HttpBasicAuth implements Authentication { 24 | private String username; 25 | private String password; 26 | 27 | public String getUsername() { 28 | return username; 29 | } 30 | 31 | public void setUsername(String username) { 32 | this.username = username; 33 | } 34 | 35 | public String getPassword() { 36 | return password; 37 | } 38 | 39 | public void setPassword(String password) { 40 | this.password = password; 41 | } 42 | 43 | @Override 44 | public void applyToParams(Map queryParams, Map headerParams) { 45 | String str = (username == null ? "" : username) + ":" + (password == null ? "" : password); 46 | try { 47 | headerParams.put("Authorization", "Basic " + DatatypeConverter.printBase64Binary(str.getBytes("UTF-8"))); 48 | } catch (UnsupportedEncodingException e) { 49 | throw new RuntimeException(e); 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/test/java/io/swagger/oas/test/client/auth/OAuth.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 SmartBear Software 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package io.swagger.oas.test.client.auth; 18 | 19 | import java.util.Map; 20 | 21 | public class OAuth implements Authentication { 22 | @Override 23 | public void applyToParams(Map queryParams, Map headerParams) { 24 | // TODO: support oauth 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/test/java/io/swagger/oas/test/integration/responses/OverloadedResponseTestIT.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 SmartBear Software 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package io.swagger.oas.test.integration.responses; 18 | 19 | import io.swagger.oas.test.models.User; 20 | import io.swagger.oas.test.client.ApiClient; 21 | 22 | import io.swagger.v3.core.util.Json; 23 | 24 | import org.testng.annotations.Test; 25 | 26 | import java.util.HashMap; 27 | import java.util.Map; 28 | 29 | import static org.testng.Assert.assertNotNull; 30 | 31 | public class OverloadedResponseTestIT { 32 | @Test 33 | public void verifyOverloadedMethod() throws Exception { 34 | ApiClient client = new ApiClient(); 35 | 36 | Map queryParams = new HashMap(); 37 | queryParams.put("arg1", "test1"); 38 | 39 | String str = client.invokeAPI("/overloaded", "GET", queryParams, null, new HashMap(), null, "application/json", null, new String[0]); 40 | User user = Json.mapper().readValue(str, User.class); 41 | 42 | assertNotNull(user); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/test/java/io/swagger/oas/test/models/Address.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 SmartBear Software 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package io.swagger.oas.test.models; 18 | 19 | public class Address { 20 | private String street; 21 | private String city; 22 | private String state; 23 | private String zip; 24 | 25 | public String getStreet() { 26 | return this.street; 27 | } 28 | public void setStreet(String street) { 29 | this.street = street; 30 | } 31 | 32 | public String getCity() { 33 | return this.city; 34 | } 35 | public void setCity(String city) { 36 | this.city = city; 37 | } 38 | 39 | public String getState() { 40 | return this.state; 41 | } 42 | public void setState(String state) { 43 | this.state = state; 44 | } 45 | 46 | public String getZip() { 47 | return this.zip; 48 | } 49 | public void setZip(String zip) { 50 | this.zip = zip; 51 | } 52 | } -------------------------------------------------------------------------------- /src/test/java/io/swagger/oas/test/models/ExtendedAddress.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 SmartBear Software 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package io.swagger.oas.test.models; 18 | 19 | public class ExtendedAddress extends Address { 20 | private String gps; 21 | 22 | public String getGps() { 23 | return gps; 24 | } 25 | 26 | public void setGps(String gps) { 27 | this.gps = gps; 28 | } 29 | } -------------------------------------------------------------------------------- /src/test/java/io/swagger/oas/test/models/Person.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 SmartBear Software 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package io.swagger.oas.test.models; 18 | 19 | import javax.xml.bind.annotation.XmlElement; 20 | import javax.xml.bind.annotation.XmlRootElement; 21 | 22 | @XmlRootElement 23 | public class Person { 24 | @XmlElement 25 | public Long id; 26 | 27 | @XmlElement 28 | public String name; 29 | } 30 | -------------------------------------------------------------------------------- /src/test/java/io/swagger/oas/test/models/ResponseContextSerializationTest.java: -------------------------------------------------------------------------------- 1 | package io.swagger.oas.test.models; 2 | 3 | import io.swagger.oas.inflector.models.ResponseContext; 4 | import io.swagger.v3.core.util.Json; 5 | import org.testng.annotations.Test; 6 | 7 | public class ResponseContextSerializationTest { 8 | @Test 9 | public void testHeader() { 10 | ResponseContext ctx = new ResponseContext() 11 | .header("foo", "bar"); 12 | 13 | Json.prettyPrint(ctx); 14 | 15 | for (String key : ctx.getHeaders().keySet()) { 16 | System.out.println(key); 17 | System.out.println(ctx.getHeaders().get(key)); 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/test/java/io/swagger/oas/test/models/User.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 SmartBear Software 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package io.swagger.oas.test.models; 18 | 19 | import javax.xml.bind.annotation.XmlElement; 20 | import javax.xml.bind.annotation.XmlElementWrapper; 21 | import javax.xml.bind.annotation.XmlRootElement; 22 | import java.util.List; 23 | 24 | @XmlRootElement(name = "user") 25 | public class User { 26 | private Long id; 27 | private String user; 28 | private List names; 29 | 30 | public User id(Long id) { 31 | this.id = id; 32 | return this; 33 | } 34 | 35 | public User user(String user) { 36 | this.user = user; 37 | return this; 38 | } 39 | 40 | public Long getId() { 41 | return id; 42 | } 43 | 44 | public void setId(Long id) { 45 | this.id = id; 46 | } 47 | 48 | public String getUser() { 49 | return user; 50 | } 51 | 52 | public void setUser(String user) { 53 | this.user = user; 54 | } 55 | 56 | @XmlElementWrapper(name = "children") 57 | @XmlElement(name = "child") 58 | public List getChildNames() { 59 | return names; 60 | } 61 | 62 | public void setChildNames(List names) { 63 | this.names = names; 64 | } 65 | } -------------------------------------------------------------------------------- /src/test/java/io/swagger/oas/test/processors/BinaryProcessorTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 SmartBear Software 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package io.swagger.oas.test.processors; 18 | 19 | 20 | import io.swagger.oas.inflector.config.Configuration; 21 | import io.swagger.oas.inflector.controllers.OpenAPIOperationController; 22 | import io.swagger.oas.inflector.processors.BinaryProcessor; 23 | import io.swagger.oas.inflector.processors.EntityProcessor; 24 | import io.swagger.v3.oas.models.Operation; 25 | import io.swagger.v3.oas.models.media.Content; 26 | 27 | import io.swagger.v3.oas.models.media.Schema; 28 | import io.swagger.v3.oas.models.media.StringSchema; 29 | import io.swagger.v3.oas.models.parameters.RequestBody; 30 | 31 | import mockit.Mocked; 32 | 33 | import mockit.StrictExpectations; 34 | import org.mockito.Mockito; 35 | import org.testng.Assert; 36 | import org.testng.annotations.Test; 37 | 38 | import javax.ws.rs.HttpMethod; 39 | import javax.ws.rs.core.MediaType; 40 | import java.io.ByteArrayInputStream; 41 | import java.util.HashMap; 42 | import java.util.Map; 43 | 44 | 45 | import static org.testng.Assert.assertEquals; 46 | import static org.testng.Assert.assertTrue; 47 | 48 | public class BinaryProcessorTest { 49 | 50 | private static final MediaType BINARY_TYPE = MediaType.APPLICATION_OCTET_STREAM_TYPE; 51 | private final EntityProcessor processor = new BinaryProcessor(); 52 | 53 | @Test 54 | public void supportsTest() { 55 | assertTrue(processor.supports(BINARY_TYPE)); 56 | 57 | MediaType zipMediaType = new MediaType("application", "zip"); 58 | processor.enableType(zipMediaType); 59 | assertTrue( processor.supports( zipMediaType )); 60 | } 61 | 62 | @Test 63 | public void processTestWithException() throws UnsupportedOperationException { 64 | final byte[] expected = "binary string".getBytes(); 65 | try { 66 | final byte[] actual = (byte[]) processor.process(MediaType.APPLICATION_OCTET_STREAM_TYPE, 67 | new ByteArrayInputStream(expected), byte[].class); 68 | Assert.fail("No exception was thrown"); 69 | assertEquals(actual, expected); 70 | }catch (Exception e){ 71 | 72 | } 73 | } 74 | 75 | @Test 76 | public void processTest(@Mocked Configuration config, @Mocked Map definitions){ 77 | 78 | Operation operation = new Operation().requestBody(new RequestBody().content(new Content(). 79 | addMediaType( "application/octec-stream", 80 | new io.swagger.v3.oas.models.media.MediaType(). 81 | schema(new Schema() 82 | .type("string") 83 | .format("binary"))))); 84 | 85 | OpenAPIOperationController controller = new OpenAPIOperationController(config,"/primitiveBody/binary", HttpMethod.POST, operation,"application/octec-stream", definitions); 86 | 87 | final byte[] expected = "binary string".getBytes(); 88 | 89 | try { 90 | final byte[] actual = (byte[]) processor.process(MediaType.APPLICATION_OCTET_STREAM_TYPE, 91 | new ByteArrayInputStream(expected), byte[].class,controller); 92 | 93 | assertEquals(actual, expected); 94 | }catch (Exception e){ 95 | 96 | 97 | } 98 | 99 | } 100 | 101 | } 102 | -------------------------------------------------------------------------------- /src/test/java/io/swagger/oas/test/processors/JacksonProcessorTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 SmartBear Software 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package io.swagger.oas.test.processors; 18 | 19 | import com.fasterxml.jackson.databind.JsonNode; 20 | import com.fasterxml.jackson.databind.node.ObjectNode; 21 | import io.swagger.oas.inflector.processors.EntityProcessorFactory; 22 | import io.swagger.oas.inflector.processors.JacksonProcessor; 23 | import org.testng.annotations.Test; 24 | 25 | import javax.ws.rs.core.MediaType; 26 | import java.io.ByteArrayInputStream; 27 | import java.io.InputStream; 28 | import java.nio.charset.StandardCharsets; 29 | 30 | import static org.testng.Assert.assertEquals; 31 | 32 | public class JacksonProcessorTest { 33 | @Test 34 | public void testConvertXMLContent() throws Exception { 35 | String input = "1fehguy"; 36 | 37 | EntityProcessorFactory.addProcessor(JacksonProcessor.class, MediaType.APPLICATION_XML_TYPE); 38 | 39 | InputStream is = new ByteArrayInputStream(input.getBytes()); 40 | ObjectNode o = (ObjectNode) EntityProcessorFactory.readValue(MediaType.APPLICATION_XML_TYPE, is, JsonNode.class); 41 | assertEquals(o.getClass(), ObjectNode.class); 42 | assertEquals(o.get("name").asText(), "fehguy"); 43 | } 44 | 45 | @Test 46 | public void testConvertJsonContent() throws Exception { 47 | String input = "{\"name\":\"fehguy\"}"; 48 | EntityProcessorFactory.addProcessor(JacksonProcessor.class, MediaType.APPLICATION_JSON_TYPE); 49 | 50 | InputStream is = new ByteArrayInputStream(input.getBytes()); 51 | ObjectNode o = (ObjectNode) EntityProcessorFactory.readValue(MediaType.APPLICATION_JSON_TYPE, is, JsonNode.class); 52 | assertEquals(o.getClass(), ObjectNode.class); 53 | assertEquals(o.get("name").asText(), "fehguy"); 54 | } 55 | 56 | @Test 57 | public void testConvertYamlContent() throws Exception { 58 | String input = "name: fehguy\nuserId: 42"; 59 | EntityProcessorFactory.addProcessor(JacksonProcessor.class, JacksonProcessor.APPLICATION_YAML_TYPE); 60 | 61 | InputStream is = new ByteArrayInputStream(input.getBytes()); 62 | MediaType t = MediaType.valueOf("application/yaml"); 63 | 64 | ObjectNode o = (ObjectNode) EntityProcessorFactory.readValue(t, is, JsonNode.class); 65 | assertEquals(o.getClass(), ObjectNode.class); 66 | assertEquals(o.get("name").asText(), "fehguy"); 67 | assertEquals(o.get("userId").asText(), "42"); 68 | } 69 | 70 | @Test 71 | public void testConvertYamlWithEncoding() throws Exception { 72 | final String input = "type: application\nsubtype: yaml\ncharset: UTF-8"; 73 | final MediaType type = new MediaType("application", "yaml", StandardCharsets.UTF_8.name()); 74 | 75 | final String string = (String) EntityProcessorFactory.readValue(type, 76 | new ByteArrayInputStream(input.getBytes(StandardCharsets.UTF_8)), String.class); 77 | assertEquals(string, input); 78 | 79 | final ObjectNode json = (ObjectNode) EntityProcessorFactory.readValue(type, 80 | new ByteArrayInputStream(input.getBytes(StandardCharsets.UTF_8)), JsonNode.class); 81 | assertEquals(json.get("type").asText(), "application"); 82 | assertEquals(json.get("subtype").asText(), "yaml"); 83 | assertEquals(json.get("charset").asText(), "UTF-8"); 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /src/test/java/io/swagger/oas/test/schema/SchemaValidationTest.java: -------------------------------------------------------------------------------- 1 | package io.swagger.oas.test.schema; 2 | 3 | import com.fasterxml.jackson.databind.JsonNode; 4 | import com.github.fge.jsonschema.core.report.ProcessingReport; 5 | import com.github.fge.jsonschema.main.JsonSchemaFactory; 6 | import io.swagger.oas.inflector.schema.SchemaValidator; 7 | import io.swagger.v3.core.util.Json; 8 | import org.testng.annotations.Test; 9 | 10 | import static org.testng.Assert.assertFalse; 11 | import static org.testng.AssertJUnit.assertTrue; 12 | 13 | public class SchemaValidationTest { 14 | @Test 15 | public void testValidPayload() { 16 | User user = new User(); 17 | user.id = 9873432343L; 18 | user.name = "Fred"; 19 | 20 | String schema = "{\n" + 21 | " \"required\": [\n" + 22 | " \"id\"\n" + 23 | " ],\n" + 24 | " \"properties\": {\n" + 25 | " \"id\": {\n" + 26 | " \"type\": \"integer\",\n" + 27 | " \"format\": \"int64\"\n" + 28 | " }\n" + 29 | " }\n" + 30 | "}"; 31 | 32 | assertTrue(SchemaValidator.validate(user, schema, SchemaValidator.Direction.INPUT)); 33 | } 34 | 35 | public void testInvalidPayload() { 36 | User user = new User(); 37 | user.name = "Fred"; 38 | 39 | String schema = "{\n" + 40 | " \"required\": [\n" + 41 | " \"id\"\n" + 42 | " ],\n" + 43 | " \"properties\": {\n" + 44 | " \"id\": {\n" + 45 | " \"type\": \"integer\",\n" + 46 | " \"format\": \"int64\"\n" + 47 | " }\n" + 48 | " }\n" + 49 | "}"; 50 | 51 | assertFalse(SchemaValidator.validate(user, schema, SchemaValidator.Direction.INPUT)); 52 | } 53 | 54 | public void testInvalidPayloadWithRange() { 55 | User user = new User(); 56 | user.id = 0L; 57 | user.name = "Fred"; 58 | 59 | String schema = "{\n" + 60 | " \"required\": [\n" + 61 | " \"id\"\n" + 62 | " ],\n" + 63 | " \"properties\": {\n" + 64 | " \"id\": {\n" + 65 | " \"type\": \"integer\",\n" + 66 | " \"format\": \"int64\",\n" + 67 | " \"minimum\": 123,\n" + 68 | " \"maximum\": 400\n" + 69 | " }\n" + 70 | " }\n" + 71 | "}"; 72 | 73 | assertFalse(SchemaValidator.validate(user, schema, SchemaValidator.Direction.INPUT)); 74 | } 75 | 76 | @Test 77 | public void testValidation() throws Exception { 78 | String schemaAsString = 79 | "{\n" + 80 | " \"properties\": {\n" + 81 | " \"id\": {\n" + 82 | " \"type\": \"integer\",\n" + 83 | " \"format\": \"int64\"\n" + 84 | " }\n" + 85 | " }\n" + 86 | "}"; 87 | JsonNode schemaObject = Json.mapper().readTree(schemaAsString); 88 | JsonNode content = Json.mapper().readValue("{\n" + 89 | " \"id\": 123\n" + 90 | "}", JsonNode.class); 91 | 92 | JsonSchemaFactory factory = JsonSchemaFactory.byDefault(); 93 | com.github.fge.jsonschema.main.JsonSchema schema = factory.getJsonSchema(schemaObject); 94 | 95 | ProcessingReport report = schema.validate(content); 96 | assertTrue(report.isSuccess()); 97 | } 98 | 99 | static class User { 100 | public Long id; 101 | public String name; 102 | } 103 | } 104 | -------------------------------------------------------------------------------- /src/test/java/io/swagger/oas/test/validators/DefaultValidatorTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 SmartBear Software 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package io.swagger.oas.test.validators; 18 | 19 | import io.swagger.oas.inflector.converters.ConversionException; 20 | import io.swagger.oas.inflector.converters.InputConverter; 21 | import io.swagger.oas.inflector.validators.*; 22 | import io.swagger.v3.oas.models.media.IntegerSchema; 23 | import io.swagger.v3.oas.models.media.StringSchema; 24 | import io.swagger.v3.oas.models.parameters.Parameter; 25 | 26 | 27 | import io.swagger.v3.oas.models.parameters.QueryParameter; 28 | import org.testng.annotations.BeforeClass; 29 | import org.testng.annotations.Test; 30 | 31 | import java.util.Arrays; 32 | 33 | public class DefaultValidatorTest { 34 | InputConverter converter; 35 | 36 | @BeforeClass 37 | public void setup() { 38 | converter = InputConverter.getInstance() 39 | .defaultConverters() 40 | .defaultValidators(); 41 | } 42 | 43 | @Test 44 | public void testOptionalParameter() throws Exception { 45 | Parameter parameter = new QueryParameter() 46 | .name("test") 47 | .schema(new StringSchema()); 48 | 49 | converter.validate(null, parameter); 50 | } 51 | 52 | @Test(expectedExceptions = ValidationException.class) 53 | public void testRequiredParameter() throws Exception { 54 | Parameter parameter = new QueryParameter() 55 | .name("test") 56 | .required(true) 57 | .schema(new StringSchema()); 58 | 59 | converter.validate(null, parameter); 60 | } 61 | 62 | @Test(expectedExceptions = ConversionException.class) 63 | public void testInvalidDatatype() throws Exception { 64 | Parameter parameter = new QueryParameter() 65 | .name("test") 66 | .required(true) 67 | .schema(new IntegerSchema()); 68 | 69 | converter.convertAndValidate(Arrays.asList("oops"), parameter, Integer.class, null); 70 | } 71 | } -------------------------------------------------------------------------------- /src/test/resources/io/swagger/oas/inflector/config/validation-as-false.yaml: -------------------------------------------------------------------------------- 1 | value: false -------------------------------------------------------------------------------- /src/test/resources/io/swagger/oas/inflector/config/validation-as-incomplete.yaml: -------------------------------------------------------------------------------- 1 | value 2 | -------------------------------------------------------------------------------- /src/test/resources/io/swagger/oas/inflector/config/validation-as-object-array.yaml: -------------------------------------------------------------------------------- 1 | value: 2 | - nestedObject: 3 | nestedValue: 1 4 | - nestedObject: 5 | nestedValue: 2 -------------------------------------------------------------------------------- /src/test/resources/io/swagger/oas/inflector/config/validation-as-object.yaml: -------------------------------------------------------------------------------- 1 | value: 2 | nextedValue: 1 3 | -------------------------------------------------------------------------------- /src/test/resources/io/swagger/oas/inflector/config/validation-as-scalar.yaml: -------------------------------------------------------------------------------- 1 | value: Some scalar value -------------------------------------------------------------------------------- /src/test/resources/io/swagger/oas/inflector/config/validation-as-set.yaml: -------------------------------------------------------------------------------- 1 | value: 2 | - IN -------------------------------------------------------------------------------- /src/test/resources/io/swagger/oas/inflector/config/validation-as-string-array.yaml: -------------------------------------------------------------------------------- 1 | value: 2 | - ONE 3 | - TWO -------------------------------------------------------------------------------- /src/test/resources/io/swagger/oas/inflector/config/validation-as-true.yaml: -------------------------------------------------------------------------------- 1 | value: true -------------------------------------------------------------------------------- /src/test/swagger/additionalProperties.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | openapi: 3.0.0 3 | info: 4 | version: 1.0.0 5 | title: Boolean `additionProperties` example 6 | paths: 7 | "/someResource": 8 | get: 9 | responses: 10 | '200': 11 | description: Fetching of some resource successful 12 | content: 13 | application/json: 14 | schema: 15 | "$ref": "#/components/schemas/someObject" 16 | components: 17 | schemas: 18 | someObject: 19 | type: object 20 | required: 21 | - innerObject 22 | additionalProperties: 23 | type: string 24 | properties: 25 | innerObject: 26 | type: object 27 | additionalProperties: false 28 | properties: 29 | stringProperty: 30 | type: string 31 | objectProperty: 32 | type: object 33 | additionalProperties: false 34 | properties: 35 | firstPossibleProperty: 36 | type: integer 37 | secondPossibleProperty: 38 | type: string 39 | objectAdditionalProperties: 40 | type: object 41 | properties: 42 | integerProperty: 43 | type: integer 44 | additionalProperties: 45 | type: string 46 | -------------------------------------------------------------------------------- /src/test/swagger/allOfAndRef.yaml: -------------------------------------------------------------------------------- 1 | openapi: 3.0.0 2 | servers: [] 3 | info: 4 | version: 0.1.1 5 | title: 'VirtServer, allOf and $ref' 6 | paths: 7 | /refToAllOf: 8 | get: 9 | responses: 10 | '200': 11 | description: OK 12 | content: 13 | application/json: 14 | schema: 15 | $ref: '#/components/schemas/UserEx' 16 | components: 17 | schemas: 18 | User: 19 | type: object 20 | properties: 21 | username: 22 | type: string 23 | example: trillian 24 | required: 25 | - username 26 | UserEx: 27 | allOf: 28 | - $ref: '#/components/schemas/User' 29 | - type: object 30 | properties: 31 | id: 32 | type: integer 33 | example: 4 34 | required: 35 | - id -------------------------------------------------------------------------------- /src/test/swagger/allOfAndRefResolveFully.yaml: -------------------------------------------------------------------------------- 1 | openapi: 3.0.0 2 | info: 3 | title: test 4 | version: 1.0.0 5 | paths: 6 | /inventory: 7 | get: 8 | responses: 9 | '200': 10 | description: OK 11 | content: 12 | application/xml: 13 | schema: 14 | $ref: '#/components/schemas/InventoryItem' 15 | components: 16 | schemas: 17 | InventoryItem: 18 | type: object 19 | properties: 20 | suppliersArray: 21 | type: array 22 | items: 23 | $ref: '#/components/schemas/Supplier' 24 | xml: 25 | name: inventoryItem 26 | Manufacturer: 27 | type: object 28 | properties: 29 | name: 30 | type: string 31 | example: ACME Corporation 32 | xml: 33 | name: manufacturer 34 | Supplier: 35 | allOf: 36 | - $ref: '#/components/schemas/Manufacturer' 37 | - type: object 38 | properties: 39 | supplierRef: 40 | type: string 41 | example: REF123 42 | xml: 43 | name: supplierObject -------------------------------------------------------------------------------- /src/test/swagger/array-example.yaml: -------------------------------------------------------------------------------- 1 | openapi: 3.0.0 2 | info: 3 | version: 0.0.0 4 | title: Array mock test 5 | paths: 6 | /: 7 | get: 8 | responses: 9 | '200': 10 | description: OK 11 | content: 12 | application/json: 13 | schema: 14 | type: array 15 | items: 16 | $ref: '#/components/schemas/User' 17 | example: 18 | - id: 1 19 | name: Arthur Dent 20 | - id: 2 21 | name: Ford Prefect 22 | components: 23 | schemas: 24 | User: 25 | type: object 26 | properties: 27 | id: 28 | type: integer 29 | example: 0 30 | name: 31 | type: string 32 | example: Marvin -------------------------------------------------------------------------------- /src/test/swagger/example-types.yaml: -------------------------------------------------------------------------------- 1 | openapi: '3.0' 2 | info: 3 | version: 1.0.0 4 | title: Different types in the example 5 | 6 | paths: 7 | /user: 8 | get: 9 | responses: 10 | 200: 11 | description: OK 12 | content: 13 | application/json: 14 | schema: 15 | type: object 16 | properties: 17 | id: 18 | type: integer 19 | format: int32 20 | name: 21 | type: string 22 | required: [id, name] 23 | example: 24 | obj: {b: ho, a: hey} 25 | arr: [hey, ho] 26 | double: 1.2 27 | int: 42 28 | biginteger: 118059162071741130342442 29 | long: 1099511627776 30 | boolean: yes 31 | string: Arthur Dent 32 | -------------------------------------------------------------------------------- /src/test/swagger/issue-1177.yaml: -------------------------------------------------------------------------------- 1 | openapi: '3.0' 2 | info: 3 | version: 1.0.0 4 | title: Array Mocking Test 5 | 6 | paths: 7 | /array: 8 | get: 9 | responses: 10 | 200: 11 | description: OK 12 | content: 13 | application/json: 14 | schema: 15 | $ref: "#/components/schemas/AnArray" 16 | 17 | components: 18 | schemas: 19 | AnArray: 20 | type: array 21 | items: 22 | type: string -------------------------------------------------------------------------------- /src/test/swagger/issue-1261.yaml: -------------------------------------------------------------------------------- 1 | openapi: '3.0' 2 | info: 3 | version: 1.0.0 4 | title: Inline schema example 5 | 6 | paths: 7 | /user: 8 | get: 9 | responses: 10 | 200: 11 | description: OK 12 | content: 13 | application/json: 14 | schema: 15 | type: object 16 | properties: 17 | id: 18 | type: integer 19 | format: int32 20 | name: 21 | type: string 22 | required: [id, name] 23 | example: 24 | id: 42 25 | name: Arthur Dent 26 | -------------------------------------------------------------------------------- /src/test/swagger/issue-1263.yaml: -------------------------------------------------------------------------------- 1 | openapi: '3.0' 2 | info: 3 | version: 1.0.0 4 | title: Nested object example 5 | 6 | paths: 7 | /nested_object: 8 | get: 9 | responses: 10 | 200: 11 | description: OK 12 | content: 13 | application/json: 14 | schema: 15 | $ref: '#/components/schemas/ComplexObject' 16 | 17 | components: 18 | schemas: 19 | ComplexObject: 20 | type: object 21 | properties: 22 | nested_object: 23 | type: object 24 | properties: 25 | foo: 26 | type: string 27 | required: [foo] 28 | required: [nested_object] 29 | # If you remove this example, the generated response structure is correct 30 | example: 31 | nested_object: 32 | foo: bar -------------------------------------------------------------------------------- /src/test/swagger/issue-171.yaml: -------------------------------------------------------------------------------- 1 | openapi: "3.0" 2 | info: 3 | description: test 4 | version: "1.0.0" 5 | title: test 6 | paths: 7 | /test: 8 | get: 9 | parameters: [] 10 | responses: 11 | 200: 12 | description: Gets an array of stuff 13 | content: 14 | application/json: 15 | schema: 16 | type: array 17 | items: 18 | $ref: '#/components/schemas/Stuff' 19 | /anothertest: 20 | get: 21 | responses: 22 | 200: 23 | description: OK 24 | content: 25 | "*/*": 26 | schema: 27 | type: array 28 | items: 29 | type: string 30 | /color: 31 | get: 32 | responses: 33 | 200: 34 | description: OK 35 | content: 36 | application/json: 37 | schema: 38 | $ref: '#/components/schemas/ColorModel' 39 | components: 40 | schemas: 41 | ColorModel: 42 | type: object 43 | properties: 44 | color: 45 | type: string 46 | enum: 47 | - black 48 | - white 49 | required: 50 | - color 51 | Stuff: 52 | type: object 53 | properties: 54 | id: 55 | type: string 56 | nestedArray: 57 | type: array 58 | items: 59 | type: object 60 | required: 61 | - id 62 | - name 63 | properties: 64 | id: 65 | type: string 66 | name: 67 | type: string 68 | -------------------------------------------------------------------------------- /src/test/swagger/issue-300.yaml: -------------------------------------------------------------------------------- 1 | openapi: 3.0.0 2 | servers: 3 | - url: 'https://petstore.swagger.io/v2' 4 | - url: 'http://petstore.swagger.io/v2' 5 | info: 6 | version: 1.0.0 7 | title: Swagger Petstore 8 | paths: 9 | '/pet/{petId}': 10 | get: 11 | summary: Find pet by ID 12 | operationId: getPetById 13 | parameters: 14 | - name: petId 15 | in: path 16 | description: ID of pet to return 17 | required: true 18 | schema: 19 | type: integer 20 | format: int64 21 | responses: 22 | '200': 23 | description: successful operation 24 | content: 25 | application/xml: 26 | schema: 27 | $ref: '#/components/schemas/Pet' 28 | application/json: 29 | schema: 30 | $ref: '#/components/schemas/Pet' 31 | '400': 32 | description: Invalid ID supplied 33 | '404': 34 | description: Pet not found 35 | components: 36 | schemas: 37 | Pet: 38 | type: object 39 | properties: 40 | name: 41 | type: string 42 | example: doggie 43 | shots: 44 | type: array 45 | items: 46 | type: string 47 | example: rabies 48 | xml: 49 | name: shot 50 | xml: 51 | name: shots 52 | wrapped: true 53 | xml: 54 | name: Pet 55 | -------------------------------------------------------------------------------- /src/test/swagger/issue252.yaml: -------------------------------------------------------------------------------- 1 | openapi: 3.0.0 2 | info: 3 | version: v0.1 4 | title: KFI quote engine and product listings API 5 | description: "" 6 | paths: 7 | /products.xml: 8 | get: 9 | summary: Get a list of public products in XML format 10 | operationId: getProductsXML 11 | tags: 12 | - Product List Service 13 | responses: 14 | "200": 15 | description: OK 16 | content: 17 | application/xml: 18 | schema: 19 | xml: 20 | wrapped: true 21 | name: products 22 | type: array 23 | items: 24 | $ref: "#/components/schemas/product" 25 | tags: 26 | - name: Product List Service 27 | servers: 28 | - url: https://virtserver.swaggerhub.com/ThirdOne/xml_issue/v0.1 29 | components: 30 | schemas: 31 | product: 32 | type: object 33 | xml: 34 | name: product 35 | wrapped: true 36 | properties: 37 | id: 38 | type: integer 39 | example: 1 40 | product: 41 | type: string 42 | example: Lump Sum -------------------------------------------------------------------------------- /src/test/swagger/nested-array-example.yaml: -------------------------------------------------------------------------------- 1 | openapi: 3.0.0 2 | info: 3 | version: 0.0.0 4 | title: Nested array mock test 5 | paths: 6 | /: 7 | get: 8 | responses: 9 | '200': 10 | description: OK 11 | content: 12 | application/json: 13 | schema: 14 | type: array 15 | items: 16 | $ref: '#/components/schemas/UserArray' 17 | 18 | components: 19 | schemas: 20 | UserArray: 21 | type: array 22 | items: 23 | $ref: "#/components/schemas/User" 24 | example: 25 | - id: 1 26 | name: Arthur Dent 27 | - id: 2 28 | name: Ford Prefect 29 | User: 30 | type: object 31 | properties: 32 | id: 33 | type: integer 34 | example: 0 35 | name: 36 | type: string 37 | example: Marvin -------------------------------------------------------------------------------- /src/test/swagger/null-examples-oas3-no-flag.yaml: -------------------------------------------------------------------------------- 1 | openapi: 3.0.2 2 | info: 3 | title: null examples 4 | version: 1.0.0 5 | paths: 6 | 7 | /object-with-null-example: 8 | get: 9 | description: Response should be `null` 10 | responses: 11 | '200': 12 | description: Should be `null` 13 | content: 14 | application/json: 15 | schema: 16 | $ref: '#/components/schemas/ObjectWithNullExample' 17 | 18 | /object-with-null-in-schema-example: 19 | get: 20 | description: 'Response should be `{..., "d": null}`' 21 | responses: 22 | '200': 23 | description: 'Should be `{..., "d": null}`' 24 | content: 25 | application/json: 26 | schema: 27 | $ref: '#/components/schemas/ObjectWithNullInSchemaExample' 28 | 29 | /object-with-null-property-example: 30 | get: 31 | description: 'Response should be `{"a": 5, "b": null}`' 32 | responses: 33 | '200': 34 | description: 'Should be `{"a": 5, "b": null}`' 35 | content: 36 | application/json: 37 | schema: 38 | $ref: '#/components/schemas/ObjectWithNullPropertyExample' 39 | 40 | /string-with-null-example: 41 | get: 42 | description: Response should be `null` 43 | responses: 44 | '200': 45 | description: Should be `null` 46 | content: 47 | application/json: 48 | schema: 49 | $ref: '#/components/schemas/StringWithNullExample' 50 | 51 | /array-with-null-array-example: 52 | get: 53 | description: Response should be `null` 54 | responses: 55 | '200': 56 | description: Should be `null` 57 | content: 58 | application/json: 59 | schema: 60 | $ref: '#/components/schemas/ArrayWithNullArrayExample' 61 | 62 | /array-with-null-item-example: 63 | get: 64 | description: Response should be `[null]` 65 | responses: 66 | '200': 67 | description: Should be `[null]` 68 | content: 69 | application/json: 70 | schema: 71 | $ref: '#/components/schemas/ArrayWithNullItemExample' 72 | 73 | /array-with-null-in-array-example: 74 | get: 75 | description: Response should be `["foo", null]` 76 | responses: 77 | '200': 78 | description: Should be `["foo", null]` 79 | content: 80 | application/json: 81 | schema: 82 | $ref: '#/components/schemas/ArrayWithNullInArrayExample' 83 | 84 | components: 85 | schemas: 86 | 87 | ObjectWithNullExample: 88 | type: object 89 | properties: 90 | foo: 91 | type: string 92 | nullable: true 93 | example: null 94 | 95 | ObjectWithNullInSchemaExample: 96 | type: object 97 | example: 98 | a: 5 99 | b: test 100 | c: true 101 | d: null 102 | 103 | ObjectWithNullPropertyExample: 104 | type: object 105 | properties: 106 | a: 107 | type: integer 108 | example: 5 109 | b: 110 | type: string 111 | nullable: true 112 | example: null 113 | 114 | StringWithNullExample: 115 | type: string 116 | nullable: true 117 | example: null 118 | 119 | ArrayWithNullArrayExample: 120 | type: array 121 | items: 122 | type: string 123 | nullable: true 124 | example: null 125 | 126 | ArrayWithNullItemExample: 127 | type: array 128 | items: 129 | type: string 130 | nullable: true 131 | example: null 132 | 133 | ArrayWithNullInArrayExample: 134 | type: array 135 | items: 136 | type: string 137 | nullable: true 138 | example: [foo, null] 139 | -------------------------------------------------------------------------------- /src/test/swagger/oas3_array.yaml: -------------------------------------------------------------------------------- 1 | openapi: 3.0.0 2 | info: 3 | version: '1.0-oas3' 4 | title: VirtServer additionalProperties test 5 | paths: 6 | /dictionaryOfArray: 7 | get: 8 | responses: 9 | 200: 10 | description: OK 11 | content: 12 | application/json: 13 | schema: 14 | type: object 15 | additionalProperties: 16 | type: array 17 | items: 18 | $ref: '#/components/schemas/myScheme' 19 | components: 20 | schemas: 21 | myScheme: 22 | type: object 23 | properties: 24 | joel: 25 | type: string 26 | prop2: 27 | type: integer 28 | # Added by API Auto Mocking Plugin 29 | servers: 30 | - description: SwaggerHub API Auto Mocking 31 | url: https://dev-virtserver.swaggerhub.com/0000/splat240_3/1.0-oas3 -------------------------------------------------------------------------------- /src/test/swagger/oas3_password.yaml: -------------------------------------------------------------------------------- 1 | openapi: 3.0.0 2 | info: 3 | version: '1.0-oas3' 4 | title: VirtServer additionalProperties test 5 | paths: 6 | /dictionaryOfPassword: 7 | get: 8 | responses: 9 | 200: 10 | description: OK 11 | content: 12 | application/json: 13 | schema: 14 | type: object 15 | additionalProperties: 16 | type: string 17 | format: password 18 | 19 | # Added by API Auto Mocking Plugin 20 | servers: 21 | - description: SwaggerHub API Auto Mocking 22 | url: https://dev-virtserver.swaggerhub.com/0000/splat240_3/1.0-oas3 -------------------------------------------------------------------------------- /src/test/swagger/oneOf-anyOf.yaml: -------------------------------------------------------------------------------- 1 | openapi: 3.0.0 2 | info: 3 | version: 0.0.0 4 | title: test 5 | 6 | paths: 7 | /oneOf: 8 | get: 9 | responses: 10 | '200': 11 | description: A book or movie object 12 | content: 13 | application/json: 14 | schema: 15 | oneOf: 16 | - $ref: '#/components/schemas/Book' 17 | - $ref: '#/components/schemas/Movie' 18 | 19 | /anyOf: 20 | get: 21 | responses: 22 | '200': 23 | description: A book or movie object 24 | content: 25 | application/json: 26 | schema: 27 | anyOf: 28 | - $ref: '#/components/schemas/Movie' 29 | - $ref: '#/components/schemas/Book' 30 | 31 | /mixed-array: 32 | get: 33 | responses: 34 | '200': 35 | description: An array containing strings and/or integers 36 | content: 37 | application/json: 38 | schema: 39 | type: array 40 | items: 41 | oneOf: 42 | - type: string 43 | - type: integer 44 | /adjacent: 45 | get: 46 | responses: 47 | '200': 48 | description: A book or movie object 49 | content: 50 | application/json: 51 | schema: 52 | oneOf: 53 | - $ref: '#/components/schemas/Book' 54 | - $ref: '#/components/schemas/Movie' 55 | anyOf: 56 | - $ref: '#/components/schemas/Movie' 57 | - $ref: '#/components/schemas/Book' 58 | 59 | components: 60 | schemas: 61 | Book: 62 | type: object 63 | properties: 64 | title: 65 | type: string 66 | authors: 67 | type: array 68 | items: 69 | type: string 70 | isbn: 71 | type: string 72 | required: 73 | - title 74 | example: 75 | title: The Hitchhiker's Guide to the Galaxy 76 | authors: 77 | - Douglas Adams 78 | isbn: 0-330-25864-8 79 | Movie: 80 | type: object 81 | properties: 82 | title: 83 | type: string 84 | directors: 85 | type: array 86 | items: 87 | type: string 88 | year: 89 | type: integer 90 | required: 91 | - title 92 | example: 93 | title: Blade Runner 94 | directors: 95 | - Ridley Scott 96 | year: 1982 -------------------------------------------------------------------------------- /src/test/swagger/swos-126.yaml: -------------------------------------------------------------------------------- 1 | MyModel: 2 | type: object 3 | properties: 4 | date: 5 | type: string 6 | format: date 7 | example: '2019-08-05' 8 | dateTime: 9 | type: string 10 | format: date-time 11 | example: '2019-08-05T12:34:56Z' -------------------------------------------------------------------------------- /src/test/swagger/write-only.yaml: -------------------------------------------------------------------------------- 1 | openapi: 3.0.0 2 | info: 3 | version: 0.0.0 4 | title: ExampleBuilder writeOnly test 5 | paths: 6 | /user: 7 | get: 8 | responses: 9 | '200': 10 | description: OK 11 | content: 12 | application/json: 13 | schema: 14 | type: object 15 | properties: 16 | username: 17 | type: string 18 | example: bob 19 | password: 20 | type: string 21 | example: p@55w0rd 22 | writeOnly: true --------------------------------------------------------------------------------