diff --git a/.devcontainer/Dockerfile b/.devcontainer/Dockerfile new file mode 100644 index 0000000..bd8e261 --- /dev/null +++ b/.devcontainer/Dockerfile @@ -0,0 +1,23 @@ +# syntax=docker/dockerfile:1 +FROM debian:bookworm-slim + +RUN apt-get update && apt-get install -y --no-install-recommends \ + libxkbcommon0 \ + ca-certificates \ + ca-certificates-java \ + make \ + curl \ + git \ + openjdk-17-jdk-headless \ + unzip \ + libc++1 \ + vim \ + && apt-get clean autoclean + +# Ensure UTF-8 encoding +ENV LANG=C.UTF-8 +ENV LC_ALL=C.UTF-8 + +WORKDIR /workspace + +COPY . /workspace diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json new file mode 100644 index 0000000..d55fc4d --- /dev/null +++ b/.devcontainer/devcontainer.json @@ -0,0 +1,20 @@ +// For format details, see https://aka.ms/devcontainer.json. For config options, see the +// README at: https://github.com/devcontainers/templates/tree/main/src/debian +{ + "name": "Debian", + "build": { + "dockerfile": "Dockerfile" + } + + // Features to add to the dev container. More info: https://containers.dev/features. + // "features": {}, + + // Use 'forwardPorts' to make a list of ports inside the container available locally. + // "forwardPorts": [], + + // Configure tool-specific properties. + // "customizations": {}, + + // Uncomment to connect as root instead. More info: https://aka.ms/dev-containers-non-root. + // "remoteUser": "root" +} diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..022b841 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,5 @@ +# +# https://help.github.com/articles/dealing-with-line-endings/ +# +# These are explicitly windows files and should use crlf +*.bat text eol=crlf diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..02410e7 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,85 @@ +name: CI +on: + push: + branches-ignore: + - 'generated' + - 'codegen/**' + - 'integrated/**' + - 'stl-preview-head/**' + - 'stl-preview-base/**' + pull_request: + branches-ignore: + - 'stl-preview-head/**' + - 'stl-preview-base/**' + +jobs: + lint: + timeout-minutes: 15 + name: lint + runs-on: ${{ github.repository == 'stainless-sdks/imagekit-java' && 'depot-ubuntu-24.04' || 'ubuntu-latest' }} + if: github.event_name == 'push' || github.event.pull_request.head.repo.fork + + steps: + - uses: actions/checkout@v4 + + - name: Set up Java + uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: | + 8 + 21 + cache: gradle + + - name: Set up Gradle + uses: gradle/actions/setup-gradle@v4 + + - name: Run lints + run: ./scripts/lint + + build: + timeout-minutes: 15 + name: build + runs-on: ${{ github.repository == 'stainless-sdks/imagekit-java' && 'depot-ubuntu-24.04' || 'ubuntu-latest' }} + if: github.event_name == 'push' || github.event.pull_request.head.repo.fork + + steps: + - uses: actions/checkout@v4 + + - name: Set up Java + uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: | + 8 + 21 + cache: gradle + + - name: Set up Gradle + uses: gradle/actions/setup-gradle@v4 + + - name: Build SDK + run: ./scripts/build + + test: + timeout-minutes: 15 + name: test + runs-on: ${{ github.repository == 'stainless-sdks/imagekit-java' && 'depot-ubuntu-24.04' || 'ubuntu-latest' }} + if: github.event_name == 'push' || github.event.pull_request.head.repo.fork + steps: + - uses: actions/checkout@v4 + + - name: Set up Java + uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: | + 8 + 21 + cache: gradle + + - name: Set up Gradle + uses: gradle/gradle-build-action@v2 + + - name: Run tests + run: ./scripts/test diff --git a/.github/workflows/publish-sonatype.yml b/.github/workflows/publish-sonatype.yml new file mode 100644 index 0000000..9207f7f --- /dev/null +++ b/.github/workflows/publish-sonatype.yml @@ -0,0 +1,41 @@ +# This workflow is triggered when a GitHub release is created. +# It can also be run manually to re-publish to Sonatype in case it failed for some reason. +# You can run this workflow by navigating to https://www.github.com/imagekit-developer/imagekit-java/actions/workflows/publish-sonatype.yml +name: Publish Sonatype +on: + workflow_dispatch: + + release: + types: [published] + +jobs: + publish: + name: publish + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v4 + + - name: Set up Java + uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: | + 8 + 21 + cache: gradle + + - name: Set up Gradle + uses: gradle/gradle-build-action@v2 + + - name: Publish to Sonatype + run: |- + export -- GPG_SIGNING_KEY_ID + printenv -- GPG_SIGNING_KEY | gpg --batch --passphrase-fd 3 --import 3<<< "$GPG_SIGNING_PASSWORD" + GPG_SIGNING_KEY_ID="$(gpg --with-colons --list-keys | awk -F : -- '/^pub:/ { getline; print "0x" substr($10, length($10) - 7) }')" + ./gradlew publish --no-configuration-cache + env: + SONATYPE_USERNAME: ${{ secrets.IMAGE_KIT_SONATYPE_USERNAME || secrets.SONATYPE_USERNAME }} + SONATYPE_PASSWORD: ${{ secrets.IMAGE_KIT_SONATYPE_PASSWORD || secrets.SONATYPE_PASSWORD }} + GPG_SIGNING_KEY: ${{ secrets.IMAGE_KIT_SONATYPE_GPG_SIGNING_KEY || secrets.GPG_SIGNING_KEY }} + GPG_SIGNING_PASSWORD: ${{ secrets.IMAGE_KIT_SONATYPE_GPG_SIGNING_PASSWORD || secrets.GPG_SIGNING_PASSWORD }} \ No newline at end of file diff --git a/.github/workflows/release-doctor.yml b/.github/workflows/release-doctor.yml new file mode 100644 index 0000000..4b394d2 --- /dev/null +++ b/.github/workflows/release-doctor.yml @@ -0,0 +1,24 @@ +name: Release Doctor +on: + pull_request: + branches: + - master + workflow_dispatch: + +jobs: + release_doctor: + name: release doctor + runs-on: ubuntu-latest + if: github.repository == 'imagekit-developer/imagekit-java' && (github.event_name == 'push' || github.event_name == 'workflow_dispatch' || startsWith(github.head_ref, 'release-please') || github.head_ref == 'next') + + steps: + - uses: actions/checkout@v4 + + - name: Check release environment + run: | + bash ./bin/check-release-environment + env: + SONATYPE_USERNAME: ${{ secrets.IMAGE_KIT_SONATYPE_USERNAME || secrets.SONATYPE_USERNAME }} + SONATYPE_PASSWORD: ${{ secrets.IMAGE_KIT_SONATYPE_PASSWORD || secrets.SONATYPE_PASSWORD }} + GPG_SIGNING_KEY: ${{ secrets.IMAGE_KIT_SONATYPE_GPG_SIGNING_KEY || secrets.GPG_SIGNING_KEY }} + GPG_SIGNING_PASSWORD: ${{ secrets.IMAGE_KIT_SONATYPE_GPG_SIGNING_PASSWORD || secrets.GPG_SIGNING_PASSWORD }} diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml deleted file mode 100644 index b1a3bc8..0000000 --- a/.github/workflows/test.yml +++ /dev/null @@ -1,22 +0,0 @@ -# This workflow will build a Java project with Gradle -# For more information see: https://help.github.com/actions/language-and-framework-guides/building-and-testing-java-with-gradle - -name: Java CI - -on: [push, pull_request] - -jobs: - build: - - runs-on: ubuntu-latest - - steps: - - uses: actions/checkout@v2 - - name: Set up JDK 1.8 - uses: actions/setup-java@v1 - with: - java-version: 1.8 - - name: Grant execute permission for gradlew - run: chmod +x gradlew - - name: Running Test Cases - run: ./gradlew imagekit-sdk:test diff --git a/.gitignore b/.gitignore index bc21173..b1346e6 100644 --- a/.gitignore +++ b/.gitignore @@ -1,10 +1,7 @@ -.idea -out/production +.prism.log .gradle -build -config.properties -.DS_Store -.project -.settings -bin -.classpath +.idea +.kotlin +build/ +codegen.log +kls_database.db diff --git a/.release-please-manifest.json b/.release-please-manifest.json new file mode 100644 index 0000000..3d2ac0b --- /dev/null +++ b/.release-please-manifest.json @@ -0,0 +1,3 @@ +{ + ".": "0.1.0" +} \ No newline at end of file diff --git a/.stats.yml b/.stats.yml new file mode 100644 index 0000000..bbfdcb4 --- /dev/null +++ b/.stats.yml @@ -0,0 +1,4 @@ +configured_endpoints: 42 +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/imagekit-inc%2Fimagekit-bc7c0d27962b30c19c778656988e154b54696819389289f34420a5e5fdfbd3b8.yml +openapi_spec_hash: 1bfde02a63416c036e9545927f727459 +config_hash: a652d68098d82eaf611a49507fb4b831 diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..c031daa --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,47 @@ +# Changelog + +## 0.1.0 (2025-09-04) + +Full Changelog: [v0.0.1...v0.1.0](https://github.com/imagekit-developer/imagekit-java/compare/v0.0.1...v0.1.0) + +### Features + +* **api:** add BaseWebhookEvent ([4ab06b0](https://github.com/imagekit-developer/imagekit-java/commit/4ab06b01316b114e526159de348b9d52fdd57567)) +* **api:** manual updates ([2ef93ad](https://github.com/imagekit-developer/imagekit-java/commit/2ef93ad3db97af5fef99687a4438c76e2220b384)) +* **api:** manual updates ([c6e61f8](https://github.com/imagekit-developer/imagekit-java/commit/c6e61f8ca6b3a9485ab15d0221842ef76b6cae32)) +* **api:** manual updates ([1c76234](https://github.com/imagekit-developer/imagekit-java/commit/1c762344ee41aa7099febdca72f368943ee8428b)) +* **api:** manual updates ([cd2b64e](https://github.com/imagekit-developer/imagekit-java/commit/cd2b64ef8d6324264a71321bb11a7849260d98fc)) +* **api:** manual updates ([1341b62](https://github.com/imagekit-developer/imagekit-java/commit/1341b6282b4a32013cb60f11ee0ec9aaef8acac4)) +* **api:** manual updates ([83ce070](https://github.com/imagekit-developer/imagekit-java/commit/83ce0707ff45a9daa97e12daa9ad050dcbab53f9)) +* **api:** manual updates ([d57885b](https://github.com/imagekit-developer/imagekit-java/commit/d57885b731de1837a7edcd3f6eab303db855475a)) +* **api:** manual updates ([74027ef](https://github.com/imagekit-developer/imagekit-java/commit/74027efe9095a5e650addddf064d6e3773413894)) +* **api:** manual updates ([76c5b5e](https://github.com/imagekit-developer/imagekit-java/commit/76c5b5e1fbc0ac3415d5e35febce642dd47cd0ab)) +* **api:** manual updates ([b462410](https://github.com/imagekit-developer/imagekit-java/commit/b46241040326016adf4ad220178ccf3221323f90)) +* **api:** manual updates ([cbbd424](https://github.com/imagekit-developer/imagekit-java/commit/cbbd424da5ebd388dd6e3d8af7e38b7633ed0604)) + + +### Bug Fixes + +* add one more method in multipartbuilder to build from json ([9dc2f89](https://github.com/imagekit-developer/imagekit-java/commit/9dc2f897ec7b9a1998d283359472b882cfb9ee68)) +* **ci:** use java-version 21 for publish step ([181fbe5](https://github.com/imagekit-developer/imagekit-java/commit/181fbe5360fbc5820cb9df684d242896ec146049)) + + +### Chores + +* added reauired constants ([85ffc4d](https://github.com/imagekit-developer/imagekit-java/commit/85ffc4d8ee3a39546f45c4abe5b26fc3a9628cfe)) +* ImageKit class added with all functionalities ([6edfbd1](https://github.com/imagekit-developer/imagekit-java/commit/6edfbd19d82826e76ed913512ef518d31859b440)) +* ImageKit Configuration class added ([3af7846](https://github.com/imagekit-developer/imagekit-java/commit/3af7846d0f91f43e63ac71c2d0f7f6b73ca3250d)) +* Initial setup ([c70634b](https://github.com/imagekit-developer/imagekit-java/commit/c70634b76b4a4f1299d73b2a6a20df128bf3c088)) +* response models, MultipartBuilder and RestClient created for file operations ([ed443a7](https://github.com/imagekit-developer/imagekit-java/commit/ed443a793f765f296ed51119656b017ab1dccfe3)) +* sample sdk running code added ([46e0c29](https://github.com/imagekit-developer/imagekit-java/commit/46e0c29bc2d3e6bfbf001870c11de08d9260e896)) +* sync repo ([05af7d5](https://github.com/imagekit-developer/imagekit-java/commit/05af7d57aab0174c720f1dd71e87d39f1197bfa1)) +* update SDK settings ([00f7055](https://github.com/imagekit-developer/imagekit-java/commit/00f705596f585c9020a4620a9675e733f28b8b1b)) +* url generation functionality and getAuthentication functionality implemented ([d8c2b5d](https://github.com/imagekit-developer/imagekit-java/commit/d8c2b5d7fe098da89e0ca2804a03032a8155ed17)) +* Utils class added ([fdfe731](https://github.com/imagekit-developer/imagekit-java/commit/fdfe73124974ade54e03705421149f89469be86d)) + + +### Build System + +* Test CI added ([16153cc](https://github.com/imagekit-developer/imagekit-java/commit/16153ccc9b7a49f7dc732974e0b4b384d8273ea2)) +* updating CI ([a14b7cc](https://github.com/imagekit-developer/imagekit-java/commit/a14b7cc70204cd8af648e3c3ac7664f3916850b1)) +* version and doc changed for expecting release of 1.0.0 ([0abfb43](https://github.com/imagekit-developer/imagekit-java/commit/0abfb433ef126b5e21acf8773733b1003153a7e4)) diff --git a/DEVELOPMENT.md b/DEVELOPMENT.md deleted file mode 100644 index f220036..0000000 --- a/DEVELOPMENT.md +++ /dev/null @@ -1,21 +0,0 @@ -# Development Guide - - -**1. To modify version open `imagekit-sdk/build.gradle` and change value of `version`.** - -**2. Run test cases** -```shell -./gradlew imagekit-sdk:test -``` - -**3. Clean cache of SDK** -```shell -./gradlew imagekit-sdk:clean -``` - -**4. Build SDK jar** -```shell script -./gradlew imagekit-sdk:build -``` -Then you will find `jar` inside `imagekit-sdk/build/libs/` with specific version name. Then you can share `jar` or upload `jar` to any java dependency repository. - diff --git a/LICENSE b/LICENSE index 2d96bbb..e7a4d16 100644 --- a/LICENSE +++ b/LICENSE @@ -1,21 +1,201 @@ -MIT License - -Copyright (c) 2020 Imagekit - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2025 Image Kit + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/README.md b/README.md index c608840..7880086 100644 --- a/README.md +++ b/README.md @@ -1,1209 +1,710 @@ -# ImageKit Java SDK - -[![Java CI](https://github.com/imagekit-developer/imagekit-java/workflows/Java%20CI/badge.svg)](https://github.com/imagekit-developer/imagekit-java) -[![Release](https://jitpack.io/v/com.github.imagekit-developer/imagekit-java.svg)](https://jitpack.io/#com.github.imagekit-developer/imagekit-java) -[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) -[![Twitter Follow](https://img.shields.io/twitter/follow/imagekitio?label=Follow&style=social)](https://twitter.com/ImagekitIo) - -Java SDK for [ImageKit.io](https://imagekit.io/) that implements the new APIs and interface for performing different file operations. - -ImageKit is complete media storage, optimization, and transformation solution that comes with an [image and video CDN](https://imagekit.io). It can be integrated with your existing infrastructure - storage like AWS S3, web servers, your CDN, and custom domain names, allowing you to deliver optimized images in minutes with minimal code changes. - -Table of contents - - * [Installation](#installation) - * [Initialization](#initialization) - * [Usage](#usage) - * [Versioning](#versioning) - * [URL generation](#url-generation) - * [File upload](#file-upload) - * [File management](#file-management) - * [Utility functions](#utility-functions) - * [Handling errors](#handling-errors) - * [Support](#support) - * [Links](#links) - -## Installation +# Image Kit Java API Library -### Requirements + -- Java 1.8 or later +[![Maven Central](https://img.shields.io/maven-central/v/com.imagekit.api/image-kit-java)](https://central.sonatype.com/artifact/com.imagekit.api/image-kit-java/0.1.0) +[![javadoc](https://javadoc.io/badge2/com.imagekit.api/image-kit-java/0.1.0/javadoc.svg)](https://javadoc.io/doc/com.imagekit.api/image-kit-java/0.1.0) -### Gradle users -Step 1. Add the JitPack repository to your build file -``` -allprojects { - repositories { - ... - maven { url 'https://jitpack.io' } - } -} -``` -Step 2. Add the dependency on the project's `build.gradle`: -``` -dependencies { - implementation 'com.github.imagekit-developer:imagekit-java:2.0.0' -} -``` -### Maven users -Step 1. Add the JitPack repository to your build file -``` - - - jitpack.io - https://jitpack.io - - -``` -Step 2. Add the dependency in the POM file: -``` - - com.github.imagekit-developer - imagekit-java - 2.0.0 - -``` + -## Initialization +The Image Kit Java SDK provides convenient access to the [Image Kit REST API](https://imagekit.io/docs) from applications written in Java. -**Step 1**. Create a `config.properties` file inside `src/main/resources` of your project. And put essential values of keys [UrlEndpoint, PrivateKey, PublicKey], no need to use quote(`'` or `"`) in values. +It is generated with [Stainless](https://www.stainless.com/). - You can get the value of [URL-endpoint](https://imagekit.io/dashboard#url-endpoints) from your ImageKit dashboard. API keys can be obtained from the [developer](https://imagekit.io/dashboard/developer/api-keys) section in your ImageKit dashboard. + -```editorconfig -# Put essential values of keys [UrlEndpoint, PrivateKey, PublicKey] -UrlEndpoint=your_public_api_key -PrivateKey=your_private_api_key -PublicKey=https://ik.imagekit.io/imagekit_id/ -``` +The REST API documentation can be found on [imagekit.io](https://imagekit.io/docs). Javadocs are available on [javadoc.io](https://javadoc.io/doc/com.imagekit.api/image-kit-java/0.1.0). -**Step 2**. Then you need to initialize ImageKit with that configuration. - - ```java -import io.imagekit.sdk.ImageKit; -import io.imagekit.sdk.config.Configuration; -import io.imagekit.sdk.utils.Utils; -class App { - public static void main(String[] args){ - ImageKit imageKit=ImageKit.getInstance(); - Configuration config=Utils.getSystemConfig(App.class); - imageKit.setConfig(config); - } -} -``` + -or - - ```java -import io.imagekit.sdk.ImageKit; -import io.imagekit.sdk.config.Configuration; -import io.imagekit.sdk.utils.Utils; -class App { - public static void main(String[] args) { - ImageKit imageKit = ImageKit.getInstance(); - Configuration config = new Configuration("your_public_key", "your_private_key", "your_url_endpoint"); - imageKit.setConfig(config); - } -} -``` +## Installation -## Usage -You can use this Java SDK for 3 different kinds of methods: + -* URL generation -* file upload -* file management +### Gradle -The usage of the SDK has been explained below. +```kotlin +implementation("com.imagekit.api:image-kit-java:0.1.0") +``` -## Change log -This document presents a list of changes that break the existing functionality of previous versions. We try our best to minimize these disruptions, but sometimes they are unavoidable and will be in major versions. +### Maven -### Breaking History: +```xml + + com.imagekit.api + image-kit-java + 0.1.0 + +``` -Changes from 1.0.3 -> 2.0.0 are listed below + -1. Result `raw` object and `getMap()` properties: +## Requirements -**What changed** -- `raw` and `getMap()` has been deprecated. +This library requires Java 8 or later. -**Who is affected?** -- This affects any development that uses the `raw` or `getMap()` from the response object of APIs and Result object. +## Usage -**How should I update my code?** -- If you still need to use `raw` and `getMap()`, do this `result.getResponseMetaData().getRaw()`. - -2. Result object `message` and `isSuccessful` boolean properties: +```java +import com.imagekit.api.client.ImageKitClient; +import com.imagekit.api.client.okhttp.ImageKitOkHttpClient; +import com.imagekit.api.models.files.FileUploadParams; +import com.imagekit.api.models.files.FileUploadResponse; +import java.io.ByteArrayInputStream; -**What changed** -- `message` and `isSuccessful` have been replaced with custom exceptions according to response code. +// Configures using the `imagekit.imagekitPrivateApiKey`, `imagekit.optionalImagekitIgnoresThis`, `imagekit.imagekitWebhookSecret` and `imagekit.baseUrl` system properties +// Or configures using the `IMAGEKIT_PRIVATE_API_KEY`, `OPTIONAL_IMAGEKIT_IGNORES_THIS`, `IMAGEKIT_WEBHOOK_SECRET` and `IMAGE_KIT_BASE_URL` environment variables +ImageKitClient client = ImageKitOkHttpClient.fromEnv(); -**Who is affected?** -- This affects any development that uses the `message` or `isSuccessful` from response object of APIs that is Result object. +FileUploadParams params = FileUploadParams.builder() + .file(ByteArrayInputStream("https://www.example.com/public-url.jpg".getBytes())) + .fileName("file-name.jpg") + .build(); +FileUploadResponse response = client.files().upload(params); +``` -**How should I update my code?** -- If you still need to use `message` it will be there in the custom exceptions that could be raised when calling the various API methods. `isSuccessful` can be understood to be `true` if the API method doesn't throw any exception. +## Client configuration +Configure the client using system properties or environment variables: -## URL generation +```java +import com.imagekit.api.client.ImageKitClient; +import com.imagekit.api.client.okhttp.ImageKitOkHttpClient; -**1. Using image path and URL-endpoint** +// Configures using the `imagekit.imagekitPrivateApiKey`, `imagekit.optionalImagekitIgnoresThis`, `imagekit.imagekitWebhookSecret` and `imagekit.baseUrl` system properties +// Or configures using the `IMAGEKIT_PRIVATE_API_KEY`, `OPTIONAL_IMAGEKIT_IGNORES_THIS`, `IMAGEKIT_WEBHOOK_SECRET` and `IMAGE_KIT_BASE_URL` environment variables +ImageKitClient client = ImageKitOkHttpClient.fromEnv(); +``` -This method allows you to create an URL to access a file using the relative file path and the ImageKit URL endpoint (`urlEndpoint`). The file can be an image, video, or any other static file supported by ImageKit. +Or manually: ```java -Map queryParam=new HashMap<>(); -queryParam.put("v","123"); - -List> transformation=new ArrayList>(); -Map scale=new HashMap<>(); -scale.put("height","600"); -scale.put("width","400"); -scale.put("raw", "ar-4-3,q-40"); -transformation.add(scale); - -Map options=new HashMap(); -options.put("urlEndpoint","https://ik.imagekit.io/your_imagekit_id/"); -options.put("path","/default-image.jpg"); -options.put("transformation", transformation); - -String url = ImageKit.getInstance().getUrl(options); -``` -The result in a URL like -``` -https://ik.imagekit.io/your_imagekit_id/tr:w-400,h-600/default-image.jpg?v=123 +import com.imagekit.api.client.ImageKitClient; +import com.imagekit.api.client.okhttp.ImageKitOkHttpClient; + +ImageKitClient client = ImageKitOkHttpClient.builder() + .privateApiKey("My Private API Key") + .password("My Password") + .build(); ``` -**2. Using full image URL** -This method allows you to add transformation parameters to an absolute URL. For example, if you have configured a custom CNAME and have absolute asset URLs in your database or CMS, you will often need this. +Or using a combination of the two approaches: ```java -List> transformation=new ArrayList>(); -Map scale=new HashMap<>(); -scale.put("height","600"); -scale.put("width","400"); -scale.put("raw", "ar-4-3,q-40"); -transformation.add(scale); - -Map options=new HashMap(); -options.put("src","https://ik.imagekit.io/your_imagekit_id/default-image.jpg"); -options.put("transformation", transformation); - -String url = ImageKit.getInstance().getUrl(options); +import com.imagekit.api.client.ImageKitClient; +import com.imagekit.api.client.okhttp.ImageKitOkHttpClient; + +ImageKitClient client = ImageKitOkHttpClient.builder() + // Configures using the `imagekit.imagekitPrivateApiKey`, `imagekit.optionalImagekitIgnoresThis`, `imagekit.imagekitWebhookSecret` and `imagekit.baseUrl` system properties + // Or configures using the `IMAGEKIT_PRIVATE_API_KEY`, `OPTIONAL_IMAGEKIT_IGNORES_THIS`, `IMAGEKIT_WEBHOOK_SECRET` and `IMAGE_KIT_BASE_URL` environment variables + .fromEnv() + .privateApiKey("My Private API Key") + .build(); ``` -The results in a URL like +See this table for the available options: -``` -https://ik.imagekit.io/your_imagekit_id/default-image.jpg?tr=w-400,h-600 -``` +| Setter | System property | Environment variable | Required | Default value | +| --------------- | -------------------------------------- | -------------------------------- | -------- | --------------------------- | +| `privateApiKey` | `imagekit.imagekitPrivateApiKey` | `IMAGEKIT_PRIVATE_API_KEY` | true | - | +| `password` | `imagekit.optionalImagekitIgnoresThis` | `OPTIONAL_IMAGEKIT_IGNORES_THIS` | false | `"do_not_set"` | +| `webhookSecret` | `imagekit.imagekitWebhookSecret` | `IMAGEKIT_WEBHOOK_SECRET` | false | - | +| `baseUrl` | `imagekit.baseUrl` | `IMAGE_KIT_BASE_URL` | true | `"https://api.imagekit.io"` | -The ```.getUrl()``` method accepts the following parameters +System properties take precedence over environment variables. -| Option | Description | -| :---------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| urlEndpoint | Optional. `(Type: String)` The base URL to be appended before the path of the image. If not specified, the URL Endpoint specified during SDK initialization is used. For example, https://ik.imagekit.io/your_imagekit_id/ | -| path | Conditional. `(Type: String)` This is the path at which the image exists. For example, `/path/to/image.jpg`. Either the `path` or `src` parameter needs to be specified for URL generation. | -| src | Conditional. `(Type: String)` This is the complete URL of an image already mapped to ImageKit. For example, `https://ik.imagekit.io/your_imagekit_id/endpoint/path/to/image.jpg`. Either the `path` or `src` parameter needs to be specified for URL generation. | -| transformation | Optional. `(Type: List>)` An array of objects specifying the transformation to be applied in the URL. The transformation name and the value should be specified as a key-value pair in the object. Different steps of a [chained transformation](https://docs.imagekit.io/features/image-transformations/chained-transformations) can be specified as different objects of the array. The complete list of supported transformations in the SDK and some examples of using them are given later. If you use a transformation name that is not specified in the SDK, it gets applied as it is in the URL. | -| transformationPosition | Optional. `(Type: String)` Default value is `path` that places the transformation string as a path parameter in the URL. It can also be specified as `query`, which adds the transformation string as the query parameter `tr` in the URL. If you use the `src` parameter to create the URL, then the transformation string is always added as a query parameter. | -| queryParameters | Optional. `(Type: Map)` These are the other query parameters that you want to add to the final URL. These can be any query parameters and not necessarily related to ImageKit. Especially useful if you want to add some versioning parameters to your URLs. | -| signed | Optional. `(Type: Boolean)` Default is `false`. If set to `true`, the SDK generates a signed image URL adding the image signature to the image URL. This can only be used if you create the URL with the `url_endpoint` and `path` parameters and not with the `src` parameter. | -| expireSeconds | Optional. `(Type: Integer)` Meant to be used along with the `signed` parameter to specify the time in seconds from now when the URL should expire. If specified, the URL contains the expiry timestamp in the URL, and the image signature is modified accordingly. | +> [!TIP] +> Don't create more than one client in the same application. Each client has a connection pool and +> thread pools, which are more efficient to share between requests. +### Modifying configuration -## Examples of generating URLs -**1. Chained Transformations as a query parameter** +To temporarily use a modified client configuration, while reusing the same connection and thread pools, call `withOptions()` on any client or service: ```java -List> transformation=new ArrayList>(); -Map scale=new HashMap<>(); -scale.put("height","300"); -scale.put("width","400"); -transformation.add(scale); -Map rotate=new HashMap<>(); -rotate.put("rotation","90"); -transformation.add(rotate); - -Map options=new HashMap(); -options.put("path","/default-image.jpg"); -options.put("transformationPosition","query"); -options.put("transformation", transformation); - -String url = ImageKit.getInstance().getUrl(options); -``` +import com.imagekit.api.client.ImageKitClient; -Sample Result URL - -``` -https://ik.imagekit.io/your_imagekit_id/default-image.jpg?tr=h-300&w-400:rt-90 +ImageKitClient clientWithOptions = client.withOptions(optionsBuilder -> { + optionsBuilder.baseUrl("https://example.com"); + optionsBuilder.maxRetries(42); +}); ``` -**2. Sharpening and contrast transform and a progressive JPG image** +The `withOptions()` method does not affect the original client or service. -There are some transforms like [Sharpening](https://docs.imagekit.io/features/image-transformations/image-enhancement-and-color-manipulation) -that can be added to the URL with or without any other value. To use such transforms without specifying a value, specify -the value as "-" in the transformation object. Otherwise, specify the value that you want to be -added to this transformation. +## Requests and responses -```java -List> transformation=new ArrayList>(); -Map scale=new HashMap<>(); -scale.put("format","jpg"); -scale.put("progressive","true"); -scale.put("effect_sharpen","-"); -scale.put("effect_contrast","1"); -transformation.add(scale); - -Map options=new HashMap(); -options.put("path","/default-image.jpg"); -options.put("transformation", transformation); -String url = ImageKit.getInstance().getUrl(options); -``` - -Note that because the `src` parameter was used, the transformation string gets added as a query parameter. - -``` -https://ik.imagekit.io/your_imagekit_id/default-image.jpg?tr=f-jpg&pr-true&e-sharpen&e-contrast-1 -``` +To send a request to the Image Kit API, build an instance of some `Params` class and pass it to the corresponding client method. When the response is received, it will be deserialized into an instance of a Java class. -**3. Signed URL that expires in 300 seconds with the default URL endpoint and other query parameters** +For example, `client.files().upload(...)` should be called with an instance of `FileUploadParams`, and it will return an instance of `FileUploadResponse`. -```java -List> transformation=new ArrayList>(); -Map scale=new HashMap<>(); -scale.put("height","600"); -scale.put("width","400"); - -transformation.add(format); - -Map options=new HashMap(); -options.put("path","/default-image.jpg"); -options.put("signed",true); -options.put("expireSeconds",300); -String url = ImageKit.getInstance().getUrl(options); -``` -**Sample Result URL** -``` -https://ik.imagekit.io/your_imagekit_id/tr:h-600,w-400/default-image.jpg?ik-t=1567358667&ik-s=f2c7cdacbe7707b71a83d49cf1c6110e3d701054 -``` +## Immutability -**4. Adding overlays** +Each class in the SDK has an associated [builder](https://blogs.oracle.com/javamagazine/post/exploring-joshua-blochs-builder-design-pattern-in-java) or factory method for constructing it. -ImageKit.io enables you to apply overlays to [images](https://docs.imagekit.io/features/image-transformations/overlay-using-layers) and [videos](https://docs.imagekit.io/features/video-transformation/overlay) using the raw parameter with the concept of [layers](https://docs.imagekit.io/features/image-transformations/overlay-using-layers#layers). The raw parameter facilitates incorporating transformations directly in the URL. A layer is a distinct type of transformation that allows you to define an asset to serve as an overlay, along with its positioning and additional transformations. +Each class is [immutable](https://docs.oracle.com/javase/tutorial/essential/concurrency/immutable.html) once constructed. If the class has an associated builder, then it has a `toBuilder()` method, which can be used to convert it back to a builder for making a modified copy. -**Text as overlays** +Because each class is immutable, builder modification will _never_ affect already built class instances. -You can add any text string over a base video or image using a text layer (l-text). +## Asynchronous execution -For example: +The default client is synchronous. To switch to asynchronous execution, call the `async()` method: ```java -List> transformation=new ArrayList>(); -Map scale=new HashMap<>(); -scale.put("height","300"); -scale.put("width","400"); -scale.put("raw", "l-text,i-Imagekit,fs-50,l-end"); -transformation.add(scale); - -Map options=new HashMap(); -options.put("src","https://ik.imagekit.io/your_imagekit_id/default-image.jpg"); -options.put("transformation", transformation); - -String url = ImageKit.getInstance().getUrl(options); -``` -**Sample Result URL** -``` -https://ik.imagekit.io/your_imagekit_id/default-image.jpg?tr=h-300,w-400,l-text,i-Imagekit,fs-50,l-end -``` - -**Image as overlays** - -You can add an image over a base video or image using an image layer (l-image). +import com.imagekit.api.client.ImageKitClient; +import com.imagekit.api.client.okhttp.ImageKitOkHttpClient; +import com.imagekit.api.models.files.FileUploadParams; +import com.imagekit.api.models.files.FileUploadResponse; +import java.io.ByteArrayInputStream; +import java.util.concurrent.CompletableFuture; -For example: +// Configures using the `imagekit.imagekitPrivateApiKey`, `imagekit.optionalImagekitIgnoresThis`, `imagekit.imagekitWebhookSecret` and `imagekit.baseUrl` system properties +// Or configures using the `IMAGEKIT_PRIVATE_API_KEY`, `OPTIONAL_IMAGEKIT_IGNORES_THIS`, `IMAGEKIT_WEBHOOK_SECRET` and `IMAGE_KIT_BASE_URL` environment variables +ImageKitClient client = ImageKitOkHttpClient.fromEnv(); -```java -List> transformation=new ArrayList>(); -Map scale=new HashMap<>(); -scale.put("height","300"); -scale.put("width","400"); -scale.put("raw", "l-image,i-default-image.jpg,w-100,b-10_CDDC39,l-end"); -transformation.add(scale); - -Map options=new HashMap(); -options.put("src","https://ik.imagekit.io/your_imagekit_id/default-image.jpg"); -options.put("transformation", transformation); - -String url = ImageKit.getInstance().getUrl(options); -``` -**Sample Result URL** -``` -https://ik.imagekit.io/your_imagekit_id/default-image.jpg?tr=h-300,w-400,l-image,i-default-image.jpg,w-100,b-10_CDDC39,l-end +FileUploadParams params = FileUploadParams.builder() + .file(ByteArrayInputStream("https://www.example.com/public-url.jpg".getBytes())) + .fileName("file-name.jpg") + .build(); +CompletableFuture response = client.async().files().upload(params); ``` -**Solid color blocks as overlays** +Or create an asynchronous client from the beginning: -You can add solid color blocks over a base video or image using an image layer (l-image). +```java +import com.imagekit.api.client.ImageKitClientAsync; +import com.imagekit.api.client.okhttp.ImageKitOkHttpClientAsync; +import com.imagekit.api.models.files.FileUploadParams; +import com.imagekit.api.models.files.FileUploadResponse; +import java.io.ByteArrayInputStream; +import java.util.concurrent.CompletableFuture; -For example: +// Configures using the `imagekit.imagekitPrivateApiKey`, `imagekit.optionalImagekitIgnoresThis`, `imagekit.imagekitWebhookSecret` and `imagekit.baseUrl` system properties +// Or configures using the `IMAGEKIT_PRIVATE_API_KEY`, `OPTIONAL_IMAGEKIT_IGNORES_THIS`, `IMAGEKIT_WEBHOOK_SECRET` and `IMAGE_KIT_BASE_URL` environment variables +ImageKitClientAsync client = ImageKitOkHttpClientAsync.fromEnv(); -```java -List> transformation=new ArrayList>(); -Map scale=new HashMap<>(); -scale.put("height","300"); -scale.put("width","400"); -scale.put("raw", "l-image,i-ik_canvas,bg-FF0000,w-300,h-100,l-end"); -transformation.add(scale); - -Map options=new HashMap(); -options.put("src","https://ik.imagekit.io/your_imagekit_id/img/sample-video.mp4"); -options.put("transformation", transformation); - -String url = ImageKit.getInstance().getUrl(options); -``` -**Sample Result URL** -``` -https://ik.imagekit.io/your_imagekit_id/img/sample-video.mp4?tr=h-300,w-400,l-image,i-ik_canvas,bg-FF0000,w-300,h-100,l-end +FileUploadParams params = FileUploadParams.builder() + .file(ByteArrayInputStream("https://www.example.com/public-url.jpg".getBytes())) + .fileName("file-name.jpg") + .build(); +CompletableFuture response = client.files().upload(params); ``` -**List of transformations** - -See the complete list of [image](https://docs.imagekit.io/features/image-transformations) and [video](https://docs.imagekit.io/features/video-transformation) transformations supported in ImageKit. The SDK gives a name to each transformation parameter e.g. `height` for `h` and `width` for `w` parameter. It makes your code more readable. If the property does not match any of the following supported options, it is added as it is. - -If you want to generate transformations in your application and add them to the URL as it is, use the `raw` parameter. - -| Supported Transformation Name | Translates to parameter | -|-------------------------------|-------------------------| -| height | h | -| width | w | -| aspectRatio | ar | -| quality | q | -| crop | c | -| cropMode | cm | -| x | x | -| y | y | -| focus | fo | -| format | f | -| radius | r | -| background | bg | -| border | b | -| rotation | rt | -| blur | bl | -| named | n | -| progressive | pr | -| lossless | lo | -| trim | t | -| metadata | md | -| colorProfile | cp | -| defaultImage | di | -| dpr | dpr | -| effectSharpen | e-sharpen | -| effectUSM | e-usm | -| effectContrast | e-contrast | -| effectGray | e-grayscale | -| original | orig | -| raw | `replaced by the parameter value` | - - -## File Upload - -The SDK provides a simple interface using the `.upload()` method to upload files to the ImageKit Media library. It -accepts an object of the `FileCreateRequest` class that contains all the parameters supported by the [ImageKit Upload API](https://docs.imagekit.io/api-reference/upload-file-api/server-side-file-upload). - -The constructor `FileCreateRequest` class requires `file` as (URL/Base64/Byte Array) and `file_name`. The method returns object of `Result` in case of successful, or it will throw custom exception in case of failure. - -Sample usage +The asynchronous client supports the same options as the synchronous one, except most methods return `CompletableFuture`s. -```java -String filePath = "your-local-file-path"; -String base64 = Utils.fileToBase64(new File(filePath)); -FileCreateRequest fileCreateRequest = new FileCreateRequest(base64, "file_name.jpg"); -String customCoordinates = "10,10,20,20"; -fileCreateRequest.setCustomCoordinates(customCoordinates); // optional -List tags = new ArrayList<>(); -tags.add("Sample-tag"); -tags.add("T-shirt"); -fileCreateRequest.setTags(tags); // optional -fileCreateRequest.setFileName("override_file_name.jpg"); // optional -fileCreateRequest.setFolder("sample-folder/nested-folder"); // optional -fileCreateRequest.setPrivateFile(false); // optional -fileCreateRequest.setUseUniqueFileName(true); // optional -List responseFields=new ArrayList<>(); -responseFields.add("tags"); -responseFields.add("customCoordinates"); -fileCreateRequest.setResponseFields(responseFields); // optional -JsonObject innerObject1 = new JsonObject(); -innerObject1.addProperty("name", "remove-bg"); -innerObject1.add("options", optionsInnerObject); -JsonObject innerObject2 = new JsonObject(); -innerObject2.addProperty("name", "google-auto-tagging"); -innerObject2.addProperty("minConfidence", 10); -innerObject2.addProperty("maxTags", 5); -JsonArray jsonArray = new JsonArray(); -jsonArray.add(innerObject1); -jsonArray.add(innerObject2); -fileCreateRequest.setExtensions(jsonArray); // optional -fileCreateRequest.setWebhookUrl("Your webhook url"); // optional -fileCreateRequest.setOverwriteFile(true); // optional -fileCreateRequest.setOverwriteAITags(true); // optional -fileCreateRequest.setOverwriteTags(true); // optional -fileCreateRequest.setOverwriteCustomMetadata(true); // optional -JsonObject jsonObjectCustomMetadata = new JsonObject(); -jsonObjectCustomMetadata.addProperty("test1", 10); -fileCreateRequest.setCustomMetadata(jsonObjectCustomMetadata); // optional -Result result = ImageKit.getInstance().upload(fileCreateRequest); -System.out.println("======FINAL RESULT======="); -System.out.println(result); -System.out.println("Raw Response:"); -System.out.println(result.getResponseMetaData().getRaw()); -System.out.println("Map Response:"); -System.out.println(result.getResponseMetaData().getMap()); -``` +## File uploads -If the upload is successful, result will be there as an object of `Result` class that contains the same all the parameters received from ImageKit's servers. +The SDK defines methods that accept files. -If the upload fails, custom exception is thrown and `getMessage()` can be called to get the error message received from ImageKit's servers. +To upload a file, pass a [`Path`](https://docs.oracle.com/javase/8/docs/api/java/nio/file/Path.html): +```java +import com.imagekit.api.models.files.FileUploadParams; +import com.imagekit.api.models.files.FileUploadResponse; +import java.nio.file.Paths; -## File Management +FileUploadParams params = FileUploadParams.builder() + .fileName("fileName") + .file(Paths.get("/path/to/file")) + .build(); +FileUploadResponse response = client.files().upload(params); +``` -The SDK provides a simple interface for all the [media APIs mentioned here](https://docs.imagekit.io/api-reference/media-api) to manage your files. This also returns `error` and `result`, the error will be `None` if API succeeds. +Or an arbitrary [`InputStream`](https://docs.oracle.com/javase/8/docs/api/java/io/InputStream.html): -**1. List & Search Files** +```java +import com.imagekit.api.models.files.FileUploadParams; +import com.imagekit.api.models.files.FileUploadResponse; +import java.net.URL; -Accepts an object of class `GetFileListRequest` specifying the parameters to be used to list and search files. All parameters specified in the [documentation here](https://docs.imagekit.io/api-reference/media-api/list-and-search-files) can be passed via their setter functions to get the results. +FileUploadParams params = FileUploadParams.builder() + .fileName("fileName") + .file(new URL("https://example.com//path/to/file").openStream()) + .build(); +FileUploadResponse response = client.files().upload(params); +``` -#### Applying Filters -Filter out the files by specifying the parameters. +Or a `byte[]` array: ```java -String[] tags = new String[3]; -tags[0] = "Software"; -tags[1] = "Developer"; -tags[2] = "Engineer"; -GetFileListRequest getFileListRequest = new GetFileListRequest(); -getFileListRequest.setType("file"); -getFileListRequest.setSort("ASC_CREATED"); -getFileListRequest.setPath("/"); -getFileListRequest.setFileType("all"); -getFileListRequest.setLimit("4"); -getFileListRequest.setSkip("1"); -getFileListRequest.setTags(tags); -ResultList resultList = ImageKit.getInstance().getFileList(getFileListRequest); -System.out.println("======FINAL RESULT======="); -System.out.println(resultList); -System.out.println("Raw Response:"); -System.out.println(resultList.getResponseMetaData().getRaw()); -System.out.println("Map Response:"); -System.out.println(resultList.getResponseMetaData().getMap()); +import com.imagekit.api.models.files.FileUploadParams; +import com.imagekit.api.models.files.FileUploadResponse; + +FileUploadParams params = FileUploadParams.builder() + .fileName("fileName") + .file("content".getBytes()) + .build(); +FileUploadResponse response = client.files().upload(params); ``` -#### Advance Search -In addition, you can fine-tune your query by specifying various filters by generating a query string in a Lucene-like syntax and setting this generated string to the `GetFileListRequest` object using `setSearchQuery` function. +Note that when passing a non-`Path` its filename is unknown so it will not be included in the request. To manually set a filename, pass a [`MultipartField`](image-kit-java-core/src/main/kotlin/com/imagekit/api/core/Values.kt): ```java -GetFileListRequest getFileListRequest = new GetFileListRequest(); -getFileListRequest.setSearchQuery("createdAt >= '2d' OR size < '2mb' OR format='png'"); -ResultList resultList = ImageKit.getInstance().getFileList(getFileListRequest); -System.out.println("======FINAL RESULT======="); -System.out.println(resultList); -System.out.println("Raw Response:"); -System.out.println(resultList.getResponseMetaData().getRaw()); -System.out.println("Map Response:"); -System.out.println(resultList.getResponseMetaData().getMap()); +import com.imagekit.api.core.MultipartField; +import com.imagekit.api.models.files.FileUploadParams; +import com.imagekit.api.models.files.FileUploadResponse; +import java.io.InputStream; +import java.net.URL; + +FileUploadParams params = FileUploadParams.builder() + .fileName("fileName") + .file(MultipartField.builder() + .value(new URL("https://example.com//path/to/file").openStream()) + .filename("/path/to/file") + .build()) + .build(); +FileUploadResponse response = client.files().upload(params); ``` -Detailed documentation can be found here for [advance search queries](https://docs.imagekit.io/api-reference/media-api/list-and-search-files#advanced-search-queries). +## Raw responses -**2. Get File Details** +The SDK defines methods that deserialize responses into instances of Java classes. However, these methods don't provide access to the response headers, status code, or the raw response body. -Accepts the file ID and fetches the details as per the [API documentation here](https://docs.imagekit.io/api-reference/media-api/get-file-details) +To access this data, prefix any HTTP method call on a client or service with `withRawResponse()`: ```java -String fileId="your-file-id"; -Result result=ImageKit.getInstance().getFileDetail(fileId); -System.out.println("======FINAL RESULT======="); -System.out.println(result); -System.out.println("Raw Response:"); -System.out.println(result.getResponseMetaData().getRaw()); -System.out.println("Map Response:"); -System.out.println(result.getResponseMetaData().getMap()); -``` +import com.imagekit.api.core.http.Headers; +import com.imagekit.api.core.http.HttpResponseFor; +import com.imagekit.api.models.files.FileUploadParams; +import com.imagekit.api.models.files.FileUploadResponse; +import java.io.ByteArrayInputStream; -**3. Get File Versions** +FileUploadParams params = FileUploadParams.builder() + .file(ByteArrayInputStream("https://www.example.com/public-url.jpg".getBytes())) + .fileName("file-name.jpg") + .build(); +HttpResponseFor response = client.files().withRawResponse().upload(params); -Accepts the file ID and fetches the details as per the [API documentation here](https://docs.imagekit.io/api-reference/media-api/get-file-versions). - -```java -String fileId = "62a04834c10d49825c6de9e8"; -ResultFileVersions resultFileVersions = ImageKit.getInstance().getFileVersions(fileId); -System.out.println("======FINAL RESULT======="); -System.out.println(resultFileVersions); -System.out.println("Raw Response:"); -System.out.println(resultFileVersions.getResponseMetaData().getRaw()); -System.out.println("Map Response:"); -System.out.println(resultFileVersions.getResponseMetaData().getMap()); +int statusCode = response.statusCode(); +Headers headers = response.headers(); ``` -**4. Get File Version details** - -Accepts the file ID and version ID and fetches the details as per the [API documentation here](https://docs.imagekit.io/api-reference/media-api/get-file-version-details). +You can still deserialize the response into an instance of a Java class if needed: ```java -String fileId = "62a04834c10d49825c6de9e8"; -String versionId = "62a04834c10d49825c6de9e8"; -ResultFileVersionDetails resultFileVersionDetails = ImageKit.getInstance().getFileVersionDetails(fileId, versionId); -System.out.println("======FINAL RESULT======="); -System.out.println(resultFileVersionDetails); -System.out.println("Raw Response:"); -System.out.println(resultFileVersionDetails.getResponseMetaData().getRaw()); -System.out.println("Map Response:"); -System.out.println(resultFileVersionDetails.getResponseMetaData().getMap()); +import com.imagekit.api.models.files.FileUploadResponse; + +FileUploadResponse parsedResponse = response.parse(); ``` -**5. Update File Details** +## Error handling -Accepts an object of class `FileUpdateRequest` specifying the parameters to be used to update file details. All parameters specified in the [documentation here] (https://docs.imagekit.io/api-reference/media-api/update-file-details) can be passed via their setter functions to get the results. +The SDK throws custom unchecked exception types: -```java -List tags = new ArrayList<>(); -tags.add("Software"); -tags.add("Developer"); -tags.add("Engineer"); - -List aiTags = new ArrayList<>(); -aiTags.add("Plant"); -FileUpdateRequest fileUpdateRequest = new FileUpdateRequest("fileId"); -fileUpdateRequest.setTags(tags); -fileUpdateRequest.setRemoveAITags(aiTags); -fileUpdateRequest.setWebhookUrl("https://webhook.site/c78d617f-33bc-40d9-9e61-608999721e2e"); - -JsonObject optionsInnerObject = new JsonObject(); -optionsInnerObject.addProperty("add_shadow", true); -optionsInnerObject.addProperty("bg_color", "yellow"); -JsonObject innerObject1 = new JsonObject(); -innerObject1.addProperty("name", "remove-bg"); -innerObject1.add("options", optionsInnerObject); -JsonObject innerObject2 = new JsonObject(); -innerObject2.addProperty("name", "google-auto-tagging"); -innerObject2.addProperty("minConfidence", 15); -innerObject2.addProperty("maxTags", 20); -JsonArray jsonArray = new JsonArray(); -jsonArray.add(innerObject1); -jsonArray.add(innerObject2); - -fileUpdateRequest.setExtensions(jsonArray); -fileUpdateRequest.setCustomCoordinates("10,10,40,40"); -JsonObject jsonObjectCustomMetadata = new JsonObject(); -jsonObjectCustomMetadata.addProperty("test10", 11); -fileUpdateRequest.setCustomMetadata(jsonObjectCustomMetadata); -Result result=ImageKit.getInstance().updateFileDetail(fileUpdateRequest); -System.out.println("======FINAL RESULT======="); -System.out.println(result); -System.out.println("Raw Response:"); -System.out.println(result.getResponseMetaData().getRaw()); -System.out.println("Map Response:"); -System.out.println(result.getResponseMetaData().getMap()); -``` +- [`ImageKitServiceException`](image-kit-java-core/src/main/kotlin/com/imagekit/api/errors/ImageKitServiceException.kt): Base class for HTTP errors. See this table for which exception subclass is thrown for each HTTP status code: -**6. Add tags** + | Status | Exception | + | ------ | ------------------------------------------------------------------------------------------------------------------------------- | + | 400 | [`BadRequestException`](image-kit-java-core/src/main/kotlin/com/imagekit/api/errors/BadRequestException.kt) | + | 401 | [`UnauthorizedException`](image-kit-java-core/src/main/kotlin/com/imagekit/api/errors/UnauthorizedException.kt) | + | 403 | [`PermissionDeniedException`](image-kit-java-core/src/main/kotlin/com/imagekit/api/errors/PermissionDeniedException.kt) | + | 404 | [`NotFoundException`](image-kit-java-core/src/main/kotlin/com/imagekit/api/errors/NotFoundException.kt) | + | 422 | [`UnprocessableEntityException`](image-kit-java-core/src/main/kotlin/com/imagekit/api/errors/UnprocessableEntityException.kt) | + | 429 | [`RateLimitException`](image-kit-java-core/src/main/kotlin/com/imagekit/api/errors/RateLimitException.kt) | + | 5xx | [`InternalServerException`](image-kit-java-core/src/main/kotlin/com/imagekit/api/errors/InternalServerException.kt) | + | others | [`UnexpectedStatusCodeException`](image-kit-java-core/src/main/kotlin/com/imagekit/api/errors/UnexpectedStatusCodeException.kt) | -Accepts an object of class `TagsRequest` specifying the parameters to be used to add tags. All parameters specified in the [documentation here](https://docs.imagekit.io/api-reference/media-api/add-tags-bulk) can be passed via their setter functions to get the results. +- [`ImageKitIoException`](image-kit-java-core/src/main/kotlin/com/imagekit/api/errors/ImageKitIoException.kt): I/O networking errors. -```java -List fileIds = new ArrayList<>(); -fileIds.add("FileId"); -List tags = new ArrayList<>(); -tags.add("tag-to-add-1"); -tags.add("tag-to-add-2"); -ResultTags resultTags=ImageKit.getInstance().addTags(new TagsRequest(fileIds, tags)); -System.out.println("======FINAL RESULT======="); -System.out.println(resultTags); -System.out.println("Raw Response:"); -System.out.println(resultTags.getResponseMetaData().getRaw()); -System.out.println("Map Response:"); -System.out.println(resultTags.getResponseMetaData().getMap()); -``` +- [`ImageKitRetryableException`](image-kit-java-core/src/main/kotlin/com/imagekit/api/errors/ImageKitRetryableException.kt): Generic error indicating a failure that could be retried by the client. -**7. Remove tags** +- [`ImageKitInvalidDataException`](image-kit-java-core/src/main/kotlin/com/imagekit/api/errors/ImageKitInvalidDataException.kt): Failure to interpret successfully parsed data. For example, when accessing a property that's supposed to be required, but the API unexpectedly omitted it from the response. -Accepts an object of class `TagsRequest` specifying the parameters to be used to remove tags. All parameters specified in the [documentation here](https://docs.imagekit.io/api-reference/media-api/remove-tags-bulk) can be passed via their setter functions to get the results. +- [`ImageKitException`](image-kit-java-core/src/main/kotlin/com/imagekit/api/errors/ImageKitException.kt): Base class for all exceptions. Most errors will result in one of the previously mentioned ones, but completely generic errors may be thrown using the base class. -```java -List fileIds = new ArrayList<>(); -fileIds.add("FileId"); -List tags = new ArrayList<>(); -tags.add("tag-to-remove-1"); -tags.add("tag-to-remove-2"); -ResultTags resultTags=ImageKit.getInstance().removeTags(new TagsRequest(fileIds, tags)); -System.out.println("======FINAL RESULT======="); -System.out.println(resultTags); -System.out.println("Raw Response:"); -System.out.println(resultTags.getResponseMetaData().getRaw()); -System.out.println("Map Response:"); -System.out.println(resultTags.getResponseMetaData().getMap()); -``` +## Logging -**8. Remove AI tags** +The SDK uses the standard [OkHttp logging interceptor](https://github.com/square/okhttp/tree/master/okhttp-logging-interceptor). -Accepts an object of class `AITagsRequest` specifying the parameters to be used to remove AI tags. All parameters specified in the [documentation here](https://docs.imagekit.io/api-reference/media-api/remove-aitags-bulk) can be passed via their setter functions to get the results. +Enable logging by setting the `IMAGE_KIT_LOG` environment variable to `info`: -```java -List fileIds = new ArrayList<>(); -fileIds.add("629f3de17eb0fe4053615450"); -List aiTags = new ArrayList<>(); -aiTags.add("Rectangle"); -AITagsRequest aiTagsRequest =new AITagsRequest(); -aiTagsRequest.setFileIds(fileIds); -aiTagsRequest.setAITags(aiTags); -ResultTags resultTags = ImageKit.getInstance().removeAITags(aiTagsRequest); -System.out.println("======FINAL RESULT======="); -System.out.println(resultTags); -System.out.println("Raw Response:"); -System.out.println(resultTags.getResponseMetaData().getRaw()); -System.out.println("Map Response:"); -System.out.println(resultTags.getResponseMetaData().getMap()); +```sh +$ export IMAGE_KIT_LOG=info ``` -**9. Delete File** +Or to `debug` for more verbose logging: -Accepts the file ID and delete a file as per the [API documentation here](https://docs.imagekit.io/api-reference/media-api/delete-file). - -```java -String fileId="your-file-id"; -Result result=ImageKit.getInstance().deleteFile(fileId); -System.out.println("======FINAL RESULT======="); -System.out.println(result); -System.out.println("Raw Response:"); -System.out.println(result.getResponseMetaData().getRaw()); -System.out.println("Map Response:"); -System.out.println(result.getResponseMetaData().getMap()); +```sh +$ export IMAGE_KIT_LOG=debug ``` -**10. Delete FileVersion** +## ProGuard and R8 -Accepts an object of class `DeleteFileVersionRequest` specifying the parameters to be used to delete file version. All parameters specified in the [documentation here](https://docs.imagekit.io/api-reference/media-api/delete-file-version) can be passed via their setter functions to get the results. +Although the SDK uses reflection, it is still usable with [ProGuard](https://github.com/Guardsquare/proguard) and [R8](https://developer.android.com/topic/performance/app-optimization/enable-app-optimization) because `image-kit-java-core` is published with a [configuration file](image-kit-java-core/src/main/resources/META-INF/proguard/image-kit-java-core.pro) containing [keep rules](https://www.guardsquare.com/manual/configuration/usage). -```java -DeleteFileVersionRequest deleteFileVersionRequest = new DeleteFileVersionRequest(); -deleteFileVersionRequest.setFileId("629d95278482ba129fd17c97"); -deleteFileVersionRequest.setVersionId("629d953ebd24e8ceca911a66"); -ResultNoContent resultNoContent = ImageKit.getInstance().deleteFileVersion(deleteFileVersionRequest); -System.out.println("======FINAL RESULT======="); -System.out.println(resultNoContent); -System.out.println("Raw Response:"); -System.out.println(resultNoContent.getResponseMetaData().getRaw()); -System.out.println("Map Response:"); -System.out.println(resultNoContent.getResponseMetaData().getMap()); -``` +ProGuard and R8 should automatically detect and use the published rules, but you can also manually copy the keep rules if necessary. -**11. Delete files (bulk)** +## Jackson -Accepts the file IDs to delete files as per the [API documentation here](https://docs.imagekit.io/api-reference/media-api/delete-files-bulk). +The SDK depends on [Jackson](https://github.com/FasterXML/jackson) for JSON serialization/deserialization. It is compatible with version 2.13.4 or higher, but depends on version 2.18.2 by default. -```java -List fileIds = new ArrayList<>(); -fileIds.add("your-file-id"); -fileIds.add("your-file-id"); -fileIds.add("your-file-id"); - -ResultFileDelete result=ImageKit.getInstance().bulkDeleteFiles(fileIds); -System.out.println("======FINAL RESULT======="); -System.out.println(result); -System.out.println("Raw Response:"); -System.out.println(result.getResponseMetaData().getRaw()); -System.out.println("Map Response:"); -System.out.println(result.getResponseMetaData().getMap()); -``` +The SDK throws an exception if it detects an incompatible Jackson version at runtime (e.g. if the default version was overridden in your Maven or Gradle config). -**12. Copy file** +If the SDK threw an exception, but you're _certain_ the version is compatible, then disable the version check using the `checkJacksonVersionCompatibility` on [`ImageKitOkHttpClient`](image-kit-java-client-okhttp/src/main/kotlin/com/imagekit/api/client/okhttp/ImageKitOkHttpClient.kt) or [`ImageKitOkHttpClientAsync`](image-kit-java-client-okhttp/src/main/kotlin/com/imagekit/api/client/okhttp/ImageKitOkHttpClientAsync.kt). -Accepts an object of class `CopyFileRequest` specifying the parameters to be used to copy file. All parameters specified in the [documentation here](https://docs.imagekit.io/api-reference/media-api/copy-file) can be passed via their setter functions to get the results. +> [!CAUTION] +> We make no guarantee that the SDK works correctly when the Jackson version check is disabled. -```java -CopyFileRequest copyFileRequest = new CopyFileRequest(); -copyFileRequest.setSourceFilePath("/w2_image.png"); -copyFileRequest.setDestinationPath("/Gallery/"); -copyFileRequest.setIncludeFileVersions(true); -ResultNoContent resultNoContent = ImageKit.getInstance().copyFile(copyFileRequest); -System.out.println("======FINAL RESULT======="); -System.out.println(resultNoContent); -System.out.println("Raw Response:"); -System.out.println(resultNoContent.getResponseMetaData().getRaw()); -System.out.println("Map Response:"); -System.out.println(resultNoContent.getResponseMetaData().getMap()); -``` +## Network options -**13. Move file** +### Retries -Accepts an object of class `MoveFileRequest` specifying the parameters to be used to move file. All parameters specified in the [documentation here](https://docs.imagekit.io/api-reference/media-api/move-file) can be passed via their setter functions to get the results. +The SDK automatically retries 2 times by default, with a short exponential backoff between requests. -```java -MoveFileRequest moveFileRequest = new MoveFileRequest(); -moveFileRequest.setSourceFilePath("/Gallery/w2_image.png"); -moveFileRequest.setDestinationPath("/"); -ResultNoContent resultNoContent = ImageKit.getInstance().moveFile(moveFileRequest); -System.out.println("======FINAL RESULT======="); -System.out.println(resultNoContent); -System.out.println("Raw Response:"); -System.out.println(resultNoContent.getResponseMetaData().getRaw()); -System.out.println("Map Response:"); -System.out.println(resultNoContent.getResponseMetaData().getMap()); -``` +Only the following error types are retried: + +- Connection errors (for example, due to a network connectivity problem) +- 408 Request Timeout +- 409 Conflict +- 429 Rate Limit +- 5xx Internal -**14. Rename file** +The API may also explicitly instruct the SDK to retry or not retry a request. -Accepts an object of class `RenameFileRequest` specifying the parameters to be used to rename file. All parameters specified in the [documentation here](https://docs.imagekit.io/api-reference/media-api/rename-file) can be passed via their setter functions to get the results. +To set a custom number of retries, configure the client using the `maxRetries` method: ```java -RenameFileRequest renameFileRequest = new RenameFileRequest(); -renameFileRequest.setFilePath("/w2_image.png"); -renameFileRequest.setNewFileName("w2_image_s.png"); -renameFileRequest.setPurgeCache(true); -ResultRenameFile resultRenameFile = ImageKit.getInstance().renameFile(renameFileRequest); -System.out.println("======FINAL RESULT======="); -System.out.println(resultRenameFile); -System.out.println("Raw Response:"); -System.out.println(resultRenameFile.getResponseMetaData().getRaw()); -System.out.println("Map Response:"); -System.out.println(resultRenameFile.getResponseMetaData().getMap()); +import com.imagekit.api.client.ImageKitClient; +import com.imagekit.api.client.okhttp.ImageKitOkHttpClient; + +ImageKitClient client = ImageKitOkHttpClient.builder() + .fromEnv() + .maxRetries(4) + .build(); ``` -**15. Restore file Version** +### Timeouts -Accepts the fileId and versionId to restore file version as per the [API documentation here](https://docs.imagekit.io/api-reference/media-api/restore-file-version). +Requests time out after 1 minute by default. + +To set a custom timeout, configure the method call using the `timeout` method: ```java -Result result = ImageKit.getInstance().restoreFileVersion("fileId", "versionId"); -System.out.println("======FINAL RESULT======="); -System.out.println(result); -System.out.println("Raw Response:"); -System.out.println(result.getResponseMetaData().getRaw()); -System.out.println("Map Response:"); -System.out.println(result.getResponseMetaData().getMap()); -``` +import com.imagekit.api.models.files.FileUploadResponse; -**16. Create Folder** +FileUploadResponse response = client.files().upload( + params, RequestOptions.builder().timeout(Duration.ofSeconds(30)).build() +); +``` -Accepts an object of class `CreateFolderRequest` specifying the parameters to be used to create folder. All parameters specified in the [documentation here](https://docs.imagekit.io/api-reference/media-api/create-folder) can be passed via their setter functions to get the results. +Or configure the default for all method calls at the client level: ```java -CreateFolderRequest createFolderRequest = new CreateFolderRequest(); -createFolderRequest.setFolderName("test1"); -createFolderRequest.setParentFolderPath("/"); -ResultEmptyBlock resultEmptyBlock = ImageKit.getInstance().createFolder(createFolderRequest); -System.out.println("======FINAL RESULT======="); -System.out.println(resultEmptyBlock); -System.out.println("Raw Response:"); -System.out.println(resultEmptyBlock.getResponseMetaData().getRaw()); -System.out.println("Map Response:"); -System.out.println(resultEmptyBlock.getResponseMetaData().getMap()); +import com.imagekit.api.client.ImageKitClient; +import com.imagekit.api.client.okhttp.ImageKitOkHttpClient; +import java.time.Duration; + +ImageKitClient client = ImageKitOkHttpClient.builder() + .fromEnv() + .timeout(Duration.ofSeconds(30)) + .build(); ``` -**17. Delete Folder** +### Proxies -Accepts an object of class `DeleteFolderRequest` specifying the parameters to be used to delete folder. All parameters specified in the [documentation here](https://docs.imagekit.io/api-reference/media-api/delete-folder) can be passed via their setter functions to get the results. +To route requests through a proxy, configure the client using the `proxy` method: ```java -DeleteFolderRequest deleteFolderRequest = new DeleteFolderRequest(); -deleteFolderRequest.setFolderPath("/test1"); -ResultNoContent resultNoContent = ImageKit.getInstance().deleteFolder(deleteFolderRequest); -System.out.println("======FINAL RESULT======="); -System.out.println(resultNoContent); -System.out.println("Raw Response:"); -System.out.println(resultNoContent.getResponseMetaData().getRaw()); -System.out.println("Map Response:"); -System.out.println(resultNoContent.getResponseMetaData().getMap()); +import com.imagekit.api.client.ImageKitClient; +import com.imagekit.api.client.okhttp.ImageKitOkHttpClient; +import java.net.InetSocketAddress; +import java.net.Proxy; + +ImageKitClient client = ImageKitOkHttpClient.builder() + .fromEnv() + .proxy(new Proxy( + Proxy.Type.HTTP, new InetSocketAddress( + "https://example.com", 8080 + ) + )) + .build(); ``` -**18. Copy Folder** +### HTTPS + +> [!NOTE] +> Most applications should not call these methods, and instead use the system defaults. The defaults include +> special optimizations that can be lost if the implementations are modified. -Accepts an object of class `CopyFolderRequest` specifying the parameters to be used to copy folder. All parameters specified in the [documentation here](https://docs.imagekit.io/api-reference/media-api/copy-folder) can be passed via their setter functions to get the results. +To configure how HTTPS connections are secured, configure the client using the `sslSocketFactory`, `trustManager`, and `hostnameVerifier` methods: ```java -CopyFolderRequest copyFolderRequest = new CopyFolderRequest(); -copyFolderRequest.setSourceFolderPath("/Gallery/test"); -copyFolderRequest.setDestinationPath("/"); -ResultOfFolderActions resultOfFolderActions = ImageKit.getInstance().copyFolder(copyFolderRequest); -System.out.println("======FINAL RESULT======="); -System.out.println(resultOfFolderActions); -System.out.println("Raw Response:"); -System.out.println(resultOfFolderActions.getResponseMetaData().getRaw()); -System.out.println("Map Response:"); -System.out.println(resultOfFolderActions.getResponseMetaData().getMap()); +import com.imagekit.api.client.ImageKitClient; +import com.imagekit.api.client.okhttp.ImageKitOkHttpClient; + +ImageKitClient client = ImageKitOkHttpClient.builder() + .fromEnv() + // If `sslSocketFactory` is set, then `trustManager` must be set, and vice versa. + .sslSocketFactory(yourSSLSocketFactory) + .trustManager(yourTrustManager) + .hostnameVerifier(yourHostnameVerifier) + .build(); ``` -**19. Move Folder** +### Custom HTTP client -Accepts an object of class `MoveFolderRequest` specifying the parameters to be used to move folder. All parameters specified in the [documentation here](https://docs.imagekit.io/api-reference/media-api/move-folder) can be passed via their setter functions to get the results. +The SDK consists of three artifacts: -```java -MoveFolderRequest moveFolderRequest = new MoveFolderRequest(); -moveFolderRequest.setSourceFolderPath("/Gallery/test"); -moveFolderRequest.setDestinationPath("/"); -ResultOfFolderActions resultOfFolderActions = ImageKit.getInstance().moveFolder(moveFolderRequest); -System.out.println("======FINAL RESULT======="); -System.out.println(resultOfFolderActions); -System.out.println("Raw Response:"); -System.out.println(resultOfFolderActions.getResponseMetaData().getRaw()); -System.out.println("Map Response:"); -System.out.println(resultOfFolderActions.getResponseMetaData().getMap()); -``` +- `image-kit-java-core` + - Contains core SDK logic + - Does not depend on [OkHttp](https://square.github.io/okhttp) + - Exposes [`ImageKitClient`](image-kit-java-core/src/main/kotlin/com/imagekit/api/client/ImageKitClient.kt), [`ImageKitClientAsync`](image-kit-java-core/src/main/kotlin/com/imagekit/api/client/ImageKitClientAsync.kt), [`ImageKitClientImpl`](image-kit-java-core/src/main/kotlin/com/imagekit/api/client/ImageKitClientImpl.kt), and [`ImageKitClientAsyncImpl`](image-kit-java-core/src/main/kotlin/com/imagekit/api/client/ImageKitClientAsyncImpl.kt), all of which can work with any HTTP client +- `image-kit-java-client-okhttp` + - Depends on [OkHttp](https://square.github.io/okhttp) + - Exposes [`ImageKitOkHttpClient`](image-kit-java-client-okhttp/src/main/kotlin/com/imagekit/api/client/okhttp/ImageKitOkHttpClient.kt) and [`ImageKitOkHttpClientAsync`](image-kit-java-client-okhttp/src/main/kotlin/com/imagekit/api/client/okhttp/ImageKitOkHttpClientAsync.kt), which provide a way to construct [`ImageKitClientImpl`](image-kit-java-core/src/main/kotlin/com/imagekit/api/client/ImageKitClientImpl.kt) and [`ImageKitClientAsyncImpl`](image-kit-java-core/src/main/kotlin/com/imagekit/api/client/ImageKitClientAsyncImpl.kt), respectively, using OkHttp +- `image-kit-java` + - Depends on and exposes the APIs of both `image-kit-java-core` and `image-kit-java-client-okhttp` + - Does not have its own logic -**20. Get Bulk Job Status** +This structure allows replacing the SDK's default HTTP client without pulling in unnecessary dependencies. -Accepts the jobId to get bulk job status as per the [API documentation here](https://docs.imagekit.io/api-reference/media-api/copy-move-folder-status). +#### Customized [`OkHttpClient`](https://square.github.io/okhttp/3.x/okhttp/okhttp3/OkHttpClient.html) -```java -String jobId = "629f44ac7eb0fe8173622d4b"; -ResultBulkJobStatus resultBulkJobStatus = ImageKit.getInstance().getBulkJobStatus(jobId); -System.out.println("======FINAL RESULT======="); -System.out.println(resultBulkJobStatus); -System.out.println("Raw Response:"); -System.out.println(resultBulkJobStatus.getResponseMetaData().getRaw()); -System.out.println("Map Response:"); -System.out.println(resultBulkJobStatus.getResponseMetaData().getMap()); -``` +> [!TIP] +> Try the available [network options](#network-options) before replacing the default client. -**21. Purge Cache** +To use a customized `OkHttpClient`: -Accepts a full URL of the file for which the cache has to be cleared as per the [API documentation here](https://docs.imagekit.io/api-reference/media-api/purge-cache). +1. Replace your [`image-kit-java` dependency](#installation) with `image-kit-java-core` +2. Copy `image-kit-java-client-okhttp`'s [`OkHttpClient`](image-kit-java-client-okhttp/src/main/kotlin/com/imagekit/api/client/okhttp/OkHttpClient.kt) class into your code and customize it +3. Construct [`ImageKitClientImpl`](image-kit-java-core/src/main/kotlin/com/imagekit/api/client/ImageKitClientImpl.kt) or [`ImageKitClientAsyncImpl`](image-kit-java-core/src/main/kotlin/com/imagekit/api/client/ImageKitClientAsyncImpl.kt), similarly to [`ImageKitOkHttpClient`](image-kit-java-client-okhttp/src/main/kotlin/com/imagekit/api/client/okhttp/ImageKitOkHttpClient.kt) or [`ImageKitOkHttpClientAsync`](image-kit-java-client-okhttp/src/main/kotlin/com/imagekit/api/client/okhttp/ImageKitOkHttpClientAsync.kt), using your customized client -```java -ResultCache result=ImageKit.getInstance().purgeCache("https://ik.imagekit.io/imagekit-id/default-image.jpg"); -System.out.println("======FINAL RESULT======="); -System.out.println(result); -System.out.println("Raw Response:"); -System.out.println(result.getResponseMetaData().getRaw()); -System.out.println("Map Response:"); -System.out.println(result.getResponseMetaData().getMap()); -``` +### Completely custom HTTP client -**22. Purge Cache Status** +To use a completely custom HTTP client: -Accepts a request ID and fetch purge cache status as per the [API documentation here](https://docs.imagekit.io/api-reference/media-api/purge-cache-status) +1. Replace your [`image-kit-java` dependency](#installation) with `image-kit-java-core` +2. Write a class that implements the [`HttpClient`](image-kit-java-core/src/main/kotlin/com/imagekit/api/core/http/HttpClient.kt) interface +3. Construct [`ImageKitClientImpl`](image-kit-java-core/src/main/kotlin/com/imagekit/api/client/ImageKitClientImpl.kt) or [`ImageKitClientAsyncImpl`](image-kit-java-core/src/main/kotlin/com/imagekit/api/client/ImageKitClientAsyncImpl.kt), similarly to [`ImageKitOkHttpClient`](image-kit-java-client-okhttp/src/main/kotlin/com/imagekit/api/client/okhttp/ImageKitOkHttpClient.kt) or [`ImageKitOkHttpClientAsync`](image-kit-java-client-okhttp/src/main/kotlin/com/imagekit/api/client/okhttp/ImageKitOkHttpClientAsync.kt), using your new client class -```java -String requestId="cache-requestId"; -ResultCacheStatus result=ImageKit.getInstance().getPurgeCacheStatus(requestId); -System.out.println("======FINAL RESULT======="); -System.out.println(result); -System.out.println("Raw Response:"); -System.out.println(result.getResponseMetaData().getRaw()); -System.out.println("Map Response:"); -System.out.println(result.getResponseMetaData().getMap()); -``` +## Undocumented API functionality -**23. Get File Metadata** +The SDK is typed for convenient usage of the documented API. However, it also supports working with undocumented or not yet supported parts of the API. -Accepts the file ID and fetches the metadata as per the [API documentation here](https://docs.imagekit.io/api-reference/metadata-api/get-image-metadata-for-uploaded-media-files) +### Parameters -```java -String fileId="your-file-id"; -ResultMetaData result=ImageKit.getInstance().getFileMetadata(fileId); -System.out.println("======FINAL RESULT======="); -System.out.println(result); -System.out.println("Raw Response:"); -System.out.println(result.getResponseMetaData().getRaw()); -System.out.println("Map Response:"); -System.out.println(result.getResponseMetaData().getMap()); -``` +To set undocumented parameters, call the `putAdditionalHeader`, `putAdditionalQueryParam`, or `putAdditionalBodyProperty` methods on any `Params` class: -Another way to get metadata from a remote file URL as per the [API documentation here](https://docs.imagekit.io/api-reference/metadata-api/get-image-metadata-from-remote-url). This file should be accessible over the ImageKit.io URL-endpoint. ```java -String url="Remote File URL"; -ResultMetaData result=ImageKit.getInstance().getRemoteFileMetadata(url); -System.out.println("======FINAL RESULT======="); -System.out.println(result); -System.out.println("Raw Response:"); -System.out.println(result.getResponseMetaData().getRaw()); -System.out.println("Map Response:"); -System.out.println(result.getResponseMetaData().getMap()); -``` +import com.imagekit.api.core.JsonValue; +import com.imagekit.api.models.files.FileUploadParams; -**24. Create CustomMetaDataFields** - -Accepts an object of class `CustomMetaDataFieldCreateRequest` specifying the parameters to be used to create cusomMetaDataFields. All parameters specified in the [documentation here](https://docs.imagekit.io/api-reference/custom-metadata-fields-api/create-custom-metadata-field) can be passed as-is with the correct values to get the results. +FileUploadParams params = FileUploadParams.builder() + .putAdditionalHeader("Secret-Header", "42") + .putAdditionalQueryParam("secret_query_param", "42") + .putAdditionalBodyProperty("secretProperty", JsonValue.from("42")) + .build(); +``` -Check for the [Allowed Values In The Schema](https://docs.imagekit.io/api-reference/custom-metadata-fields-api/create-custom-metadata-field#allowed-values-in-the-schema-object). +These can be accessed on the built object later using the `_additionalHeaders()`, `_additionalQueryParams()`, and `_additionalBodyProperties()` methods. -#### Examples: +To set undocumented parameters on _nested_ headers, query params, or body classes, call the `putAdditionalProperty` method on the nested class: ```java -CustomMetaDataFieldSchemaObject schemaObject = new CustomMetaDataFieldSchemaObject(); -schemaObject.setType("Number"); -schemaObject.setMinValue(10); -schemaObject.setMaxValue(200); -CustomMetaDataFieldCreateRequest customMetaDataFieldCreateRequest = new CustomMetaDataFieldCreateRequest(); -customMetaDataFieldCreateRequest.setName("Name"); -customMetaDataFieldCreateRequest.setLabel("Label"); -customMetaDataFieldCreateRequest.setSchema(schemaObject); -ResultCustomMetaDataField resultCustomMetaDataField=ImageKit.getInstance().createCustomMetaDataFields(customMetaDataFieldCreateRequest); -System.out.println("======FINAL RESULT======="); -System.out.println(resultCustomMetaDataField); -System.out.println("Raw Response:"); -System.out.println(resultCustomMetaDataField.getResponseMetaData().getRaw()); -System.out.println("Map Response:"); -System.out.println(resultCustomMetaDataField.getResponseMetaData().getMap()); +import com.imagekit.api.core.JsonValue; +import com.imagekit.api.models.files.FileUploadParams; + +FileUploadParams params = FileUploadParams.builder() + .transformation(FileUploadParams.Transformation.builder() + .putAdditionalProperty("secretProperty", JsonValue.from("42")) + .build()) + .build(); ``` -- MultiSelect type Exmample: +These properties can be accessed on the nested built object later using the `_additionalProperties()` method. + +To set a documented parameter or property to an undocumented or not yet supported _value_, pass a [`JsonValue`](image-kit-java-core/src/main/kotlin/com/imagekit/api/core/Values.kt) object to its setter: ```java -List objectList = new ArrayList<>(); -objectList.add("small"); -objectList.add(30); -objectList.add(40); -objectList.add(true); - -List defaultValueObject = new ArrayList<>(); -defaultValueObject.add("small"); -defaultValueObject.add(30); -defaultValueObject.add(true); -CustomMetaDataFieldSchemaObject customMetaDataFieldSchemaObject = new CustomMetaDataFieldSchemaObject(); -customMetaDataFieldSchemaObject.setType("MultiSelect"); -customMetaDataFieldSchemaObject.setValueRequired(true); // optional -customMetaDataFieldSchemaObject.setDefaultValue(defaultValueObject); // required if isValueRequired set to true -customMetaDataFieldSchemaObject.setSelectOptions(objectList); -CustomMetaDataFieldCreateRequest customMetaDataFieldCreateRequest = new CustomMetaDataFieldCreateRequest(); -customMetaDataFieldCreateRequest.setName("Name-MultiSelect"); -customMetaDataFieldCreateRequest.setLabel("Label-MultiSelect"); -customMetaDataFieldCreateRequest.setSchema(customMetaDataFieldSchemaObject); - -ResultCustomMetaDataField resultCustomMetaDataField = ImageKit.getInstance() - .createCustomMetaDataFields(customMetaDataFieldCreateRequest); +import com.imagekit.api.core.JsonValue; +import com.imagekit.api.models.files.FileUploadParams; + +FileUploadParams params = FileUploadParams.builder() + .file(JsonValue.from(42)) + .fileName("file-name.jpg") + .build(); ``` -- Date type Exmample: +The most straightforward way to create a [`JsonValue`](image-kit-java-core/src/main/kotlin/com/imagekit/api/core/Values.kt) is using its `from(...)` method: ```java -CustomMetaDataFieldSchemaObject customMetaDataFieldSchemaObject = new CustomMetaDataFieldSchemaObject(); -customMetaDataFieldSchemaObject.setType("Date"); -customMetaDataFieldSchemaObject.setValueRequired(true); // optional -customMetaDataFieldSchemaObject.setDefaultValue("2022-11-30T10:11:10+00:00"); // required if isValueRequired set to true -customMetaDataFieldSchemaObject.setMinValue("2022-11-30T10:11:10+00:00"); -customMetaDataFieldSchemaObject.setMaxValue("2022-12-30T10:11:10+00:00"); - -CustomMetaDataFieldCreateRequest customMetaDataFieldCreateRequest = new CustomMetaDataFieldCreateRequest(); -customMetaDataFieldCreateRequest.setName("Name"); -customMetaDataFieldCreateRequest.setLabel("Label"); -customMetaDataFieldCreateRequest.setSchema(customMetaDataFieldSchemaObject); - -ResultCustomMetaDataField resultCustomMetaDataField = ImageKit.getInstance() - .createCustomMetaDataFields(customMetaDataFieldCreateRequest); -``` +import com.imagekit.api.core.JsonValue; +import java.util.List; +import java.util.Map; +// Create primitive JSON values +JsonValue nullValue = JsonValue.from(null); +JsonValue booleanValue = JsonValue.from(true); +JsonValue numberValue = JsonValue.from(42); +JsonValue stringValue = JsonValue.from("Hello World!"); -**25. Get CustomMetaDataFields** +// Create a JSON array value equivalent to `["Hello", "World"]` +JsonValue arrayValue = JsonValue.from(List.of( + "Hello", "World" +)); -Accepts the includeDeleted boolean and fetches the metadata as per the [API documentation here](https://docs.imagekit.io/api-reference/custom-metadata-fields-api/get-custom-metadata-field) +// Create a JSON object value equivalent to `{ "a": 1, "b": 2 }` +JsonValue objectValue = JsonValue.from(Map.of( + "a", 1, + "b", 2 +)); -```java -ResultCustomMetaDataFieldList resultCustomMetaDataFieldList=ImageKit.getInstance().getCustomMetaDataFields(false); -System.out.println("======FINAL RESULT======="); -System.out.println(resultCustomMetaDataFieldList); -System.out.println("Raw Response:"); -System.out.println(resultCustomMetaDataFieldList.getResponseMetaData().getRaw()); -System.out.println("Map Response:"); -System.out.println(resultCustomMetaDataFieldList.getResponseMetaData().getList()); -System.out.println(resultCustomMetaDataFieldList.getResultCustomMetaDataFields()); +// Create an arbitrarily nested JSON equivalent to: +// { +// "a": [1, 2], +// "b": [3, 4] +// } +JsonValue complexValue = JsonValue.from(Map.of( + "a", List.of( + 1, 2 + ), + "b", List.of( + 3, 4 + ) +)); ``` -**26. Edit CustomMetaDataFields** +Normally a `Builder` class's `build` method will throw [`IllegalStateException`](https://docs.oracle.com/javase/8/docs/api/java/lang/IllegalStateException.html) if any required parameter or property is unset. -Accepts an ID of customMetaDataField and object of class `CustomMetaDataFieldUpdateRequest` specifying the parameters to be used to edit cusomMetaDataFields as per the [API documentation here](https://docs.imagekit.io/api-reference/custom-metadata-fields-api/update-custom-metadata-field). +To forcibly omit a required parameter or property, pass [`JsonMissing`](image-kit-java-core/src/main/kotlin/com/imagekit/api/core/Values.kt): ```java -CustomMetaDataFieldSchemaObject schemaObject = new CustomMetaDataFieldSchemaObject(); -schemaObject.setMinValue(10); -schemaObject.setMaxValue(200); - -CustomMetaDataFieldUpdateRequest customMetaDataFieldUpdateRequest = new CustomMetaDataFieldUpdateRequest(); -customMetaDataFieldUpdateRequest.setId("id"); -customMetaDataFieldUpdateRequest.setLabel("label"); -customMetaDataFieldUpdateRequest.setSchema(schemaObject); -ResultCustomMetaDataField resultCustomMetaDataField=ImageKit.getInstance().updateCustomMetaDataFields(customMetaDataFieldUpdateRequest); -System.out.println("======FINAL RESULT======="); -System.out.println(resultCustomMetaDataField); -System.out.println("Raw Response:"); -System.out.println(resultCustomMetaDataField.getResponseMetaData().getRaw()); -System.out.println("Map Response:"); -System.out.println(resultCustomMetaDataField.getResponseMetaData().getMap()); +import com.imagekit.api.core.JsonMissing; +import com.imagekit.api.models.files.FileUploadParams; + +FileUploadParams params = FileUploadParams.builder() + .fileName("fileName") + .file(JsonMissing.of()) + .build(); ``` -**27. Delete CustomMetaDataFields** +### Response properties -Accepts the id to delete the customMetaDataFields as per the [API documentation here](https://docs.imagekit.io/api-reference/custom-metadata-fields-api/delete-custom-metadata-field). +To access undocumented response properties, call the `_additionalProperties()` method: ```java -ResultNoContent resultNoContent=ImageKit.getInstance().deleteCustomMetaDataField("id"); -System.out.println("======FINAL RESULT======="); -System.out.println(resultNoContent); -System.out.println("Raw Response:"); -System.out.println(resultNoContent.getResponseMetaData().getRaw()); -System.out.println("Map Response:"); -System.out.println(resultNoContent.getResponseMetaData().getMap()); -``` +import com.imagekit.api.core.JsonValue; +import java.util.Map; -## Utility functions +Map additionalProperties = client.files().upload(params)._additionalProperties(); +JsonValue secretPropertyValue = additionalProperties.get("secretProperty"); -We have included the following commonly used utility functions in this package. +String result = secretPropertyValue.accept(new JsonValue.Visitor<>() { + @Override + public String visitNull() { + return "It's null!"; + } -**Authentication parameter generation** + @Override + public String visitBoolean(boolean value) { + return "It's a boolean!"; + } -In case you are looking to implement client-side file upload, you are going to need a token, expiry timestamp, and a valid signature for that upload. The SDK provides a simple method that you can use in your code to generate these -authentication parameters for you. + @Override + public String visitNumber(Number value) { + return "It's a number!"; + } -Note: The Private API Key should never be exposed in any client-side code. You must always generate these authentications - parameters on the server-side + // Other methods include `visitMissing`, `visitString`, `visitArray`, and `visitObject` + // The default implementation of each unimplemented method delegates to `visitDefault`, which throws by default, but can also be overridden +}); +``` -authentication +To access a property's raw JSON value, which may be undocumented, call its `_` prefixed method: ```java -Map authenticationParams = ImageKit.getInstance().getAuthenticationParameters(token, expire); -``` +import com.imagekit.api.core.JsonField; +import java.io.InputStream; +import java.util.Optional; + +JsonField file = client.files().upload(params)._file(); -Returns Map object of this json -```json -{ - "token": "unique_token", - "expire": "valid_expiry_timestamp", - "signature": "generated_signature" +if (file.isMissing()) { + // The property is absent from the JSON response +} else if (file.isNull()) { + // The property was set to literal null +} else { + // Check if value was provided as a string + // Other methods include `asNumber()`, `asBoolean()`, etc. + Optional jsonString = file.asString(); + + // Try to deserialize into a custom type + MyClass myObject = file.asUnknown().orElseThrow().convert(MyClass.class); } ``` -Both the `token` and `expire` parameters are optional. If not specified, the SDK uses the uuid to generate a random -token and also generates a valid expiry timestamp internally. The value of the token and expire used to generate the -signature are always returned in the response, no matter if they are provided as an input to this method or not. - -**Distance calculation between two pHash values** +### Response validation -Perceptual hashing allows you to construct a hash value that uniquely identifies an input image based on the contents -of an image. [imagekit.io metadata API](https://docs.imagekit.io/api-reference/metadata-api) returns the pHash -value of an image in the response. You can use this value to find a duplicate (or similar) images by calculating the distance between the two images. +In rare cases, the API may return a response that doesn't match the expected type. For example, the SDK may expect a property to contain a `String`, but the API could return something else. +By default, the SDK will not throw an exception in this case. It will throw [`ImageKitInvalidDataException`](image-kit-java-core/src/main/kotlin/com/imagekit/api/errors/ImageKitInvalidDataException.kt) only if you directly access the property. -This SDK exposes phash_distance function to calculate the distance between two pHash value. It accepts two pHash hexadecimal -strings and returns a numeric value indicative of the level of difference between the two images. +If you would prefer to check that the response is completely well-typed upfront, then either call `validate()`: ```java -int calculateDistance(){ - // fetch metadata of two uploaded image files - ... - // extract pHash strings from both: say 'first_hash' and 'second_hash' - ... - // calculate the distance between them: - - int distance = ImageKit.getInstance().pHashDistance(first_hash, second_hash); - return distance; -} +import com.imagekit.api.models.files.FileUploadResponse; + +FileUploadResponse response = client.files().upload(params).validate(); ``` -**Distance calculation examples** -```java -ImageKit.getInstance().pHashDistance("f06830ca9f1e3e90", "f06830ca9f1e3e90"); -// output: 0 (ame image) +Or configure the method call to validate the response using the `responseValidation` method: -ImageKit.getInstance().pHashDistance("2d5ad3936d2e015b", "2d6ed293db36a4fb"); -// output: 17 (similar images) +```java +import com.imagekit.api.models.files.FileUploadResponse; -ImageKit.getInstance().pHashDistance("a4a65595ac94518b", "7838873e791f8400"); -// output: 37 (dissimilar images) +FileUploadResponse response = client.files().upload( + params, RequestOptions.builder().responseValidation(true).build() +); ``` -**HTTP response metadata of Internal API** - -HTTP response metadata of the internal API call can be accessed using the getResponseMetaData function on the Result (or ResultList, ResultCache etc.) object. Example: +Or configure the default for all method calls at the client level: ```java -Result result = ImageKit.getInstance().upload(fileCreateRequest); -result.getResponseMetaData().getRaw(); -result.getResponseMetaData().getHeaders(); -result.getResponseMetaData().getHttpStatusCode(); +import com.imagekit.api.client.ImageKitClient; +import com.imagekit.api.client.okhttp.ImageKitOkHttpClient; + +ImageKitClient client = ImageKitOkHttpClient.builder() + .fromEnv() + .responseValidation(true) + .build(); ``` -## Sample Code Instruction +## FAQ -**1. First clone this repository to your system using git.** -```shell script -git clone https://github.com/imagekit-developer/imagekit-java.git -``` -**2. Open project in your favorite Java IDE that can supports Gradle dependency management or you can use Terminal/Command Prompt.** +### Why don't you use plain `enum` classes? -**3. Goto `src/main/resources` directory.** +Java `enum` classes are not trivially [forwards compatible](https://www.stainless.com/blog/making-java-enums-forwards-compatible). Using them in the SDK could cause runtime exceptions if the API is updated to respond with a new enum value. -**4. Rename file `config.sample.properties` to `config.properties`.** +### Why do you represent fields using `JsonField` instead of just plain `T`? -**5. Edit `config.properties` and write values of given keys.** -```properties -UrlEndpoint=your_url_endpoint -PrivateKey=your_private_key -PublicKey=your_public_key -``` +Using `JsonField` enables a few features: -**5. You will find `App.java` in `src/main/java/io/imagekit/sampleapp/` directory. Edit program as you need, then run `App.java`. If you are using CLI Tool (Terminal/Command Prompt) Then Open Project in CLI and execute using gradle** -```shell -cd imagekit-java -./gradlew run -``` -* Run test case: -```shell -./gradlew imagekit-sdk:test -``` -* Build ImageKit SDK: -```shell -./gradlew imagekit-sdk:clean -./gradlew imagekit-sdk:build -# You will find jar in "imagekit-sdk/build/libs/" directory. -``` +- Allowing usage of [undocumented API functionality](#undocumented-api-functionality) +- Lazily [validating the API response against the expected shape](#response-validation) +- Representing absent vs explicitly null values -## Handling errors -Catch and respond to invalid data, internal problems, and more. +### Why don't you use [`data` classes](https://kotlinlang.org/docs/data-classes.html)? -Imagekit Java SDK raise exceptions for many reasons, such as not found, invalid parameters, authentication errors, and internal server error. We recommend writing code that gracefully handles all possible API exceptions. +It is not [backwards compatible to add new fields to a data class](https://kotlinlang.org/docs/api-guidelines-backward-compatibility.html#avoid-using-data-classes-in-your-api) and we don't want to introduce a breaking change every time we add a field to a class. -#### Example: +### Why don't you use checked exceptions? -```java -try { - // Use ImageKit's SDK to make requests... -} catch (BadRequestException e) { - // Missing or Invalid parameters were supplied to Imagekit.io's API - System.out.println("Status is: " + e.getResponseMetaData().getHttpStatusCode()); - System.out.println("Message is: " + e.getMessage()); - System.out.println("Headers are: " + e.getResponseMetaData().getHeaders()); - System.out.println("Raw body is: " + e.getResponseMetaData().getRaw()); - System.out.println("Mapped body is: " + e.getResponseMetaData().getMap()); -} catch (UnauthorizedException e) { - // No valid API key was provided. -} catch (ForbiddenException e) { - // Can be for the following reasons: - // ImageKit could not authenticate your account with the keys provided. - // An expired key (public or private) was used with the request. - // The account is disabled. - // If you are using the upload API, the total storage limit (or upload limit) is exceeded. -} catch (TooManyRequestsException e) { - // Too many requests made to the API too quickly -} catch (InternalServerException e) { - // Something went wrong with ImageKit.io API. -} catch (PartialSuccessException e) { - // Error cases on partial success. -} catch (NotFoundException e) { - // If any of the field or parameter is not found in data -} catch (UnknownException e) { - // Something else happened, which can be unrelated to imagekit, reason will be indicated in the message field -} -``` +Checked exceptions are widely considered a mistake in the Java programming language. In fact, they were omitted from Kotlin for this reason. + +Checked exceptions: -## Supporttim -For any feedback or to report any issues or general implementation support, please reach out to [support@imagekit.io]() +- Are verbose to handle +- Encourage error handling at the wrong level of abstraction, where nothing can be done about the error +- Are tedious to propagate due to the [function coloring problem](https://journal.stuffwithstuff.com/2015/02/01/what-color-is-your-function) +- Don't play well with lambdas (also due to the function coloring problem) +## Semantic versioning -## Links +This package generally follows [SemVer](https://semver.org/spec/v2.0.0.html) conventions, though certain backwards-incompatible changes may be released as minor versions: -* [Documentation](https://docs.imagekit.io/) -* [Main Website](https://imagekit.io/) +1. Changes to library internals which are technically public but not intended or documented for external use. _(Please open a GitHub issue to let us know if you are relying on such internals.)_ +2. Changes that we do not expect to impact the vast majority of users in practice. +We take backwards-compatibility seriously and work hard to ensure you can rely on a smooth upgrade experience. -## License -Released under the MIT license. +We are keen for your feedback; please open an [issue](https://www.github.com/imagekit-developer/imagekit-java/issues) with questions, bugs, or suggestions. diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..8e64327 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,27 @@ +# Security Policy + +## Reporting Security Issues + +This SDK is generated by [Stainless Software Inc](http://stainless.com). Stainless takes security seriously, and encourages you to report any security vulnerability promptly so that appropriate action can be taken. + +To report a security issue, please contact the Stainless team at security@stainless.com. + +## Responsible Disclosure + +We appreciate the efforts of security researchers and individuals who help us maintain the security of +SDKs we generate. If you believe you have found a security vulnerability, please adhere to responsible +disclosure practices by allowing us a reasonable amount of time to investigate and address the issue +before making any information public. + +## Reporting Non-SDK Related Security Issues + +If you encounter security issues that are not directly related to SDKs but pertain to the services +or products provided by Image Kit, please follow the respective company's security reporting guidelines. + +### Image Kit Terms and Policies + +Please contact developer@imagekit.io for any questions or concerns regarding the security of our services. + +--- + +Thank you for helping us keep the SDKs and systems they interact with secure. diff --git a/bin/check-release-environment b/bin/check-release-environment new file mode 100644 index 0000000..3a6a7b4 --- /dev/null +++ b/bin/check-release-environment @@ -0,0 +1,33 @@ +#!/usr/bin/env bash + +errors=() + +if [ -z "${SONATYPE_USERNAME}" ]; then + errors+=("The SONATYPE_USERNAME secret has not been set. Please set it in either this repository's secrets or your organization secrets") +fi + +if [ -z "${SONATYPE_PASSWORD}" ]; then + errors+=("The SONATYPE_PASSWORD secret has not been set. Please set it in either this repository's secrets or your organization secrets") +fi + +if [ -z "${GPG_SIGNING_KEY}" ]; then + errors+=("The GPG_SIGNING_KEY secret has not been set. Please set it in either this repository's secrets or your organization secrets") +fi + +if [ -z "${GPG_SIGNING_PASSWORD}" ]; then + errors+=("The GPG_SIGNING_PASSWORD secret has not been set. Please set it in either this repository's secrets or your organization secrets") +fi + +lenErrors=${#errors[@]} + +if [[ lenErrors -gt 0 ]]; then + echo -e "Found the following errors in the release environment:\n" + + for error in "${errors[@]}"; do + echo -e "- $error\n" + done + + exit 1 +fi + +echo "The environment is ready to push releases!" diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 0000000..492c480 --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,49 @@ +plugins { + id("io.github.gradle-nexus.publish-plugin") version "1.1.0" + id("org.jetbrains.dokka") version "2.0.0" +} + +repositories { + mavenCentral() +} + +allprojects { + group = "com.imagekit.api" + version = "0.1.0" // x-release-please-version +} + +subprojects { + // These are populated with dependencies by `buildSrc` scripts. + tasks.register("format") { + group = "Verification" + description = "Formats all source files." + } + tasks.register("lint") { + group = "Verification" + description = "Verifies all source files are formatted." + } + apply(plugin = "org.jetbrains.dokka") +} + +subprojects { + apply(plugin = "org.jetbrains.dokka") +} + +// Avoid race conditions between `dokkaJavadocCollector` and `dokkaJavadocJar` tasks +tasks.named("dokkaJavadocCollector").configure { + subprojects.flatMap { it.tasks } + .filter { it.project.name != "image-kit-java" && it.name == "dokkaJavadocJar" } + .forEach { mustRunAfter(it) } +} + +nexusPublishing { + repositories { + sonatype { + nexusUrl.set(uri("https://s01.oss.sonatype.org/service/local/")) + snapshotRepositoryUrl.set(uri("https://s01.oss.sonatype.org/content/repositories/snapshots/")) + + username.set(System.getenv("SONATYPE_USERNAME")) + password.set(System.getenv("SONATYPE_PASSWORD")) + } + } +} diff --git a/buildSrc/build.gradle.kts b/buildSrc/build.gradle.kts new file mode 100644 index 0000000..0b14135 --- /dev/null +++ b/buildSrc/build.gradle.kts @@ -0,0 +1,12 @@ +plugins { + `kotlin-dsl` + kotlin("jvm") version "1.9.20" +} + +repositories { + gradlePluginPortal() +} + +dependencies { + implementation("org.jetbrains.kotlin:kotlin-gradle-plugin:1.9.20") +} diff --git a/buildSrc/src/main/kotlin/image-kit.java.gradle.kts b/buildSrc/src/main/kotlin/image-kit.java.gradle.kts new file mode 100644 index 0000000..81d5d32 --- /dev/null +++ b/buildSrc/src/main/kotlin/image-kit.java.gradle.kts @@ -0,0 +1,136 @@ +import org.gradle.api.tasks.testing.logging.TestExceptionFormat + +plugins { + `java-library` +} + +repositories { + mavenCentral() +} + +configure { + withJavadocJar() + withSourcesJar() +} + +java { + toolchain { + languageVersion.set(JavaLanguageVersion.of(21)) + } + + sourceCompatibility = JavaVersion.VERSION_1_8 + targetCompatibility = JavaVersion.VERSION_1_8 +} + +tasks.withType().configureEach { + options.compilerArgs.add("-Werror") + options.release.set(8) +} + +tasks.named("javadocJar") { + setZip64(true) +} + +tasks.named("jar") { + manifest { + attributes(mapOf( + "Implementation-Title" to project.name, + "Implementation-Version" to project.version + )) + } +} + +tasks.withType().configureEach { + useJUnitPlatform() + + // Run tests in parallel to some degree. + maxParallelForks = (Runtime.getRuntime().availableProcessors() / 2).coerceAtLeast(1) + forkEvery = 100 + + testLogging { + exceptionFormat = TestExceptionFormat.FULL + } +} + +val palantir by configurations.creating +dependencies { + palantir("com.palantir.javaformat:palantir-java-format:2.73.0") +} + +fun registerPalantir( + name: String, + description: String, +) { + val javaName = "${name}Java" + tasks.register(javaName) { + group = "Verification" + this.description = description + + classpath = palantir + mainClass = "com.palantir.javaformat.java.Main" + + // Avoid an `IllegalAccessError` on Java 9+. + jvmArgs( + "--add-exports", "jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED", + "--add-exports", "jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED", + "--add-exports", "jdk.compiler/com.sun.tools.javac.parser=ALL-UNNAMED", + "--add-exports", "jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED", + "--add-exports", "jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED", + ) + + // Use paths relative to the current module. + val argumentFile = + project.layout.buildDirectory.file("palantir-$name-args.txt").get().asFile + val lastRunTimeFile = + project.layout.buildDirectory.file("palantir-$name-last-run.txt").get().asFile + + // Read the time when this task was last executed for this module (if ever). + val lastRunTime = lastRunTimeFile.takeIf { it.exists() }?.readText()?.toLongOrNull() ?: 0L + + // Use a `fileTree` relative to the module's source directory. + val javaFiles = project.fileTree("src") { include("**/*.java") } + + // Determine if any files need to be formatted or linted and continue only if there is at least + // one file. + onlyIf { javaFiles.any { it.lastModified() > lastRunTime } } + + inputs.files(javaFiles) + + doFirst { + // Create the argument file and set the preferred formatting style. + argumentFile.parentFile.mkdirs() + argumentFile.writeText("--palantir\n") + + if (name == "lint") { + // For lint, do a dry run, so no files are modified. Set the exit code to 1 (instead of + // the default 0) if any files need to be formatted, indicating that linting has failed. + argumentFile.appendText("--dry-run\n") + argumentFile.appendText("--set-exit-if-changed\n") + } else { + // `--dry-run` and `--replace` (for in-place formatting) are mutually exclusive. + argumentFile.appendText("--replace\n") + } + + // Write the modified files to the argument file. + javaFiles.filter { it.lastModified() > lastRunTime } + .forEach { argumentFile.appendText("${it.absolutePath}\n") } + } + + doLast { + // Record the last execution time for later up-to-date checking. + lastRunTimeFile.writeText(System.currentTimeMillis().toString()) + } + + // Pass the argument file using the @ symbol + args = listOf("@${argumentFile.absolutePath}") + + outputs.upToDateWhen { javaFiles.none { it.lastModified() > lastRunTime } } + } + + tasks.named(name) { + dependsOn(tasks.named(javaName)) + } +} + +registerPalantir(name = "format", description = "Formats all Java source files.") +registerPalantir(name = "lint", description = "Verifies all Java source files are formatted.") diff --git a/buildSrc/src/main/kotlin/image-kit.kotlin.gradle.kts b/buildSrc/src/main/kotlin/image-kit.kotlin.gradle.kts new file mode 100644 index 0000000..aaec88f --- /dev/null +++ b/buildSrc/src/main/kotlin/image-kit.kotlin.gradle.kts @@ -0,0 +1,106 @@ +import org.jetbrains.kotlin.gradle.dsl.JvmTarget +import org.jetbrains.kotlin.gradle.dsl.KotlinVersion + +plugins { + id("image-kit.java") + kotlin("jvm") +} + +repositories { + mavenCentral() +} + +kotlin { + jvmToolchain { + languageVersion.set(JavaLanguageVersion.of(21)) + } + + compilerOptions { + freeCompilerArgs = listOf( + "-Xjvm-default=all", + "-Xjdk-release=1.8", + // Suppress deprecation warnings because we may still reference and test deprecated members. + // TODO: Replace with `-Xsuppress-warning=DEPRECATION` once we use Kotlin compiler 2.1.0+. + "-nowarn", + ) + jvmTarget.set(JvmTarget.JVM_1_8) + languageVersion.set(KotlinVersion.KOTLIN_1_8) + apiVersion.set(KotlinVersion.KOTLIN_1_8) + coreLibrariesVersion = "1.8.0" + } +} + +tasks.withType().configureEach { + systemProperty("junit.jupiter.execution.parallel.enabled", true) + systemProperty("junit.jupiter.execution.parallel.mode.default", "concurrent") +} + +val ktfmt by configurations.creating +dependencies { + ktfmt("com.facebook:ktfmt:0.56") +} + +fun registerKtfmt( + name: String, + description: String, +) { + val kotlinName = "${name}Kotlin" + tasks.register(kotlinName) { + group = "Verification" + this.description = description + + classpath = ktfmt + mainClass = "com.facebook.ktfmt.cli.Main" + + // Use paths relative to the current module. + val argumentFile = project.layout.buildDirectory.file("ktfmt-$name-args.txt").get().asFile + val lastRunTimeFile = + project.layout.buildDirectory.file("ktfmt-$name-last-run.txt").get().asFile + + // Read the time when this task was last executed for this module (if ever). + val lastRunTime = lastRunTimeFile.takeIf { it.exists() }?.readText()?.toLongOrNull() ?: 0L + + // Use a `fileTree` relative to the module's source directory. + val kotlinFiles = project.fileTree("src") { include("**/*.kt") } + + // Determine if any files need to be formatted or linted and continue only if there is at least + // one file (otherwise Ktfmt will fail). + onlyIf { kotlinFiles.any { it.lastModified() > lastRunTime } } + + inputs.files(kotlinFiles) + + doFirst { + // Create the argument file and set the preferred formatting style. + argumentFile.parentFile.mkdirs() + argumentFile.writeText("--kotlinlang-style\n") + + if (name == "lint") { + // For lint, do a dry run, so no files are modified. Set the exit code to 1 (instead of + // the default 0) if any files need to be formatted, indicating that linting has failed. + argumentFile.appendText("--dry-run\n") + argumentFile.appendText("--set-exit-if-changed\n") + } + + // Write the modified files to the argument file. + kotlinFiles.filter { it.lastModified() > lastRunTime } + .forEach { argumentFile.appendText("${it.absolutePath}\n") } + } + + doLast { + // Record the last execution time for later up-to-date checking. + lastRunTimeFile.writeText(System.currentTimeMillis().toString()) + } + + // Pass the argument file using the @ symbol + args = listOf("@${argumentFile.absolutePath}") + + outputs.upToDateWhen { kotlinFiles.none { it.lastModified() > lastRunTime } } + } + + tasks.named(name) { + dependsOn(tasks.named(kotlinName)) + } +} + +registerKtfmt(name = "format", description = "Formats all Kotlin source files.") +registerKtfmt(name = "lint", description = "Verifies all Kotlin source files are formatted.") diff --git a/buildSrc/src/main/kotlin/image-kit.publish.gradle.kts b/buildSrc/src/main/kotlin/image-kit.publish.gradle.kts new file mode 100644 index 0000000..8d98781 --- /dev/null +++ b/buildSrc/src/main/kotlin/image-kit.publish.gradle.kts @@ -0,0 +1,61 @@ +plugins { + `maven-publish` + signing +} + +configure { + publications { + register("maven") { + from(components["java"]) + + pom { + name.set("ImageKit API") + description.set("Checkout [API overview](/docs/api-overview) to learn about ImageKit's APIs,\nauthentication, rate limits, and error codes etc.") + url.set("https://imagekit.io/docs") + + licenses { + license { + name.set("Apache-2.0") + } + } + + developers { + developer { + name.set("Image Kit") + email.set("developer@imagekit.io") + } + } + + scm { + connection.set("scm:git:git://github.com/imagekit-developer/imagekit-java.git") + developerConnection.set("scm:git:git://github.com/imagekit-developer/imagekit-java.git") + url.set("https://github.com/imagekit-developer/imagekit-java") + } + + versionMapping { + allVariants { + fromResolutionResult() + } + } + } + } + } +} + +signing { + val signingKeyId = System.getenv("GPG_SIGNING_KEY_ID")?.ifBlank { null } + val signingKey = System.getenv("GPG_SIGNING_KEY")?.ifBlank { null } + val signingPassword = System.getenv("GPG_SIGNING_PASSWORD")?.ifBlank { null } + if (signingKey != null && signingPassword != null) { + useInMemoryPgpKeys( + signingKeyId, + signingKey, + signingPassword, + ) + sign(publishing.publications["maven"]) + } +} + +tasks.named("publish") { + dependsOn(":closeAndReleaseSonatypeStagingRepository") +} diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..6680f9c --- /dev/null +++ b/gradle.properties @@ -0,0 +1,18 @@ +org.gradle.caching=true +org.gradle.configuration-cache=true +org.gradle.parallel=true +org.gradle.daemon=false +# These options improve our compilation and test performance. They are inherited by the Kotlin daemon. +org.gradle.jvmargs=\ + -Xms2g \ + -Xmx8g \ + -XX:+UseParallelGC \ + -XX:InitialCodeCacheSize=256m \ + -XX:ReservedCodeCacheSize=1G \ + -XX:MetaspaceSize=512m \ + -XX:MaxMetaspaceSize=2G \ + -XX:TieredStopAtLevel=1 \ + -XX:GCTimeRatio=4 \ + -XX:CICompilerCount=4 \ + -XX:+OptimizeStringConcat \ + -XX:+UseStringDeduplication diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index 87b738c..a4b76b9 100644 Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index e9e7c76..cea7a79 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,7 @@ -#Sat Jan 04 19:50:00 IST 2020 -distributionUrl=https\://services.gradle.org/distributions/gradle-6.0.1-all.zip distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.12-bin.zip +networkTimeout=10000 +validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew index af6708f..f3b75f3 100755 --- a/gradlew +++ b/gradlew @@ -1,78 +1,129 @@ -#!/usr/bin/env sh +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# ############################################################################## -## -## Gradle start up script for UN*X -## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# ############################################################################## # Attempt to set APP_HOME + # Resolve links: $0 may be a link -PRG="$0" -# Need this for relative symlinks. -while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG=`dirname "$PRG"`"/$link" - fi +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac done -SAVED="`pwd`" -cd "`dirname \"$PRG\"`/" >/dev/null -APP_HOME="`pwd -P`" -cd "$SAVED" >/dev/null - -APP_NAME="Gradle" -APP_BASE_NAME=`basename "$0"` -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS='"-Xmx64m"' +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit # Use the maximum available, or set MAX_FD != -1 to use that value. -MAX_FD="maximum" +MAX_FD=maximum warn () { echo "$*" -} +} >&2 die () { echo echo "$*" echo exit 1 -} +} >&2 # OS specific support (must be 'true' or 'false'). cygwin=false msys=false darwin=false nonstop=false -case "`uname`" in - CYGWIN* ) - cygwin=true - ;; - Darwin* ) - darwin=true - ;; - MINGW* ) - msys=true - ;; - NONSTOP* ) - nonstop=true - ;; +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; esac CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + # Determine the Java command to use to start the JVM. if [ -n "$JAVA_HOME" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" + JAVACMD=$JAVA_HOME/jre/sh/java else - JAVACMD="$JAVA_HOME/bin/java" + JAVACMD=$JAVA_HOME/bin/java fi if [ ! -x "$JAVACMD" ] ; then die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME @@ -81,92 +132,120 @@ Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi else - JAVACMD="java" - which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA_HOME variable in your environment to match the location of your Java installation." + fi fi # Increase the maximum file descriptors if we can. -if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then - MAX_FD_LIMIT=`ulimit -H -n` - if [ $? -eq 0 ] ; then - if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then - MAX_FD="$MAX_FD_LIMIT" - fi - ulimit -n $MAX_FD - if [ $? -ne 0 ] ; then - warn "Could not set maximum file descriptor limit: $MAX_FD" - fi - else - warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" - fi +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac fi -# For Darwin, add options to specify how the application appears in the dock -if $darwin; then - GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" -fi +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) -# For Cygwin, switch paths to Windows format before running java -if $cygwin ; then - APP_HOME=`cygpath --path --mixed "$APP_HOME"` - CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` - JAVACMD=`cygpath --unix "$JAVACMD"` - - # We build the pattern for arguments to be converted via cygpath - ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` - SEP="" - for dir in $ROOTDIRSRAW ; do - ROOTDIRS="$ROOTDIRS$SEP$dir" - SEP="|" - done - OURCYGPATTERN="(^($ROOTDIRS))" - # Add a user-defined pattern to the cygpath arguments - if [ "$GRADLE_CYGPATTERN" != "" ] ; then - OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" - fi # Now convert the arguments - kludge to limit ourselves to /bin/sh - i=0 - for arg in "$@" ; do - CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` - CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option - - if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition - eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` - else - eval `echo args$i`="\"$arg\"" + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) fi - i=$((i+1)) + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg done - case $i in - (0) set -- ;; - (1) set -- "$args0" ;; - (2) set -- "$args0" "$args1" ;; - (3) set -- "$args0" "$args1" "$args2" ;; - (4) set -- "$args0" "$args1" "$args2" "$args3" ;; - (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; - (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; - (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; - (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; - (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; - esac fi -# Escape application args -save () { - for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done - echo " " -} -APP_ARGS=$(save "$@") - -# Collect all arguments for the java command, following the shell quoting and substitution rules -eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" -# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong -if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then - cd "$(dirname "$0")" +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" fi +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat index 0f8d593..9d21a21 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -1,84 +1,94 @@ -@if "%DEBUG%" == "" @echo off -@rem ########################################################################## -@rem -@rem Gradle startup script for Windows -@rem -@rem ########################################################################## - -@rem Set local scope for the variables with windows NT shell -if "%OS%"=="Windows_NT" setlocal - -set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. -set APP_BASE_NAME=%~n0 -set APP_HOME=%DIRNAME% - -@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS="-Xmx64m" - -@rem Find java.exe -if defined JAVA_HOME goto findJavaFromJavaHome - -set JAVA_EXE=java.exe -%JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto init - -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:findJavaFromJavaHome -set JAVA_HOME=%JAVA_HOME:"=% -set JAVA_EXE=%JAVA_HOME%/bin/java.exe - -if exist "%JAVA_EXE%" goto init - -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:init -@rem Get command-line arguments, handling Windows variants - -if not "%OS%" == "Windows_NT" goto win9xME_args - -:win9xME_args -@rem Slurp the command line arguments. -set CMD_LINE_ARGS= -set _SKIP=2 - -:win9xME_args_slurp -if "x%~1" == "x" goto execute - -set CMD_LINE_ARGS=%* - -:execute -@rem Setup the command line - -set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar - -@rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% - -:end -@rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd - -:fail -rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of -rem the _cmd.exe /c_ return code! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 - -:mainEnd -if "%OS%"=="Windows_NT" endlocal - -:omega +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/image-kit-java-client-okhttp/build.gradle.kts b/image-kit-java-client-okhttp/build.gradle.kts new file mode 100644 index 0000000..cd001ec --- /dev/null +++ b/image-kit-java-client-okhttp/build.gradle.kts @@ -0,0 +1,14 @@ +plugins { + id("image-kit.kotlin") + id("image-kit.publish") +} + +dependencies { + api(project(":image-kit-java-core")) + + implementation("com.squareup.okhttp3:okhttp:4.12.0") + implementation("com.squareup.okhttp3:logging-interceptor:4.12.0") + + testImplementation(kotlin("test")) + testImplementation("org.assertj:assertj-core:3.25.3") +} diff --git a/image-kit-java-client-okhttp/src/main/kotlin/com/imagekit/api/client/okhttp/ImageKitOkHttpClient.kt b/image-kit-java-client-okhttp/src/main/kotlin/com/imagekit/api/client/okhttp/ImageKitOkHttpClient.kt new file mode 100644 index 0000000..2da16e7 --- /dev/null +++ b/image-kit-java-client-okhttp/src/main/kotlin/com/imagekit/api/client/okhttp/ImageKitOkHttpClient.kt @@ -0,0 +1,327 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.client.okhttp + +import com.fasterxml.jackson.databind.json.JsonMapper +import com.imagekit.api.client.ImageKitClient +import com.imagekit.api.client.ImageKitClientImpl +import com.imagekit.api.core.ClientOptions +import com.imagekit.api.core.Timeout +import com.imagekit.api.core.http.Headers +import com.imagekit.api.core.http.HttpClient +import com.imagekit.api.core.http.QueryParams +import com.imagekit.api.core.jsonMapper +import java.net.Proxy +import java.time.Clock +import java.time.Duration +import java.util.Optional +import javax.net.ssl.HostnameVerifier +import javax.net.ssl.SSLSocketFactory +import javax.net.ssl.X509TrustManager +import kotlin.jvm.optionals.getOrNull + +/** + * A class that allows building an instance of [ImageKitClient] with [OkHttpClient] as the + * underlying [HttpClient]. + */ +class ImageKitOkHttpClient private constructor() { + + companion object { + + /** Returns a mutable builder for constructing an instance of [ImageKitClient]. */ + @JvmStatic fun builder() = Builder() + + /** + * Returns a client configured using system properties and environment variables. + * + * @see ClientOptions.Builder.fromEnv + */ + @JvmStatic fun fromEnv(): ImageKitClient = builder().fromEnv().build() + } + + /** A builder for [ImageKitOkHttpClient]. */ + class Builder internal constructor() { + + private var clientOptions: ClientOptions.Builder = ClientOptions.builder() + private var proxy: Proxy? = null + private var sslSocketFactory: SSLSocketFactory? = null + private var trustManager: X509TrustManager? = null + private var hostnameVerifier: HostnameVerifier? = null + + fun proxy(proxy: Proxy?) = apply { this.proxy = proxy } + + /** Alias for calling [Builder.proxy] with `proxy.orElse(null)`. */ + fun proxy(proxy: Optional) = proxy(proxy.getOrNull()) + + /** + * The socket factory used to secure HTTPS connections. + * + * If this is set, then [trustManager] must also be set. + * + * If unset, then the system default is used. Most applications should not call this method, + * and instead use the system default. The default include special optimizations that can be + * lost if the implementation is modified. + */ + fun sslSocketFactory(sslSocketFactory: SSLSocketFactory?) = apply { + this.sslSocketFactory = sslSocketFactory + } + + /** Alias for calling [Builder.sslSocketFactory] with `sslSocketFactory.orElse(null)`. */ + fun sslSocketFactory(sslSocketFactory: Optional) = + sslSocketFactory(sslSocketFactory.getOrNull()) + + /** + * The trust manager used to secure HTTPS connections. + * + * If this is set, then [sslSocketFactory] must also be set. + * + * If unset, then the system default is used. Most applications should not call this method, + * and instead use the system default. The default include special optimizations that can be + * lost if the implementation is modified. + */ + fun trustManager(trustManager: X509TrustManager?) = apply { + this.trustManager = trustManager + } + + /** Alias for calling [Builder.trustManager] with `trustManager.orElse(null)`. */ + fun trustManager(trustManager: Optional) = + trustManager(trustManager.getOrNull()) + + /** + * The verifier used to confirm that response certificates apply to requested hostnames for + * HTTPS connections. + * + * If unset, then a default hostname verifier is used. + */ + fun hostnameVerifier(hostnameVerifier: HostnameVerifier?) = apply { + this.hostnameVerifier = hostnameVerifier + } + + /** Alias for calling [Builder.hostnameVerifier] with `hostnameVerifier.orElse(null)`. */ + fun hostnameVerifier(hostnameVerifier: Optional) = + hostnameVerifier(hostnameVerifier.getOrNull()) + + /** + * Whether to throw an exception if any of the Jackson versions detected at runtime are + * incompatible with the SDK's minimum supported Jackson version (2.13.4). + * + * Defaults to true. Use extreme caution when disabling this option. There is no guarantee + * that the SDK will work correctly when using an incompatible Jackson version. + */ + fun checkJacksonVersionCompatibility(checkJacksonVersionCompatibility: Boolean) = apply { + clientOptions.checkJacksonVersionCompatibility(checkJacksonVersionCompatibility) + } + + /** + * The Jackson JSON mapper to use for serializing and deserializing JSON. + * + * Defaults to [com.imagekit.api.core.jsonMapper]. The default is usually sufficient and + * rarely needs to be overridden. + */ + fun jsonMapper(jsonMapper: JsonMapper) = apply { clientOptions.jsonMapper(jsonMapper) } + + /** + * The clock to use for operations that require timing, like retries. + * + * This is primarily useful for using a fake clock in tests. + * + * Defaults to [Clock.systemUTC]. + */ + fun clock(clock: Clock) = apply { clientOptions.clock(clock) } + + /** + * The base URL to use for every request. + * + * Defaults to the production environment: `https://api.imagekit.io`. + */ + fun baseUrl(baseUrl: String?) = apply { clientOptions.baseUrl(baseUrl) } + + /** Alias for calling [Builder.baseUrl] with `baseUrl.orElse(null)`. */ + fun baseUrl(baseUrl: Optional) = baseUrl(baseUrl.getOrNull()) + + /** + * Whether to call `validate` on every response before returning it. + * + * Defaults to false, which means the shape of the response will not be validated upfront. + * Instead, validation will only occur for the parts of the response that are accessed. + */ + fun responseValidation(responseValidation: Boolean) = apply { + clientOptions.responseValidation(responseValidation) + } + + /** + * Sets the maximum time allowed for various parts of an HTTP call's lifecycle, excluding + * retries. + * + * Defaults to [Timeout.default]. + */ + fun timeout(timeout: Timeout) = apply { clientOptions.timeout(timeout) } + + /** + * Sets the maximum time allowed for a complete HTTP call, not including retries. + * + * See [Timeout.request] for more details. + * + * For fine-grained control, pass a [Timeout] object. + */ + fun timeout(timeout: Duration) = apply { clientOptions.timeout(timeout) } + + /** + * The maximum number of times to retry failed requests, with a short exponential backoff + * between requests. + * + * Only the following error types are retried: + * - Connection errors (for example, due to a network connectivity problem) + * - 408 Request Timeout + * - 409 Conflict + * - 429 Rate Limit + * - 5xx Internal + * + * The API may also explicitly instruct the SDK to retry or not retry a request. + * + * Defaults to 2. + */ + fun maxRetries(maxRetries: Int) = apply { clientOptions.maxRetries(maxRetries) } + + /** + * Your ImageKit private API key (it starts with `private_`). You can view and manage API + * keys in the [dashboard](https://imagekit.io/dashboard/developer/api-keys). + */ + fun privateApiKey(privateApiKey: String) = apply { + clientOptions.privateApiKey(privateApiKey) + } + + /** + * ImageKit Basic Auth only uses the username field and ignores the password. This field is + * unused. + * + * Defaults to `"do_not_set"`. + */ + fun password(password: String?) = apply { clientOptions.password(password) } + + /** Alias for calling [Builder.password] with `password.orElse(null)`. */ + fun password(password: Optional) = password(password.getOrNull()) + + /** + * Your ImageKit webhook secret. This is used by the SDK to verify webhook signatures. It + * starts with a `whsec_` prefix. You can view and manage your webhook secret in the + * [dashboard](https://imagekit.io/dashboard/developer/webhooks). Treat the secret like a + * password, keep it private and do not expose it publicly. Learn more about + * [webhook verification](https://imagekit.io/docs/webhooks#verify-webhook-signature). + */ + fun webhookSecret(webhookSecret: String?) = apply { + clientOptions.webhookSecret(webhookSecret) + } + + /** Alias for calling [Builder.webhookSecret] with `webhookSecret.orElse(null)`. */ + fun webhookSecret(webhookSecret: Optional) = + webhookSecret(webhookSecret.getOrNull()) + + fun headers(headers: Headers) = apply { clientOptions.headers(headers) } + + fun headers(headers: Map>) = apply { + clientOptions.headers(headers) + } + + fun putHeader(name: String, value: String) = apply { clientOptions.putHeader(name, value) } + + fun putHeaders(name: String, values: Iterable) = apply { + clientOptions.putHeaders(name, values) + } + + fun putAllHeaders(headers: Headers) = apply { clientOptions.putAllHeaders(headers) } + + fun putAllHeaders(headers: Map>) = apply { + clientOptions.putAllHeaders(headers) + } + + fun replaceHeaders(name: String, value: String) = apply { + clientOptions.replaceHeaders(name, value) + } + + fun replaceHeaders(name: String, values: Iterable) = apply { + clientOptions.replaceHeaders(name, values) + } + + fun replaceAllHeaders(headers: Headers) = apply { clientOptions.replaceAllHeaders(headers) } + + fun replaceAllHeaders(headers: Map>) = apply { + clientOptions.replaceAllHeaders(headers) + } + + fun removeHeaders(name: String) = apply { clientOptions.removeHeaders(name) } + + fun removeAllHeaders(names: Set) = apply { clientOptions.removeAllHeaders(names) } + + fun queryParams(queryParams: QueryParams) = apply { clientOptions.queryParams(queryParams) } + + fun queryParams(queryParams: Map>) = apply { + clientOptions.queryParams(queryParams) + } + + fun putQueryParam(key: String, value: String) = apply { + clientOptions.putQueryParam(key, value) + } + + fun putQueryParams(key: String, values: Iterable) = apply { + clientOptions.putQueryParams(key, values) + } + + fun putAllQueryParams(queryParams: QueryParams) = apply { + clientOptions.putAllQueryParams(queryParams) + } + + fun putAllQueryParams(queryParams: Map>) = apply { + clientOptions.putAllQueryParams(queryParams) + } + + fun replaceQueryParams(key: String, value: String) = apply { + clientOptions.replaceQueryParams(key, value) + } + + fun replaceQueryParams(key: String, values: Iterable) = apply { + clientOptions.replaceQueryParams(key, values) + } + + fun replaceAllQueryParams(queryParams: QueryParams) = apply { + clientOptions.replaceAllQueryParams(queryParams) + } + + fun replaceAllQueryParams(queryParams: Map>) = apply { + clientOptions.replaceAllQueryParams(queryParams) + } + + fun removeQueryParams(key: String) = apply { clientOptions.removeQueryParams(key) } + + fun removeAllQueryParams(keys: Set) = apply { + clientOptions.removeAllQueryParams(keys) + } + + /** + * Updates configuration using system properties and environment variables. + * + * @see ClientOptions.Builder.fromEnv + */ + fun fromEnv() = apply { clientOptions.fromEnv() } + + /** + * Returns an immutable instance of [ImageKitClient]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): ImageKitClient = + ImageKitClientImpl( + clientOptions + .httpClient( + OkHttpClient.builder() + .timeout(clientOptions.timeout()) + .proxy(proxy) + .sslSocketFactory(sslSocketFactory) + .trustManager(trustManager) + .hostnameVerifier(hostnameVerifier) + .build() + ) + .build() + ) + } +} diff --git a/image-kit-java-client-okhttp/src/main/kotlin/com/imagekit/api/client/okhttp/ImageKitOkHttpClientAsync.kt b/image-kit-java-client-okhttp/src/main/kotlin/com/imagekit/api/client/okhttp/ImageKitOkHttpClientAsync.kt new file mode 100644 index 0000000..d998ad8 --- /dev/null +++ b/image-kit-java-client-okhttp/src/main/kotlin/com/imagekit/api/client/okhttp/ImageKitOkHttpClientAsync.kt @@ -0,0 +1,327 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.client.okhttp + +import com.fasterxml.jackson.databind.json.JsonMapper +import com.imagekit.api.client.ImageKitClientAsync +import com.imagekit.api.client.ImageKitClientAsyncImpl +import com.imagekit.api.core.ClientOptions +import com.imagekit.api.core.Timeout +import com.imagekit.api.core.http.Headers +import com.imagekit.api.core.http.HttpClient +import com.imagekit.api.core.http.QueryParams +import com.imagekit.api.core.jsonMapper +import java.net.Proxy +import java.time.Clock +import java.time.Duration +import java.util.Optional +import javax.net.ssl.HostnameVerifier +import javax.net.ssl.SSLSocketFactory +import javax.net.ssl.X509TrustManager +import kotlin.jvm.optionals.getOrNull + +/** + * A class that allows building an instance of [ImageKitClientAsync] with [OkHttpClient] as the + * underlying [HttpClient]. + */ +class ImageKitOkHttpClientAsync private constructor() { + + companion object { + + /** Returns a mutable builder for constructing an instance of [ImageKitClientAsync]. */ + @JvmStatic fun builder() = Builder() + + /** + * Returns a client configured using system properties and environment variables. + * + * @see ClientOptions.Builder.fromEnv + */ + @JvmStatic fun fromEnv(): ImageKitClientAsync = builder().fromEnv().build() + } + + /** A builder for [ImageKitOkHttpClientAsync]. */ + class Builder internal constructor() { + + private var clientOptions: ClientOptions.Builder = ClientOptions.builder() + private var proxy: Proxy? = null + private var sslSocketFactory: SSLSocketFactory? = null + private var trustManager: X509TrustManager? = null + private var hostnameVerifier: HostnameVerifier? = null + + fun proxy(proxy: Proxy?) = apply { this.proxy = proxy } + + /** Alias for calling [Builder.proxy] with `proxy.orElse(null)`. */ + fun proxy(proxy: Optional) = proxy(proxy.getOrNull()) + + /** + * The socket factory used to secure HTTPS connections. + * + * If this is set, then [trustManager] must also be set. + * + * If unset, then the system default is used. Most applications should not call this method, + * and instead use the system default. The default include special optimizations that can be + * lost if the implementation is modified. + */ + fun sslSocketFactory(sslSocketFactory: SSLSocketFactory?) = apply { + this.sslSocketFactory = sslSocketFactory + } + + /** Alias for calling [Builder.sslSocketFactory] with `sslSocketFactory.orElse(null)`. */ + fun sslSocketFactory(sslSocketFactory: Optional) = + sslSocketFactory(sslSocketFactory.getOrNull()) + + /** + * The trust manager used to secure HTTPS connections. + * + * If this is set, then [sslSocketFactory] must also be set. + * + * If unset, then the system default is used. Most applications should not call this method, + * and instead use the system default. The default include special optimizations that can be + * lost if the implementation is modified. + */ + fun trustManager(trustManager: X509TrustManager?) = apply { + this.trustManager = trustManager + } + + /** Alias for calling [Builder.trustManager] with `trustManager.orElse(null)`. */ + fun trustManager(trustManager: Optional) = + trustManager(trustManager.getOrNull()) + + /** + * The verifier used to confirm that response certificates apply to requested hostnames for + * HTTPS connections. + * + * If unset, then a default hostname verifier is used. + */ + fun hostnameVerifier(hostnameVerifier: HostnameVerifier?) = apply { + this.hostnameVerifier = hostnameVerifier + } + + /** Alias for calling [Builder.hostnameVerifier] with `hostnameVerifier.orElse(null)`. */ + fun hostnameVerifier(hostnameVerifier: Optional) = + hostnameVerifier(hostnameVerifier.getOrNull()) + + /** + * Whether to throw an exception if any of the Jackson versions detected at runtime are + * incompatible with the SDK's minimum supported Jackson version (2.13.4). + * + * Defaults to true. Use extreme caution when disabling this option. There is no guarantee + * that the SDK will work correctly when using an incompatible Jackson version. + */ + fun checkJacksonVersionCompatibility(checkJacksonVersionCompatibility: Boolean) = apply { + clientOptions.checkJacksonVersionCompatibility(checkJacksonVersionCompatibility) + } + + /** + * The Jackson JSON mapper to use for serializing and deserializing JSON. + * + * Defaults to [com.imagekit.api.core.jsonMapper]. The default is usually sufficient and + * rarely needs to be overridden. + */ + fun jsonMapper(jsonMapper: JsonMapper) = apply { clientOptions.jsonMapper(jsonMapper) } + + /** + * The clock to use for operations that require timing, like retries. + * + * This is primarily useful for using a fake clock in tests. + * + * Defaults to [Clock.systemUTC]. + */ + fun clock(clock: Clock) = apply { clientOptions.clock(clock) } + + /** + * The base URL to use for every request. + * + * Defaults to the production environment: `https://api.imagekit.io`. + */ + fun baseUrl(baseUrl: String?) = apply { clientOptions.baseUrl(baseUrl) } + + /** Alias for calling [Builder.baseUrl] with `baseUrl.orElse(null)`. */ + fun baseUrl(baseUrl: Optional) = baseUrl(baseUrl.getOrNull()) + + /** + * Whether to call `validate` on every response before returning it. + * + * Defaults to false, which means the shape of the response will not be validated upfront. + * Instead, validation will only occur for the parts of the response that are accessed. + */ + fun responseValidation(responseValidation: Boolean) = apply { + clientOptions.responseValidation(responseValidation) + } + + /** + * Sets the maximum time allowed for various parts of an HTTP call's lifecycle, excluding + * retries. + * + * Defaults to [Timeout.default]. + */ + fun timeout(timeout: Timeout) = apply { clientOptions.timeout(timeout) } + + /** + * Sets the maximum time allowed for a complete HTTP call, not including retries. + * + * See [Timeout.request] for more details. + * + * For fine-grained control, pass a [Timeout] object. + */ + fun timeout(timeout: Duration) = apply { clientOptions.timeout(timeout) } + + /** + * The maximum number of times to retry failed requests, with a short exponential backoff + * between requests. + * + * Only the following error types are retried: + * - Connection errors (for example, due to a network connectivity problem) + * - 408 Request Timeout + * - 409 Conflict + * - 429 Rate Limit + * - 5xx Internal + * + * The API may also explicitly instruct the SDK to retry or not retry a request. + * + * Defaults to 2. + */ + fun maxRetries(maxRetries: Int) = apply { clientOptions.maxRetries(maxRetries) } + + /** + * Your ImageKit private API key (it starts with `private_`). You can view and manage API + * keys in the [dashboard](https://imagekit.io/dashboard/developer/api-keys). + */ + fun privateApiKey(privateApiKey: String) = apply { + clientOptions.privateApiKey(privateApiKey) + } + + /** + * ImageKit Basic Auth only uses the username field and ignores the password. This field is + * unused. + * + * Defaults to `"do_not_set"`. + */ + fun password(password: String?) = apply { clientOptions.password(password) } + + /** Alias for calling [Builder.password] with `password.orElse(null)`. */ + fun password(password: Optional) = password(password.getOrNull()) + + /** + * Your ImageKit webhook secret. This is used by the SDK to verify webhook signatures. It + * starts with a `whsec_` prefix. You can view and manage your webhook secret in the + * [dashboard](https://imagekit.io/dashboard/developer/webhooks). Treat the secret like a + * password, keep it private and do not expose it publicly. Learn more about + * [webhook verification](https://imagekit.io/docs/webhooks#verify-webhook-signature). + */ + fun webhookSecret(webhookSecret: String?) = apply { + clientOptions.webhookSecret(webhookSecret) + } + + /** Alias for calling [Builder.webhookSecret] with `webhookSecret.orElse(null)`. */ + fun webhookSecret(webhookSecret: Optional) = + webhookSecret(webhookSecret.getOrNull()) + + fun headers(headers: Headers) = apply { clientOptions.headers(headers) } + + fun headers(headers: Map>) = apply { + clientOptions.headers(headers) + } + + fun putHeader(name: String, value: String) = apply { clientOptions.putHeader(name, value) } + + fun putHeaders(name: String, values: Iterable) = apply { + clientOptions.putHeaders(name, values) + } + + fun putAllHeaders(headers: Headers) = apply { clientOptions.putAllHeaders(headers) } + + fun putAllHeaders(headers: Map>) = apply { + clientOptions.putAllHeaders(headers) + } + + fun replaceHeaders(name: String, value: String) = apply { + clientOptions.replaceHeaders(name, value) + } + + fun replaceHeaders(name: String, values: Iterable) = apply { + clientOptions.replaceHeaders(name, values) + } + + fun replaceAllHeaders(headers: Headers) = apply { clientOptions.replaceAllHeaders(headers) } + + fun replaceAllHeaders(headers: Map>) = apply { + clientOptions.replaceAllHeaders(headers) + } + + fun removeHeaders(name: String) = apply { clientOptions.removeHeaders(name) } + + fun removeAllHeaders(names: Set) = apply { clientOptions.removeAllHeaders(names) } + + fun queryParams(queryParams: QueryParams) = apply { clientOptions.queryParams(queryParams) } + + fun queryParams(queryParams: Map>) = apply { + clientOptions.queryParams(queryParams) + } + + fun putQueryParam(key: String, value: String) = apply { + clientOptions.putQueryParam(key, value) + } + + fun putQueryParams(key: String, values: Iterable) = apply { + clientOptions.putQueryParams(key, values) + } + + fun putAllQueryParams(queryParams: QueryParams) = apply { + clientOptions.putAllQueryParams(queryParams) + } + + fun putAllQueryParams(queryParams: Map>) = apply { + clientOptions.putAllQueryParams(queryParams) + } + + fun replaceQueryParams(key: String, value: String) = apply { + clientOptions.replaceQueryParams(key, value) + } + + fun replaceQueryParams(key: String, values: Iterable) = apply { + clientOptions.replaceQueryParams(key, values) + } + + fun replaceAllQueryParams(queryParams: QueryParams) = apply { + clientOptions.replaceAllQueryParams(queryParams) + } + + fun replaceAllQueryParams(queryParams: Map>) = apply { + clientOptions.replaceAllQueryParams(queryParams) + } + + fun removeQueryParams(key: String) = apply { clientOptions.removeQueryParams(key) } + + fun removeAllQueryParams(keys: Set) = apply { + clientOptions.removeAllQueryParams(keys) + } + + /** + * Updates configuration using system properties and environment variables. + * + * @see ClientOptions.Builder.fromEnv + */ + fun fromEnv() = apply { clientOptions.fromEnv() } + + /** + * Returns an immutable instance of [ImageKitClientAsync]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): ImageKitClientAsync = + ImageKitClientAsyncImpl( + clientOptions + .httpClient( + OkHttpClient.builder() + .timeout(clientOptions.timeout()) + .proxy(proxy) + .sslSocketFactory(sslSocketFactory) + .trustManager(trustManager) + .hostnameVerifier(hostnameVerifier) + .build() + ) + .build() + ) + } +} diff --git a/image-kit-java-client-okhttp/src/main/kotlin/com/imagekit/api/client/okhttp/OkHttpClient.kt b/image-kit-java-client-okhttp/src/main/kotlin/com/imagekit/api/client/okhttp/OkHttpClient.kt new file mode 100644 index 0000000..f86881b --- /dev/null +++ b/image-kit-java-client-okhttp/src/main/kotlin/com/imagekit/api/client/okhttp/OkHttpClient.kt @@ -0,0 +1,246 @@ +package com.imagekit.api.client.okhttp + +import com.imagekit.api.core.RequestOptions +import com.imagekit.api.core.Timeout +import com.imagekit.api.core.http.Headers +import com.imagekit.api.core.http.HttpClient +import com.imagekit.api.core.http.HttpMethod +import com.imagekit.api.core.http.HttpRequest +import com.imagekit.api.core.http.HttpRequestBody +import com.imagekit.api.core.http.HttpResponse +import com.imagekit.api.errors.ImageKitIoException +import java.io.IOException +import java.io.InputStream +import java.net.Proxy +import java.time.Duration +import java.util.concurrent.CompletableFuture +import javax.net.ssl.HostnameVerifier +import javax.net.ssl.SSLSocketFactory +import javax.net.ssl.X509TrustManager +import okhttp3.Call +import okhttp3.Callback +import okhttp3.HttpUrl.Companion.toHttpUrl +import okhttp3.MediaType +import okhttp3.MediaType.Companion.toMediaType +import okhttp3.Request +import okhttp3.RequestBody +import okhttp3.RequestBody.Companion.toRequestBody +import okhttp3.Response +import okhttp3.logging.HttpLoggingInterceptor +import okio.BufferedSink + +class OkHttpClient private constructor(private val okHttpClient: okhttp3.OkHttpClient) : + HttpClient { + + override fun execute(request: HttpRequest, requestOptions: RequestOptions): HttpResponse { + val call = newCall(request, requestOptions) + + return try { + call.execute().toResponse() + } catch (e: IOException) { + throw ImageKitIoException("Request failed", e) + } finally { + request.body?.close() + } + } + + override fun executeAsync( + request: HttpRequest, + requestOptions: RequestOptions, + ): CompletableFuture { + val future = CompletableFuture() + + request.body?.run { future.whenComplete { _, _ -> close() } } + + newCall(request, requestOptions) + .enqueue( + object : Callback { + override fun onResponse(call: Call, response: Response) { + future.complete(response.toResponse()) + } + + override fun onFailure(call: Call, e: IOException) { + future.completeExceptionally(ImageKitIoException("Request failed", e)) + } + } + ) + + return future + } + + override fun close() { + okHttpClient.dispatcher.executorService.shutdown() + okHttpClient.connectionPool.evictAll() + okHttpClient.cache?.close() + } + + private fun newCall(request: HttpRequest, requestOptions: RequestOptions): Call { + val clientBuilder = okHttpClient.newBuilder() + + val logLevel = + when (System.getenv("IMAGE_KIT_LOG")?.lowercase()) { + "info" -> HttpLoggingInterceptor.Level.BASIC + "debug" -> HttpLoggingInterceptor.Level.BODY + else -> null + } + if (logLevel != null) { + clientBuilder.addNetworkInterceptor( + HttpLoggingInterceptor().setLevel(logLevel).apply { redactHeader("Authorization") } + ) + } + + requestOptions.timeout?.let { + clientBuilder + .connectTimeout(it.connect()) + .readTimeout(it.read()) + .writeTimeout(it.write()) + .callTimeout(it.request()) + } + + val client = clientBuilder.build() + return client.newCall(request.toRequest(client)) + } + + private fun HttpRequest.toRequest(client: okhttp3.OkHttpClient): Request { + var body: RequestBody? = body?.toRequestBody() + if (body == null && requiresBody(method)) { + body = "".toRequestBody() + } + + val builder = Request.Builder().url(toUrl()).method(method.name, body) + headers.names().forEach { name -> + headers.values(name).forEach { builder.header(name, it) } + } + + if ( + !headers.names().contains("X-Stainless-Read-Timeout") && client.readTimeoutMillis != 0 + ) { + builder.header( + "X-Stainless-Read-Timeout", + Duration.ofMillis(client.readTimeoutMillis.toLong()).seconds.toString(), + ) + } + if (!headers.names().contains("X-Stainless-Timeout") && client.callTimeoutMillis != 0) { + builder.header( + "X-Stainless-Timeout", + Duration.ofMillis(client.callTimeoutMillis.toLong()).seconds.toString(), + ) + } + + return builder.build() + } + + /** `OkHttpClient` always requires a request body for some methods. */ + private fun requiresBody(method: HttpMethod): Boolean = + when (method) { + HttpMethod.POST, + HttpMethod.PUT, + HttpMethod.PATCH -> true + else -> false + } + + private fun HttpRequest.toUrl(): String { + val builder = baseUrl.toHttpUrl().newBuilder() + pathSegments.forEach(builder::addPathSegment) + queryParams.keys().forEach { key -> + queryParams.values(key).forEach { builder.addQueryParameter(key, it) } + } + + return builder.toString() + } + + private fun HttpRequestBody.toRequestBody(): RequestBody { + val mediaType = contentType()?.toMediaType() + val length = contentLength() + + return object : RequestBody() { + override fun contentType(): MediaType? = mediaType + + override fun contentLength(): Long = length + + override fun isOneShot(): Boolean = !repeatable() + + override fun writeTo(sink: BufferedSink) = writeTo(sink.outputStream()) + } + } + + private fun Response.toResponse(): HttpResponse { + val headers = headers.toHeaders() + + return object : HttpResponse { + override fun statusCode(): Int = code + + override fun headers(): Headers = headers + + override fun body(): InputStream = body!!.byteStream() + + override fun close() = body!!.close() + } + } + + private fun okhttp3.Headers.toHeaders(): Headers { + val headersBuilder = Headers.builder() + forEach { (name, value) -> headersBuilder.put(name, value) } + return headersBuilder.build() + } + + companion object { + @JvmStatic fun builder() = Builder() + } + + class Builder internal constructor() { + + private var timeout: Timeout = Timeout.default() + private var proxy: Proxy? = null + private var sslSocketFactory: SSLSocketFactory? = null + private var trustManager: X509TrustManager? = null + private var hostnameVerifier: HostnameVerifier? = null + + fun timeout(timeout: Timeout) = apply { this.timeout = timeout } + + fun timeout(timeout: Duration) = timeout(Timeout.builder().request(timeout).build()) + + fun proxy(proxy: Proxy?) = apply { this.proxy = proxy } + + fun sslSocketFactory(sslSocketFactory: SSLSocketFactory?) = apply { + this.sslSocketFactory = sslSocketFactory + } + + fun trustManager(trustManager: X509TrustManager?) = apply { + this.trustManager = trustManager + } + + fun hostnameVerifier(hostnameVerifier: HostnameVerifier?) = apply { + this.hostnameVerifier = hostnameVerifier + } + + fun build(): OkHttpClient = + OkHttpClient( + okhttp3.OkHttpClient.Builder() + .connectTimeout(timeout.connect()) + .readTimeout(timeout.read()) + .writeTimeout(timeout.write()) + .callTimeout(timeout.request()) + .proxy(proxy) + .apply { + val sslSocketFactory = sslSocketFactory + val trustManager = trustManager + if (sslSocketFactory != null && trustManager != null) { + sslSocketFactory(sslSocketFactory, trustManager) + } else { + check((sslSocketFactory != null) == (trustManager != null)) { + "Both or none of `sslSocketFactory` and `trustManager` must be set, but only one was set" + } + } + + hostnameVerifier?.let(::hostnameVerifier) + } + .build() + .apply { + // We usually make all our requests to the same host so it makes sense to + // raise the per-host limit to the overall limit. + dispatcher.maxRequestsPerHost = dispatcher.maxRequests + } + ) + } +} diff --git a/image-kit-java-core/build.gradle.kts b/image-kit-java-core/build.gradle.kts new file mode 100644 index 0000000..9226395 --- /dev/null +++ b/image-kit-java-core/build.gradle.kts @@ -0,0 +1,41 @@ +plugins { + id("image-kit.kotlin") + id("image-kit.publish") +} + +configurations.all { + resolutionStrategy { + // Compile and test against a lower Jackson version to ensure we're compatible with it. + // We publish with a higher version (see below) to ensure users depend on a secure version by default. + force("com.fasterxml.jackson.core:jackson-core:2.13.4") + force("com.fasterxml.jackson.core:jackson-databind:2.13.4") + force("com.fasterxml.jackson.core:jackson-annotations:2.13.4") + force("com.fasterxml.jackson.datatype:jackson-datatype-jdk8:2.13.4") + force("com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.13.4") + force("com.fasterxml.jackson.module:jackson-module-kotlin:2.13.4") + } +} + +dependencies { + api("com.fasterxml.jackson.core:jackson-core:2.18.2") + api("com.fasterxml.jackson.core:jackson-databind:2.18.2") + api("com.google.errorprone:error_prone_annotations:2.33.0") + + implementation("com.fasterxml.jackson.core:jackson-annotations:2.18.2") + implementation("com.fasterxml.jackson.datatype:jackson-datatype-jdk8:2.18.2") + implementation("com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.18.2") + implementation("com.fasterxml.jackson.module:jackson-module-kotlin:2.18.2") + implementation("org.apache.httpcomponents.core5:httpcore5:5.2.4") + implementation("org.apache.httpcomponents.client5:httpclient5:5.3.1") + + testImplementation(kotlin("test")) + testImplementation(project(":image-kit-java-client-okhttp")) + testImplementation("com.github.tomakehurst:wiremock-jre8:2.35.2") + testImplementation("org.assertj:assertj-core:3.25.3") + testImplementation("org.junit.jupiter:junit-jupiter-api:5.9.3") + testImplementation("org.junit.jupiter:junit-jupiter-params:5.9.3") + testImplementation("org.junit-pioneer:junit-pioneer:1.9.1") + testImplementation("org.mockito:mockito-core:5.14.2") + testImplementation("org.mockito:mockito-junit-jupiter:5.14.2") + testImplementation("org.mockito.kotlin:mockito-kotlin:4.1.0") +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/client/ImageKitClient.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/client/ImageKitClient.kt new file mode 100644 index 0000000..ff5e227 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/client/ImageKitClient.kt @@ -0,0 +1,107 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.client + +import com.imagekit.api.core.ClientOptions +import com.imagekit.api.services.blocking.AccountService +import com.imagekit.api.services.blocking.AssetService +import com.imagekit.api.services.blocking.BetaService +import com.imagekit.api.services.blocking.CacheService +import com.imagekit.api.services.blocking.CustomMetadataFieldService +import com.imagekit.api.services.blocking.FileService +import com.imagekit.api.services.blocking.FolderService +import com.imagekit.api.services.blocking.WebhookService +import java.util.function.Consumer + +/** + * A client for interacting with the Image Kit REST API synchronously. You can also switch to + * asynchronous execution via the [async] method. + * + * This client performs best when you create a single instance and reuse it for all interactions + * with the REST API. This is because each client holds its own connection pool and thread pools. + * Reusing connections and threads reduces latency and saves memory. The client also handles rate + * limiting per client. This means that creating and using multiple instances at the same time will + * not respect rate limits. + * + * The threads and connections that are held will be released automatically if they remain idle. But + * if you are writing an application that needs to aggressively release unused resources, then you + * may call [close]. + */ +interface ImageKitClient { + + /** + * Returns a version of this client that uses asynchronous execution. + * + * The returned client shares its resources, like its connection pool and thread pools, with + * this client. + */ + fun async(): ImageKitClientAsync + + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): ImageKitClient + + fun customMetadataFields(): CustomMetadataFieldService + + fun files(): FileService + + fun assets(): AssetService + + fun cache(): CacheService + + fun folders(): FolderService + + fun accounts(): AccountService + + fun beta(): BetaService + + fun webhooks(): WebhookService + + /** + * Closes this client, relinquishing any underlying resources. + * + * This is purposefully not inherited from [AutoCloseable] because the client is long-lived and + * usually should not be synchronously closed via try-with-resources. + * + * It's also usually not necessary to call this method at all. the default HTTP client + * automatically releases threads and connections if they remain idle, but if you are writing an + * application that needs to aggressively release unused resources, then you may call this + * method. + */ + fun close() + + /** A view of [ImageKitClient] that provides access to raw HTTP responses for each method. */ + interface WithRawResponse { + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): ImageKitClient.WithRawResponse + + fun customMetadataFields(): CustomMetadataFieldService.WithRawResponse + + fun files(): FileService.WithRawResponse + + fun assets(): AssetService.WithRawResponse + + fun cache(): CacheService.WithRawResponse + + fun folders(): FolderService.WithRawResponse + + fun accounts(): AccountService.WithRawResponse + + fun beta(): BetaService.WithRawResponse + + fun webhooks(): WebhookService.WithRawResponse + } +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/client/ImageKitClientAsync.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/client/ImageKitClientAsync.kt new file mode 100644 index 0000000..2213152 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/client/ImageKitClientAsync.kt @@ -0,0 +1,111 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.client + +import com.imagekit.api.core.ClientOptions +import com.imagekit.api.services.async.AccountServiceAsync +import com.imagekit.api.services.async.AssetServiceAsync +import com.imagekit.api.services.async.BetaServiceAsync +import com.imagekit.api.services.async.CacheServiceAsync +import com.imagekit.api.services.async.CustomMetadataFieldServiceAsync +import com.imagekit.api.services.async.FileServiceAsync +import com.imagekit.api.services.async.FolderServiceAsync +import com.imagekit.api.services.async.WebhookServiceAsync +import java.util.function.Consumer + +/** + * A client for interacting with the Image Kit REST API asynchronously. You can also switch to + * synchronous execution via the [sync] method. + * + * This client performs best when you create a single instance and reuse it for all interactions + * with the REST API. This is because each client holds its own connection pool and thread pools. + * Reusing connections and threads reduces latency and saves memory. The client also handles rate + * limiting per client. This means that creating and using multiple instances at the same time will + * not respect rate limits. + * + * The threads and connections that are held will be released automatically if they remain idle. But + * if you are writing an application that needs to aggressively release unused resources, then you + * may call [close]. + */ +interface ImageKitClientAsync { + + /** + * Returns a version of this client that uses synchronous execution. + * + * The returned client shares its resources, like its connection pool and thread pools, with + * this client. + */ + fun sync(): ImageKitClient + + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): ImageKitClientAsync + + fun customMetadataFields(): CustomMetadataFieldServiceAsync + + fun files(): FileServiceAsync + + fun assets(): AssetServiceAsync + + fun cache(): CacheServiceAsync + + fun folders(): FolderServiceAsync + + fun accounts(): AccountServiceAsync + + fun beta(): BetaServiceAsync + + fun webhooks(): WebhookServiceAsync + + /** + * Closes this client, relinquishing any underlying resources. + * + * This is purposefully not inherited from [AutoCloseable] because the client is long-lived and + * usually should not be synchronously closed via try-with-resources. + * + * It's also usually not necessary to call this method at all. the default HTTP client + * automatically releases threads and connections if they remain idle, but if you are writing an + * application that needs to aggressively release unused resources, then you may call this + * method. + */ + fun close() + + /** + * A view of [ImageKitClientAsync] that provides access to raw HTTP responses for each method. + */ + interface WithRawResponse { + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions( + modifier: Consumer + ): ImageKitClientAsync.WithRawResponse + + fun customMetadataFields(): CustomMetadataFieldServiceAsync.WithRawResponse + + fun files(): FileServiceAsync.WithRawResponse + + fun assets(): AssetServiceAsync.WithRawResponse + + fun cache(): CacheServiceAsync.WithRawResponse + + fun folders(): FolderServiceAsync.WithRawResponse + + fun accounts(): AccountServiceAsync.WithRawResponse + + fun beta(): BetaServiceAsync.WithRawResponse + + fun webhooks(): WebhookServiceAsync.WithRawResponse + } +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/client/ImageKitClientAsyncImpl.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/client/ImageKitClientAsyncImpl.kt new file mode 100644 index 0000000..4ddc059 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/client/ImageKitClientAsyncImpl.kt @@ -0,0 +1,154 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.client + +import com.imagekit.api.core.ClientOptions +import com.imagekit.api.core.getPackageVersion +import com.imagekit.api.services.async.AccountServiceAsync +import com.imagekit.api.services.async.AccountServiceAsyncImpl +import com.imagekit.api.services.async.AssetServiceAsync +import com.imagekit.api.services.async.AssetServiceAsyncImpl +import com.imagekit.api.services.async.BetaServiceAsync +import com.imagekit.api.services.async.BetaServiceAsyncImpl +import com.imagekit.api.services.async.CacheServiceAsync +import com.imagekit.api.services.async.CacheServiceAsyncImpl +import com.imagekit.api.services.async.CustomMetadataFieldServiceAsync +import com.imagekit.api.services.async.CustomMetadataFieldServiceAsyncImpl +import com.imagekit.api.services.async.FileServiceAsync +import com.imagekit.api.services.async.FileServiceAsyncImpl +import com.imagekit.api.services.async.FolderServiceAsync +import com.imagekit.api.services.async.FolderServiceAsyncImpl +import com.imagekit.api.services.async.WebhookServiceAsync +import com.imagekit.api.services.async.WebhookServiceAsyncImpl +import java.util.function.Consumer + +class ImageKitClientAsyncImpl(private val clientOptions: ClientOptions) : ImageKitClientAsync { + + private val clientOptionsWithUserAgent = + if (clientOptions.headers.names().contains("User-Agent")) clientOptions + else + clientOptions + .toBuilder() + .putHeader("User-Agent", "${javaClass.simpleName}/Java ${getPackageVersion()}") + .build() + + // Pass the original clientOptions so that this client sets its own User-Agent. + private val sync: ImageKitClient by lazy { ImageKitClientImpl(clientOptions) } + + private val withRawResponse: ImageKitClientAsync.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + private val customMetadataFields: CustomMetadataFieldServiceAsync by lazy { + CustomMetadataFieldServiceAsyncImpl(clientOptionsWithUserAgent) + } + + private val files: FileServiceAsync by lazy { FileServiceAsyncImpl(clientOptionsWithUserAgent) } + + private val assets: AssetServiceAsync by lazy { + AssetServiceAsyncImpl(clientOptionsWithUserAgent) + } + + private val cache: CacheServiceAsync by lazy { + CacheServiceAsyncImpl(clientOptionsWithUserAgent) + } + + private val folders: FolderServiceAsync by lazy { + FolderServiceAsyncImpl(clientOptionsWithUserAgent) + } + + private val accounts: AccountServiceAsync by lazy { + AccountServiceAsyncImpl(clientOptionsWithUserAgent) + } + + private val beta: BetaServiceAsync by lazy { BetaServiceAsyncImpl(clientOptionsWithUserAgent) } + + private val webhooks: WebhookServiceAsync by lazy { + WebhookServiceAsyncImpl(clientOptionsWithUserAgent) + } + + override fun sync(): ImageKitClient = sync + + override fun withRawResponse(): ImageKitClientAsync.WithRawResponse = withRawResponse + + override fun withOptions(modifier: Consumer): ImageKitClientAsync = + ImageKitClientAsyncImpl(clientOptions.toBuilder().apply(modifier::accept).build()) + + override fun customMetadataFields(): CustomMetadataFieldServiceAsync = customMetadataFields + + override fun files(): FileServiceAsync = files + + override fun assets(): AssetServiceAsync = assets + + override fun cache(): CacheServiceAsync = cache + + override fun folders(): FolderServiceAsync = folders + + override fun accounts(): AccountServiceAsync = accounts + + override fun beta(): BetaServiceAsync = beta + + override fun webhooks(): WebhookServiceAsync = webhooks + + override fun close() = clientOptions.close() + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + ImageKitClientAsync.WithRawResponse { + + private val customMetadataFields: CustomMetadataFieldServiceAsync.WithRawResponse by lazy { + CustomMetadataFieldServiceAsyncImpl.WithRawResponseImpl(clientOptions) + } + + private val files: FileServiceAsync.WithRawResponse by lazy { + FileServiceAsyncImpl.WithRawResponseImpl(clientOptions) + } + + private val assets: AssetServiceAsync.WithRawResponse by lazy { + AssetServiceAsyncImpl.WithRawResponseImpl(clientOptions) + } + + private val cache: CacheServiceAsync.WithRawResponse by lazy { + CacheServiceAsyncImpl.WithRawResponseImpl(clientOptions) + } + + private val folders: FolderServiceAsync.WithRawResponse by lazy { + FolderServiceAsyncImpl.WithRawResponseImpl(clientOptions) + } + + private val accounts: AccountServiceAsync.WithRawResponse by lazy { + AccountServiceAsyncImpl.WithRawResponseImpl(clientOptions) + } + + private val beta: BetaServiceAsync.WithRawResponse by lazy { + BetaServiceAsyncImpl.WithRawResponseImpl(clientOptions) + } + + private val webhooks: WebhookServiceAsync.WithRawResponse by lazy { + WebhookServiceAsyncImpl.WithRawResponseImpl(clientOptions) + } + + override fun withOptions( + modifier: Consumer + ): ImageKitClientAsync.WithRawResponse = + ImageKitClientAsyncImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + override fun customMetadataFields(): CustomMetadataFieldServiceAsync.WithRawResponse = + customMetadataFields + + override fun files(): FileServiceAsync.WithRawResponse = files + + override fun assets(): AssetServiceAsync.WithRawResponse = assets + + override fun cache(): CacheServiceAsync.WithRawResponse = cache + + override fun folders(): FolderServiceAsync.WithRawResponse = folders + + override fun accounts(): AccountServiceAsync.WithRawResponse = accounts + + override fun beta(): BetaServiceAsync.WithRawResponse = beta + + override fun webhooks(): WebhookServiceAsync.WithRawResponse = webhooks + } +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/client/ImageKitClientImpl.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/client/ImageKitClientImpl.kt new file mode 100644 index 0000000..433b100 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/client/ImageKitClientImpl.kt @@ -0,0 +1,144 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.client + +import com.imagekit.api.core.ClientOptions +import com.imagekit.api.core.getPackageVersion +import com.imagekit.api.services.blocking.AccountService +import com.imagekit.api.services.blocking.AccountServiceImpl +import com.imagekit.api.services.blocking.AssetService +import com.imagekit.api.services.blocking.AssetServiceImpl +import com.imagekit.api.services.blocking.BetaService +import com.imagekit.api.services.blocking.BetaServiceImpl +import com.imagekit.api.services.blocking.CacheService +import com.imagekit.api.services.blocking.CacheServiceImpl +import com.imagekit.api.services.blocking.CustomMetadataFieldService +import com.imagekit.api.services.blocking.CustomMetadataFieldServiceImpl +import com.imagekit.api.services.blocking.FileService +import com.imagekit.api.services.blocking.FileServiceImpl +import com.imagekit.api.services.blocking.FolderService +import com.imagekit.api.services.blocking.FolderServiceImpl +import com.imagekit.api.services.blocking.WebhookService +import com.imagekit.api.services.blocking.WebhookServiceImpl +import java.util.function.Consumer + +class ImageKitClientImpl(private val clientOptions: ClientOptions) : ImageKitClient { + + private val clientOptionsWithUserAgent = + if (clientOptions.headers.names().contains("User-Agent")) clientOptions + else + clientOptions + .toBuilder() + .putHeader("User-Agent", "${javaClass.simpleName}/Java ${getPackageVersion()}") + .build() + + // Pass the original clientOptions so that this client sets its own User-Agent. + private val async: ImageKitClientAsync by lazy { ImageKitClientAsyncImpl(clientOptions) } + + private val withRawResponse: ImageKitClient.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + private val customMetadataFields: CustomMetadataFieldService by lazy { + CustomMetadataFieldServiceImpl(clientOptionsWithUserAgent) + } + + private val files: FileService by lazy { FileServiceImpl(clientOptionsWithUserAgent) } + + private val assets: AssetService by lazy { AssetServiceImpl(clientOptionsWithUserAgent) } + + private val cache: CacheService by lazy { CacheServiceImpl(clientOptionsWithUserAgent) } + + private val folders: FolderService by lazy { FolderServiceImpl(clientOptionsWithUserAgent) } + + private val accounts: AccountService by lazy { AccountServiceImpl(clientOptionsWithUserAgent) } + + private val beta: BetaService by lazy { BetaServiceImpl(clientOptionsWithUserAgent) } + + private val webhooks: WebhookService by lazy { WebhookServiceImpl(clientOptionsWithUserAgent) } + + override fun async(): ImageKitClientAsync = async + + override fun withRawResponse(): ImageKitClient.WithRawResponse = withRawResponse + + override fun withOptions(modifier: Consumer): ImageKitClient = + ImageKitClientImpl(clientOptions.toBuilder().apply(modifier::accept).build()) + + override fun customMetadataFields(): CustomMetadataFieldService = customMetadataFields + + override fun files(): FileService = files + + override fun assets(): AssetService = assets + + override fun cache(): CacheService = cache + + override fun folders(): FolderService = folders + + override fun accounts(): AccountService = accounts + + override fun beta(): BetaService = beta + + override fun webhooks(): WebhookService = webhooks + + override fun close() = clientOptions.close() + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + ImageKitClient.WithRawResponse { + + private val customMetadataFields: CustomMetadataFieldService.WithRawResponse by lazy { + CustomMetadataFieldServiceImpl.WithRawResponseImpl(clientOptions) + } + + private val files: FileService.WithRawResponse by lazy { + FileServiceImpl.WithRawResponseImpl(clientOptions) + } + + private val assets: AssetService.WithRawResponse by lazy { + AssetServiceImpl.WithRawResponseImpl(clientOptions) + } + + private val cache: CacheService.WithRawResponse by lazy { + CacheServiceImpl.WithRawResponseImpl(clientOptions) + } + + private val folders: FolderService.WithRawResponse by lazy { + FolderServiceImpl.WithRawResponseImpl(clientOptions) + } + + private val accounts: AccountService.WithRawResponse by lazy { + AccountServiceImpl.WithRawResponseImpl(clientOptions) + } + + private val beta: BetaService.WithRawResponse by lazy { + BetaServiceImpl.WithRawResponseImpl(clientOptions) + } + + private val webhooks: WebhookService.WithRawResponse by lazy { + WebhookServiceImpl.WithRawResponseImpl(clientOptions) + } + + override fun withOptions( + modifier: Consumer + ): ImageKitClient.WithRawResponse = + ImageKitClientImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + override fun customMetadataFields(): CustomMetadataFieldService.WithRawResponse = + customMetadataFields + + override fun files(): FileService.WithRawResponse = files + + override fun assets(): AssetService.WithRawResponse = assets + + override fun cache(): CacheService.WithRawResponse = cache + + override fun folders(): FolderService.WithRawResponse = folders + + override fun accounts(): AccountService.WithRawResponse = accounts + + override fun beta(): BetaService.WithRawResponse = beta + + override fun webhooks(): WebhookService.WithRawResponse = webhooks + } +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/BaseDeserializer.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/BaseDeserializer.kt new file mode 100644 index 0000000..106fb74 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/BaseDeserializer.kt @@ -0,0 +1,44 @@ +package com.imagekit.api.core + +import com.fasterxml.jackson.core.JsonParser +import com.fasterxml.jackson.core.ObjectCodec +import com.fasterxml.jackson.core.type.TypeReference +import com.fasterxml.jackson.databind.BeanProperty +import com.fasterxml.jackson.databind.DeserializationContext +import com.fasterxml.jackson.databind.JavaType +import com.fasterxml.jackson.databind.JsonDeserializer +import com.fasterxml.jackson.databind.JsonNode +import com.fasterxml.jackson.databind.deser.ContextualDeserializer +import com.fasterxml.jackson.databind.deser.std.StdDeserializer +import kotlin.reflect.KClass + +abstract class BaseDeserializer(type: KClass) : + StdDeserializer(type.java), ContextualDeserializer { + + override fun createContextual( + context: DeserializationContext, + property: BeanProperty?, + ): JsonDeserializer { + return this + } + + override fun deserialize(parser: JsonParser, context: DeserializationContext): T { + return parser.codec.deserialize(parser.readValueAsTree()) + } + + protected abstract fun ObjectCodec.deserialize(node: JsonNode): T + + protected fun ObjectCodec.tryDeserialize(node: JsonNode, type: TypeReference): T? = + try { + readValue(treeAsTokens(node), type) + } catch (e: Exception) { + null + } + + protected fun ObjectCodec.tryDeserialize(node: JsonNode, type: JavaType): T? = + try { + readValue(treeAsTokens(node), type) + } catch (e: Exception) { + null + } +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/BaseSerializer.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/BaseSerializer.kt new file mode 100644 index 0000000..b0d195b --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/BaseSerializer.kt @@ -0,0 +1,6 @@ +package com.imagekit.api.core + +import com.fasterxml.jackson.databind.ser.std.StdSerializer +import kotlin.reflect.KClass + +abstract class BaseSerializer(type: KClass) : StdSerializer(type.java) diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/Check.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/Check.kt new file mode 100644 index 0000000..f587fcc --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/Check.kt @@ -0,0 +1,96 @@ +@file:JvmName("Check") + +package com.imagekit.api.core + +import com.fasterxml.jackson.core.Version +import com.fasterxml.jackson.core.util.VersionUtil + +fun checkRequired(name: String, condition: Boolean) = + check(condition) { "`$name` is required, but was not set" } + +fun checkRequired(name: String, value: T?): T = + checkNotNull(value) { "`$name` is required, but was not set" } + +@JvmSynthetic +internal fun checkKnown(name: String, value: JsonField): T = + value.asKnown().orElseThrow { + IllegalStateException("`$name` is not a known type: ${value.javaClass.simpleName}") + } + +@JvmSynthetic +internal fun checkKnown(name: String, value: MultipartField): T = + value.value.asKnown().orElseThrow { + IllegalStateException("`$name` is not a known type: ${value.javaClass.simpleName}") + } + +@JvmSynthetic +internal fun checkLength(name: String, value: String, length: Int): String = + value.also { + check(it.length == length) { "`$name` must have length $length, but was ${it.length}" } + } + +@JvmSynthetic +internal fun checkMinLength(name: String, value: String, minLength: Int): String = + value.also { + check(it.length >= minLength) { + if (minLength == 1) "`$name` must be non-empty, but was empty" + else "`$name` must have at least length $minLength, but was ${it.length}" + } + } + +@JvmSynthetic +internal fun checkMaxLength(name: String, value: String, maxLength: Int): String = + value.also { + check(it.length <= maxLength) { + "`$name` must have at most length $maxLength, but was ${it.length}" + } + } + +@JvmSynthetic +internal fun checkJacksonVersionCompatibility() { + val incompatibleJacksonVersions = + RUNTIME_JACKSON_VERSIONS.mapNotNull { + val badVersionReason = BAD_JACKSON_VERSIONS[it.toString()] + when { + it.majorVersion != MINIMUM_JACKSON_VERSION.majorVersion -> + it to "incompatible major version" + it.minorVersion < MINIMUM_JACKSON_VERSION.minorVersion -> + it to "minor version too low" + it.minorVersion == MINIMUM_JACKSON_VERSION.minorVersion && + it.patchLevel < MINIMUM_JACKSON_VERSION.patchLevel -> + it to "patch version too low" + badVersionReason != null -> it to badVersionReason + else -> null + } + } + check(incompatibleJacksonVersions.isEmpty()) { + """ +This SDK requires a minimum Jackson version of $MINIMUM_JACKSON_VERSION, but the following incompatible Jackson versions were detected at runtime: + +${incompatibleJacksonVersions.asSequence().map { (version, incompatibilityReason) -> + "- `${version.toFullString().replace("/", ":")}` ($incompatibilityReason)" +}.joinToString("\n")} + +This can happen if you are either: +1. Directly depending on different Jackson versions +2. Depending on some library that depends on different Jackson versions, potentially transitively + +Double-check that you are depending on compatible Jackson versions. + +See https://www.github.com/imagekit-developer/imagekit-java#jackson for more information. + """ + .trimIndent() + } +} + +private val MINIMUM_JACKSON_VERSION: Version = VersionUtil.parseVersion("2.13.4", null, null) +private val BAD_JACKSON_VERSIONS: Map = + mapOf("2.18.1" to "due to https://github.com/FasterXML/jackson-databind/issues/4639") +private val RUNTIME_JACKSON_VERSIONS: List = + listOf( + com.fasterxml.jackson.core.json.PackageVersion.VERSION, + com.fasterxml.jackson.databind.cfg.PackageVersion.VERSION, + com.fasterxml.jackson.datatype.jdk8.PackageVersion.VERSION, + com.fasterxml.jackson.datatype.jsr310.PackageVersion.VERSION, + com.fasterxml.jackson.module.kotlin.PackageVersion.VERSION, + ) diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/ClientOptions.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/ClientOptions.kt new file mode 100644 index 0000000..7b379cd --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/ClientOptions.kt @@ -0,0 +1,496 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.core + +import com.fasterxml.jackson.databind.json.JsonMapper +import com.imagekit.api.core.http.Headers +import com.imagekit.api.core.http.HttpClient +import com.imagekit.api.core.http.PhantomReachableClosingHttpClient +import com.imagekit.api.core.http.QueryParams +import com.imagekit.api.core.http.RetryingHttpClient +import java.time.Clock +import java.time.Duration +import java.util.Base64 +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** A class representing the SDK client configuration. */ +class ClientOptions +private constructor( + private val originalHttpClient: HttpClient, + /** + * The HTTP client to use in the SDK. + * + * Use the one published in `image-kit-java-client-okhttp` or implement your own. + * + * This class takes ownership of the client and closes it when closed. + */ + @get:JvmName("httpClient") val httpClient: HttpClient, + /** + * Whether to throw an exception if any of the Jackson versions detected at runtime are + * incompatible with the SDK's minimum supported Jackson version (2.13.4). + * + * Defaults to true. Use extreme caution when disabling this option. There is no guarantee that + * the SDK will work correctly when using an incompatible Jackson version. + */ + @get:JvmName("checkJacksonVersionCompatibility") val checkJacksonVersionCompatibility: Boolean, + /** + * The Jackson JSON mapper to use for serializing and deserializing JSON. + * + * Defaults to [com.imagekit.api.core.jsonMapper]. The default is usually sufficient and rarely + * needs to be overridden. + */ + @get:JvmName("jsonMapper") val jsonMapper: JsonMapper, + /** + * The clock to use for operations that require timing, like retries. + * + * This is primarily useful for using a fake clock in tests. + * + * Defaults to [Clock.systemUTC]. + */ + @get:JvmName("clock") val clock: Clock, + private val baseUrl: String?, + /** Headers to send with the request. */ + @get:JvmName("headers") val headers: Headers, + /** Query params to send with the request. */ + @get:JvmName("queryParams") val queryParams: QueryParams, + /** + * Whether to call `validate` on every response before returning it. + * + * Defaults to false, which means the shape of the response will not be validated upfront. + * Instead, validation will only occur for the parts of the response that are accessed. + */ + @get:JvmName("responseValidation") val responseValidation: Boolean, + /** + * Sets the maximum time allowed for various parts of an HTTP call's lifecycle, excluding + * retries. + * + * Defaults to [Timeout.default]. + */ + @get:JvmName("timeout") val timeout: Timeout, + /** + * The maximum number of times to retry failed requests, with a short exponential backoff + * between requests. + * + * Only the following error types are retried: + * - Connection errors (for example, due to a network connectivity problem) + * - 408 Request Timeout + * - 409 Conflict + * - 429 Rate Limit + * - 5xx Internal + * + * The API may also explicitly instruct the SDK to retry or not retry a request. + * + * Defaults to 2. + */ + @get:JvmName("maxRetries") val maxRetries: Int, + /** + * Your ImageKit private API key (it starts with `private_`). You can view and manage API keys + * in the [dashboard](https://imagekit.io/dashboard/developer/api-keys). + */ + @get:JvmName("privateApiKey") val privateApiKey: String, + private val password: String?, + private val webhookSecret: String?, +) { + + init { + if (checkJacksonVersionCompatibility) { + checkJacksonVersionCompatibility() + } + } + + /** + * The base URL to use for every request. + * + * Defaults to the production environment: `https://api.imagekit.io`. + */ + fun baseUrl(): String = baseUrl ?: PRODUCTION_URL + + fun baseUrlOverridden(): Boolean = baseUrl != null + + /** + * ImageKit Basic Auth only uses the username field and ignores the password. This field is + * unused. + * + * Defaults to `"do_not_set"`. + */ + fun password(): Optional = Optional.ofNullable(password) + + /** + * Your ImageKit webhook secret. This is used by the SDK to verify webhook signatures. It starts + * with a `whsec_` prefix. You can view and manage your webhook secret in the + * [dashboard](https://imagekit.io/dashboard/developer/webhooks). Treat the secret like a + * password, keep it private and do not expose it publicly. Learn more about + * [webhook verification](https://imagekit.io/docs/webhooks#verify-webhook-signature). + */ + fun webhookSecret(): Optional = Optional.ofNullable(webhookSecret) + + fun toBuilder() = Builder().from(this) + + companion object { + + const val PRODUCTION_URL = "https://api.imagekit.io" + + /** + * Returns a mutable builder for constructing an instance of [ClientOptions]. + * + * The following fields are required: + * ```java + * .httpClient() + * .privateApiKey() + * ``` + */ + @JvmStatic fun builder() = Builder() + + /** + * Returns options configured using system properties and environment variables. + * + * @see Builder.fromEnv + */ + @JvmStatic fun fromEnv(): ClientOptions = builder().fromEnv().build() + } + + /** A builder for [ClientOptions]. */ + class Builder internal constructor() { + + private var httpClient: HttpClient? = null + private var checkJacksonVersionCompatibility: Boolean = true + private var jsonMapper: JsonMapper = jsonMapper() + private var clock: Clock = Clock.systemUTC() + private var baseUrl: String? = null + private var headers: Headers.Builder = Headers.builder() + private var queryParams: QueryParams.Builder = QueryParams.builder() + private var responseValidation: Boolean = false + private var timeout: Timeout = Timeout.default() + private var maxRetries: Int = 2 + private var privateApiKey: String? = null + private var password: String? = "do_not_set" + private var webhookSecret: String? = null + + @JvmSynthetic + internal fun from(clientOptions: ClientOptions) = apply { + httpClient = clientOptions.originalHttpClient + checkJacksonVersionCompatibility = clientOptions.checkJacksonVersionCompatibility + jsonMapper = clientOptions.jsonMapper + clock = clientOptions.clock + baseUrl = clientOptions.baseUrl + headers = clientOptions.headers.toBuilder() + queryParams = clientOptions.queryParams.toBuilder() + responseValidation = clientOptions.responseValidation + timeout = clientOptions.timeout + maxRetries = clientOptions.maxRetries + privateApiKey = clientOptions.privateApiKey + password = clientOptions.password + webhookSecret = clientOptions.webhookSecret + } + + /** + * The HTTP client to use in the SDK. + * + * Use the one published in `image-kit-java-client-okhttp` or implement your own. + * + * This class takes ownership of the client and closes it when closed. + */ + fun httpClient(httpClient: HttpClient) = apply { + this.httpClient = PhantomReachableClosingHttpClient(httpClient) + } + + /** + * Whether to throw an exception if any of the Jackson versions detected at runtime are + * incompatible with the SDK's minimum supported Jackson version (2.13.4). + * + * Defaults to true. Use extreme caution when disabling this option. There is no guarantee + * that the SDK will work correctly when using an incompatible Jackson version. + */ + fun checkJacksonVersionCompatibility(checkJacksonVersionCompatibility: Boolean) = apply { + this.checkJacksonVersionCompatibility = checkJacksonVersionCompatibility + } + + /** + * The Jackson JSON mapper to use for serializing and deserializing JSON. + * + * Defaults to [com.imagekit.api.core.jsonMapper]. The default is usually sufficient and + * rarely needs to be overridden. + */ + fun jsonMapper(jsonMapper: JsonMapper) = apply { this.jsonMapper = jsonMapper } + + /** + * The clock to use for operations that require timing, like retries. + * + * This is primarily useful for using a fake clock in tests. + * + * Defaults to [Clock.systemUTC]. + */ + fun clock(clock: Clock) = apply { this.clock = clock } + + /** + * The base URL to use for every request. + * + * Defaults to the production environment: `https://api.imagekit.io`. + */ + fun baseUrl(baseUrl: String?) = apply { this.baseUrl = baseUrl } + + /** Alias for calling [Builder.baseUrl] with `baseUrl.orElse(null)`. */ + fun baseUrl(baseUrl: Optional) = baseUrl(baseUrl.getOrNull()) + + /** + * Whether to call `validate` on every response before returning it. + * + * Defaults to false, which means the shape of the response will not be validated upfront. + * Instead, validation will only occur for the parts of the response that are accessed. + */ + fun responseValidation(responseValidation: Boolean) = apply { + this.responseValidation = responseValidation + } + + /** + * Sets the maximum time allowed for various parts of an HTTP call's lifecycle, excluding + * retries. + * + * Defaults to [Timeout.default]. + */ + fun timeout(timeout: Timeout) = apply { this.timeout = timeout } + + /** + * Sets the maximum time allowed for a complete HTTP call, not including retries. + * + * See [Timeout.request] for more details. + * + * For fine-grained control, pass a [Timeout] object. + */ + fun timeout(timeout: Duration) = timeout(Timeout.builder().request(timeout).build()) + + /** + * The maximum number of times to retry failed requests, with a short exponential backoff + * between requests. + * + * Only the following error types are retried: + * - Connection errors (for example, due to a network connectivity problem) + * - 408 Request Timeout + * - 409 Conflict + * - 429 Rate Limit + * - 5xx Internal + * + * The API may also explicitly instruct the SDK to retry or not retry a request. + * + * Defaults to 2. + */ + fun maxRetries(maxRetries: Int) = apply { this.maxRetries = maxRetries } + + /** + * Your ImageKit private API key (it starts with `private_`). You can view and manage API + * keys in the [dashboard](https://imagekit.io/dashboard/developer/api-keys). + */ + fun privateApiKey(privateApiKey: String) = apply { this.privateApiKey = privateApiKey } + + /** + * ImageKit Basic Auth only uses the username field and ignores the password. This field is + * unused. + * + * Defaults to `"do_not_set"`. + */ + fun password(password: String?) = apply { this.password = password } + + /** Alias for calling [Builder.password] with `password.orElse(null)`. */ + fun password(password: Optional) = password(password.getOrNull()) + + /** + * Your ImageKit webhook secret. This is used by the SDK to verify webhook signatures. It + * starts with a `whsec_` prefix. You can view and manage your webhook secret in the + * [dashboard](https://imagekit.io/dashboard/developer/webhooks). Treat the secret like a + * password, keep it private and do not expose it publicly. Learn more about + * [webhook verification](https://imagekit.io/docs/webhooks#verify-webhook-signature). + */ + fun webhookSecret(webhookSecret: String?) = apply { this.webhookSecret = webhookSecret } + + /** Alias for calling [Builder.webhookSecret] with `webhookSecret.orElse(null)`. */ + fun webhookSecret(webhookSecret: Optional) = + webhookSecret(webhookSecret.getOrNull()) + + fun headers(headers: Headers) = apply { + this.headers.clear() + putAllHeaders(headers) + } + + fun headers(headers: Map>) = apply { + this.headers.clear() + putAllHeaders(headers) + } + + fun putHeader(name: String, value: String) = apply { headers.put(name, value) } + + fun putHeaders(name: String, values: Iterable) = apply { headers.put(name, values) } + + fun putAllHeaders(headers: Headers) = apply { this.headers.putAll(headers) } + + fun putAllHeaders(headers: Map>) = apply { + this.headers.putAll(headers) + } + + fun replaceHeaders(name: String, value: String) = apply { headers.replace(name, value) } + + fun replaceHeaders(name: String, values: Iterable) = apply { + headers.replace(name, values) + } + + fun replaceAllHeaders(headers: Headers) = apply { this.headers.replaceAll(headers) } + + fun replaceAllHeaders(headers: Map>) = apply { + this.headers.replaceAll(headers) + } + + fun removeHeaders(name: String) = apply { headers.remove(name) } + + fun removeAllHeaders(names: Set) = apply { headers.removeAll(names) } + + fun queryParams(queryParams: QueryParams) = apply { + this.queryParams.clear() + putAllQueryParams(queryParams) + } + + fun queryParams(queryParams: Map>) = apply { + this.queryParams.clear() + putAllQueryParams(queryParams) + } + + fun putQueryParam(key: String, value: String) = apply { queryParams.put(key, value) } + + fun putQueryParams(key: String, values: Iterable) = apply { + queryParams.put(key, values) + } + + fun putAllQueryParams(queryParams: QueryParams) = apply { + this.queryParams.putAll(queryParams) + } + + fun putAllQueryParams(queryParams: Map>) = apply { + this.queryParams.putAll(queryParams) + } + + fun replaceQueryParams(key: String, value: String) = apply { + queryParams.replace(key, value) + } + + fun replaceQueryParams(key: String, values: Iterable) = apply { + queryParams.replace(key, values) + } + + fun replaceAllQueryParams(queryParams: QueryParams) = apply { + this.queryParams.replaceAll(queryParams) + } + + fun replaceAllQueryParams(queryParams: Map>) = apply { + this.queryParams.replaceAll(queryParams) + } + + fun removeQueryParams(key: String) = apply { queryParams.remove(key) } + + fun removeAllQueryParams(keys: Set) = apply { queryParams.removeAll(keys) } + + fun timeout(): Timeout = timeout + + /** + * Updates configuration using system properties and environment variables. + * + * See this table for the available options: + * + * |Setter |System property |Environment variable |Required|Default value | + * |---------------|--------------------------------------|--------------------------------|--------|---------------------------| + * |`privateApiKey`|`imagekit.imagekitPrivateApiKey` |`IMAGEKIT_PRIVATE_API_KEY` |true |- | + * |`password` |`imagekit.optionalImagekitIgnoresThis`|`OPTIONAL_IMAGEKIT_IGNORES_THIS`|false |`"do_not_set"` | + * |`webhookSecret`|`imagekit.imagekitWebhookSecret` |`IMAGEKIT_WEBHOOK_SECRET` |false |- | + * |`baseUrl` |`imagekit.baseUrl` |`IMAGE_KIT_BASE_URL` |true |`"https://api.imagekit.io"`| + * + * System properties take precedence over environment variables. + */ + fun fromEnv() = apply { + (System.getProperty("imagekit.baseUrl") ?: System.getenv("IMAGE_KIT_BASE_URL"))?.let { + baseUrl(it) + } + (System.getProperty("imagekit.imagekitPrivateApiKey") + ?: System.getenv("IMAGEKIT_PRIVATE_API_KEY")) + ?.let { privateApiKey(it) } + (System.getProperty("imagekit.optionalImagekitIgnoresThis") + ?: System.getenv("OPTIONAL_IMAGEKIT_IGNORES_THIS")) + ?.let { password(it) } + (System.getProperty("imagekit.imagekitWebhookSecret") + ?: System.getenv("IMAGEKIT_WEBHOOK_SECRET")) + ?.let { webhookSecret(it) } + } + + /** + * Returns an immutable instance of [ClientOptions]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .httpClient() + * .privateApiKey() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): ClientOptions { + val httpClient = checkRequired("httpClient", httpClient) + val privateApiKey = checkRequired("privateApiKey", privateApiKey) + + val headers = Headers.builder() + val queryParams = QueryParams.builder() + headers.put("X-Stainless-Lang", "java") + headers.put("X-Stainless-Arch", getOsArch()) + headers.put("X-Stainless-OS", getOsName()) + headers.put("X-Stainless-OS-Version", getOsVersion()) + headers.put("X-Stainless-Package-Version", getPackageVersion()) + headers.put("X-Stainless-Runtime", "JRE") + headers.put("X-Stainless-Runtime-Version", getJavaVersion()) + privateApiKey.let { username -> + password?.let { password -> + if (!username.isEmpty() && !password.isEmpty()) { + headers.put( + "Authorization", + "Basic ${Base64.getEncoder().encodeToString("$username:$password".toByteArray())}", + ) + } + } + } + headers.replaceAll(this.headers.build()) + queryParams.replaceAll(this.queryParams.build()) + + return ClientOptions( + httpClient, + RetryingHttpClient.builder() + .httpClient(httpClient) + .clock(clock) + .maxRetries(maxRetries) + .build(), + checkJacksonVersionCompatibility, + jsonMapper, + clock, + baseUrl, + headers.build(), + queryParams.build(), + responseValidation, + timeout, + maxRetries, + privateApiKey, + password, + webhookSecret, + ) + } + } + + /** + * Closes these client options, relinquishing any underlying resources. + * + * This is purposefully not inherited from [AutoCloseable] because the client options are + * long-lived and usually should not be synchronously closed via try-with-resources. + * + * It's also usually not necessary to call this method at all. the default client automatically + * releases threads and connections if they remain idle, but if you are writing an application + * that needs to aggressively release unused resources, then you may call this method. + */ + fun close() { + httpClient.close() + } +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/ObjectMappers.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/ObjectMappers.kt new file mode 100644 index 0000000..beaef0f --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/ObjectMappers.kt @@ -0,0 +1,167 @@ +@file:JvmName("ObjectMappers") + +package com.imagekit.api.core + +import com.fasterxml.jackson.annotation.JsonInclude +import com.fasterxml.jackson.core.JsonGenerator +import com.fasterxml.jackson.core.JsonParseException +import com.fasterxml.jackson.core.JsonParser +import com.fasterxml.jackson.databind.DeserializationContext +import com.fasterxml.jackson.databind.DeserializationFeature +import com.fasterxml.jackson.databind.MapperFeature +import com.fasterxml.jackson.databind.SerializationFeature +import com.fasterxml.jackson.databind.SerializerProvider +import com.fasterxml.jackson.databind.cfg.CoercionAction +import com.fasterxml.jackson.databind.cfg.CoercionInputShape +import com.fasterxml.jackson.databind.deser.std.StdDeserializer +import com.fasterxml.jackson.databind.json.JsonMapper +import com.fasterxml.jackson.databind.module.SimpleModule +import com.fasterxml.jackson.databind.type.LogicalType +import com.fasterxml.jackson.datatype.jdk8.Jdk8Module +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule +import com.fasterxml.jackson.module.kotlin.kotlinModule +import java.io.InputStream +import java.time.DateTimeException +import java.time.LocalDate +import java.time.LocalDateTime +import java.time.ZonedDateTime +import java.time.format.DateTimeFormatter +import java.time.temporal.ChronoField + +fun jsonMapper(): JsonMapper = + JsonMapper.builder() + .addModule(kotlinModule()) + .addModule(Jdk8Module()) + .addModule(JavaTimeModule()) + .addModule( + SimpleModule() + .addSerializer(InputStreamSerializer) + .addDeserializer(LocalDateTime::class.java, LenientLocalDateTimeDeserializer()) + ) + .withCoercionConfig(LogicalType.Boolean) { + it.setCoercion(CoercionInputShape.Integer, CoercionAction.Fail) + .setCoercion(CoercionInputShape.Float, CoercionAction.Fail) + .setCoercion(CoercionInputShape.String, CoercionAction.Fail) + .setCoercion(CoercionInputShape.Array, CoercionAction.Fail) + .setCoercion(CoercionInputShape.Object, CoercionAction.Fail) + } + .withCoercionConfig(LogicalType.Integer) { + it.setCoercion(CoercionInputShape.Boolean, CoercionAction.Fail) + .setCoercion(CoercionInputShape.String, CoercionAction.Fail) + .setCoercion(CoercionInputShape.Array, CoercionAction.Fail) + .setCoercion(CoercionInputShape.Object, CoercionAction.Fail) + } + .withCoercionConfig(LogicalType.Float) { + it.setCoercion(CoercionInputShape.Boolean, CoercionAction.Fail) + .setCoercion(CoercionInputShape.String, CoercionAction.Fail) + .setCoercion(CoercionInputShape.Array, CoercionAction.Fail) + .setCoercion(CoercionInputShape.Object, CoercionAction.Fail) + } + .withCoercionConfig(LogicalType.Textual) { + it.setCoercion(CoercionInputShape.Boolean, CoercionAction.Fail) + .setCoercion(CoercionInputShape.Integer, CoercionAction.Fail) + .setCoercion(CoercionInputShape.Float, CoercionAction.Fail) + .setCoercion(CoercionInputShape.Array, CoercionAction.Fail) + .setCoercion(CoercionInputShape.Object, CoercionAction.Fail) + } + .withCoercionConfig(LogicalType.Array) { + it.setCoercion(CoercionInputShape.Boolean, CoercionAction.Fail) + .setCoercion(CoercionInputShape.Integer, CoercionAction.Fail) + .setCoercion(CoercionInputShape.Float, CoercionAction.Fail) + .setCoercion(CoercionInputShape.String, CoercionAction.Fail) + .setCoercion(CoercionInputShape.Object, CoercionAction.Fail) + } + .withCoercionConfig(LogicalType.Collection) { + it.setCoercion(CoercionInputShape.Boolean, CoercionAction.Fail) + .setCoercion(CoercionInputShape.Integer, CoercionAction.Fail) + .setCoercion(CoercionInputShape.Float, CoercionAction.Fail) + .setCoercion(CoercionInputShape.String, CoercionAction.Fail) + .setCoercion(CoercionInputShape.Object, CoercionAction.Fail) + } + .withCoercionConfig(LogicalType.Map) { + it.setCoercion(CoercionInputShape.Boolean, CoercionAction.Fail) + .setCoercion(CoercionInputShape.Integer, CoercionAction.Fail) + .setCoercion(CoercionInputShape.Float, CoercionAction.Fail) + .setCoercion(CoercionInputShape.String, CoercionAction.Fail) + .setCoercion(CoercionInputShape.Object, CoercionAction.Fail) + } + .withCoercionConfig(LogicalType.POJO) { + it.setCoercion(CoercionInputShape.Boolean, CoercionAction.Fail) + .setCoercion(CoercionInputShape.Integer, CoercionAction.Fail) + .setCoercion(CoercionInputShape.Float, CoercionAction.Fail) + .setCoercion(CoercionInputShape.String, CoercionAction.Fail) + .setCoercion(CoercionInputShape.Array, CoercionAction.Fail) + } + .serializationInclusion(JsonInclude.Include.NON_ABSENT) + .disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE) + .disable(SerializationFeature.FLUSH_AFTER_WRITE_VALUE) + .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) + .disable(SerializationFeature.WRITE_DURATIONS_AS_TIMESTAMPS) + .disable(MapperFeature.ALLOW_COERCION_OF_SCALARS) + .disable(MapperFeature.AUTO_DETECT_CREATORS) + .disable(MapperFeature.AUTO_DETECT_FIELDS) + .disable(MapperFeature.AUTO_DETECT_GETTERS) + .disable(MapperFeature.AUTO_DETECT_IS_GETTERS) + .disable(MapperFeature.AUTO_DETECT_SETTERS) + .build() + +/** A serializer that serializes [InputStream] to bytes. */ +private object InputStreamSerializer : BaseSerializer(InputStream::class) { + + private fun readResolve(): Any = InputStreamSerializer + + override fun serialize( + value: InputStream?, + gen: JsonGenerator?, + serializers: SerializerProvider?, + ) { + if (value == null) { + gen?.writeNull() + } else { + value.use { gen?.writeBinary(it.readBytes()) } + } + } +} + +/** + * A deserializer that can deserialize [LocalDateTime] from datetimes, dates, and zoned datetimes. + */ +private class LenientLocalDateTimeDeserializer : + StdDeserializer(LocalDateTime::class.java) { + + companion object { + + private val DATE_TIME_FORMATTERS = + listOf( + DateTimeFormatter.ISO_LOCAL_DATE_TIME, + DateTimeFormatter.ISO_LOCAL_DATE, + DateTimeFormatter.ISO_ZONED_DATE_TIME, + ) + } + + override fun logicalType(): LogicalType = LogicalType.DateTime + + override fun deserialize(p: JsonParser, context: DeserializationContext?): LocalDateTime { + val exceptions = mutableListOf() + + for (formatter in DATE_TIME_FORMATTERS) { + try { + val temporal = formatter.parse(p.text) + + return when { + !temporal.isSupported(ChronoField.HOUR_OF_DAY) -> + LocalDate.from(temporal).atStartOfDay() + !temporal.isSupported(ChronoField.OFFSET_SECONDS) -> + LocalDateTime.from(temporal) + else -> ZonedDateTime.from(temporal).toLocalDateTime() + } + } catch (e: DateTimeException) { + exceptions.add(e) + } + } + + throw JsonParseException(p, "Cannot parse `LocalDateTime` from value: ${p.text}").apply { + exceptions.forEach { addSuppressed(it) } + } + } +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/Params.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/Params.kt new file mode 100644 index 0000000..2a62a93 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/Params.kt @@ -0,0 +1,16 @@ +package com.imagekit.api.core + +import com.imagekit.api.core.http.Headers +import com.imagekit.api.core.http.QueryParams + +/** An interface representing parameters passed to a service method. */ +interface Params { + /** The full set of headers in the parameters, including both fixed and additional headers. */ + fun _headers(): Headers + + /** + * The full set of query params in the parameters, including both fixed and additional query + * params. + */ + fun _queryParams(): QueryParams +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/PhantomReachable.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/PhantomReachable.kt new file mode 100644 index 0000000..d17a689 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/PhantomReachable.kt @@ -0,0 +1,56 @@ +@file:JvmName("PhantomReachable") + +package com.imagekit.api.core + +import com.imagekit.api.errors.ImageKitException +import java.lang.reflect.InvocationTargetException + +/** + * Closes [closeable] when [observed] becomes only phantom reachable. + * + * This is a wrapper around a Java 9+ [java.lang.ref.Cleaner], or a no-op in older Java versions. + */ +@JvmSynthetic +internal fun closeWhenPhantomReachable(observed: Any, closeable: AutoCloseable) { + check(observed !== closeable) { + "`observed` cannot be the same object as `closeable` because it would never become phantom reachable" + } + closeWhenPhantomReachable(observed, closeable::close) +} + +/** + * Calls [close] when [observed] becomes only phantom reachable. + * + * This is a wrapper around a Java 9+ [java.lang.ref.Cleaner], or a no-op in older Java versions. + */ +@JvmSynthetic +internal fun closeWhenPhantomReachable(observed: Any, close: () -> Unit) { + closeWhenPhantomReachable?.let { it(observed, close) } +} + +private val closeWhenPhantomReachable: ((Any, () -> Unit) -> Unit)? by lazy { + try { + val cleanerClass = Class.forName("java.lang.ref.Cleaner") + val cleanerCreate = cleanerClass.getMethod("create") + val cleanerRegister = + cleanerClass.getMethod("register", Any::class.java, Runnable::class.java) + val cleanerObject = cleanerCreate.invoke(null); + + { observed, close -> + try { + cleanerRegister.invoke(cleanerObject, observed, Runnable { close() }) + } catch (e: ReflectiveOperationException) { + if (e is InvocationTargetException) { + when (val cause = e.cause) { + is RuntimeException, + is Error -> throw cause + } + } + throw ImageKitException("Unexpected reflective invocation failure", e) + } + } + } catch (e: ReflectiveOperationException) { + // We're running Java 8, which has no Cleaner. + null + } +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/PhantomReachableExecutorService.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/PhantomReachableExecutorService.kt new file mode 100644 index 0000000..19a3538 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/PhantomReachableExecutorService.kt @@ -0,0 +1,58 @@ +package com.imagekit.api.core + +import java.util.concurrent.Callable +import java.util.concurrent.ExecutorService +import java.util.concurrent.Future +import java.util.concurrent.TimeUnit + +/** + * A delegating wrapper around an [ExecutorService] that shuts it down once it's only phantom + * reachable. + * + * This class ensures the [ExecutorService] is shut down even if the user forgets to do it. + */ +internal class PhantomReachableExecutorService(private val executorService: ExecutorService) : + ExecutorService { + init { + closeWhenPhantomReachable(this) { executorService.shutdown() } + } + + override fun execute(command: Runnable) = executorService.execute(command) + + override fun shutdown() = executorService.shutdown() + + override fun shutdownNow(): MutableList = executorService.shutdownNow() + + override fun isShutdown(): Boolean = executorService.isShutdown + + override fun isTerminated(): Boolean = executorService.isTerminated + + override fun awaitTermination(timeout: Long, unit: TimeUnit): Boolean = + executorService.awaitTermination(timeout, unit) + + override fun submit(task: Callable): Future = executorService.submit(task) + + override fun submit(task: Runnable, result: T): Future = + executorService.submit(task, result) + + override fun submit(task: Runnable): Future<*> = executorService.submit(task) + + override fun invokeAll( + tasks: MutableCollection> + ): MutableList> = executorService.invokeAll(tasks) + + override fun invokeAll( + tasks: MutableCollection>, + timeout: Long, + unit: TimeUnit, + ): MutableList> = executorService.invokeAll(tasks, timeout, unit) + + override fun invokeAny(tasks: MutableCollection>): T = + executorService.invokeAny(tasks) + + override fun invokeAny( + tasks: MutableCollection>, + timeout: Long, + unit: TimeUnit, + ): T = executorService.invokeAny(tasks, timeout, unit) +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/PrepareRequest.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/PrepareRequest.kt new file mode 100644 index 0000000..5ea20e4 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/PrepareRequest.kt @@ -0,0 +1,24 @@ +@file:JvmName("PrepareRequest") + +package com.imagekit.api.core + +import com.imagekit.api.core.http.HttpRequest +import java.util.concurrent.CompletableFuture + +@JvmSynthetic +internal fun HttpRequest.prepare(clientOptions: ClientOptions, params: Params): HttpRequest = + toBuilder() + .putAllQueryParams(clientOptions.queryParams) + .replaceAllQueryParams(params._queryParams()) + .putAllHeaders(clientOptions.headers) + .replaceAllHeaders(params._headers()) + .build() + +@JvmSynthetic +internal fun HttpRequest.prepareAsync( + clientOptions: ClientOptions, + params: Params, +): CompletableFuture = + // This async version exists to make it easier to add async specific preparation logic in the + // future. + CompletableFuture.completedFuture(prepare(clientOptions, params)) diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/Properties.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/Properties.kt new file mode 100644 index 0000000..bc15f01 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/Properties.kt @@ -0,0 +1,42 @@ +@file:JvmName("Properties") + +package com.imagekit.api.core + +import java.util.Properties + +fun getOsArch(): String { + val osArch = System.getProperty("os.arch") + + return when (osArch) { + null -> "unknown" + "i386", + "x32", + "x86" -> "x32" + "amd64", + "x86_64" -> "x64" + "arm" -> "arm" + "aarch64" -> "arm64" + else -> "other:${osArch}" + } +} + +fun getOsName(): String { + val osName = System.getProperty("os.name") + val vendorUrl = System.getProperty("java.vendor.url") + + return when { + osName == null -> "Unknown" + osName.startsWith("Linux") && vendorUrl == "http://www.android.com/" -> "Android" + osName.startsWith("Linux") -> "Linux" + osName.startsWith("Mac OS") -> "MacOS" + osName.startsWith("Windows") -> "Windows" + else -> "Other:${osName}" + } +} + +fun getOsVersion(): String = System.getProperty("os.version", "unknown") + +fun getPackageVersion(): String = + Properties::class.java.`package`.implementationVersion ?: "unknown" + +fun getJavaVersion(): String = System.getProperty("java.version", "unknown") diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/RequestOptions.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/RequestOptions.kt new file mode 100644 index 0000000..2d4840a --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/RequestOptions.kt @@ -0,0 +1,46 @@ +package com.imagekit.api.core + +import java.time.Duration + +class RequestOptions private constructor(val responseValidation: Boolean?, val timeout: Timeout?) { + + companion object { + + private val NONE = builder().build() + + @JvmStatic fun none() = NONE + + @JvmSynthetic + internal fun from(clientOptions: ClientOptions): RequestOptions = + builder() + .responseValidation(clientOptions.responseValidation) + .timeout(clientOptions.timeout) + .build() + + @JvmStatic fun builder() = Builder() + } + + fun applyDefaults(options: RequestOptions): RequestOptions = + RequestOptions( + responseValidation = responseValidation ?: options.responseValidation, + timeout = + if (options.timeout != null && timeout != null) timeout.assign(options.timeout) + else timeout ?: options.timeout, + ) + + class Builder internal constructor() { + + private var responseValidation: Boolean? = null + private var timeout: Timeout? = null + + fun responseValidation(responseValidation: Boolean) = apply { + this.responseValidation = responseValidation + } + + fun timeout(timeout: Timeout) = apply { this.timeout = timeout } + + fun timeout(timeout: Duration) = timeout(Timeout.builder().request(timeout).build()) + + fun build(): RequestOptions = RequestOptions(responseValidation, timeout) + } +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/Timeout.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/Timeout.kt new file mode 100644 index 0000000..5ca5989 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/Timeout.kt @@ -0,0 +1,171 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.core + +import java.time.Duration +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** A class containing timeouts for various processing phases of a request. */ +class Timeout +private constructor( + private val connect: Duration?, + private val read: Duration?, + private val write: Duration?, + private val request: Duration?, +) { + + /** + * The maximum time allowed to establish a connection with a host. + * + * A value of [Duration.ZERO] means there's no timeout. + * + * Defaults to `Duration.ofMinutes(1)`. + */ + fun connect(): Duration = connect ?: Duration.ofMinutes(1) + + /** + * The maximum time allowed between two data packets when waiting for the server’s response. + * + * A value of [Duration.ZERO] means there's no timeout. + * + * Defaults to `request()`. + */ + fun read(): Duration = read ?: request() + + /** + * The maximum time allowed between two data packets when sending the request to the server. + * + * A value of [Duration.ZERO] means there's no timeout. + * + * Defaults to `request()`. + */ + fun write(): Duration = write ?: request() + + /** + * The maximum time allowed for a complete HTTP call, not including retries. + * + * This includes resolving DNS, connecting, writing the request body, server processing, as well + * as reading the response body. + * + * A value of [Duration.ZERO] means there's no timeout. + * + * Defaults to `Duration.ofMinutes(1)`. + */ + fun request(): Duration = request ?: Duration.ofMinutes(1) + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun default() = builder().build() + + /** Returns a mutable builder for constructing an instance of [Timeout]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Timeout]. */ + class Builder internal constructor() { + + private var connect: Duration? = null + private var read: Duration? = null + private var write: Duration? = null + private var request: Duration? = null + + @JvmSynthetic + internal fun from(timeout: Timeout) = apply { + connect = timeout.connect + read = timeout.read + write = timeout.write + request = timeout.request + } + + /** + * The maximum time allowed to establish a connection with a host. + * + * A value of [Duration.ZERO] means there's no timeout. + * + * Defaults to `Duration.ofMinutes(1)`. + */ + fun connect(connect: Duration?) = apply { this.connect = connect } + + /** Alias for calling [Builder.connect] with `connect.orElse(null)`. */ + fun connect(connect: Optional) = connect(connect.getOrNull()) + + /** + * The maximum time allowed between two data packets when waiting for the server’s response. + * + * A value of [Duration.ZERO] means there's no timeout. + * + * Defaults to `request()`. + */ + fun read(read: Duration?) = apply { this.read = read } + + /** Alias for calling [Builder.read] with `read.orElse(null)`. */ + fun read(read: Optional) = read(read.getOrNull()) + + /** + * The maximum time allowed between two data packets when sending the request to the server. + * + * A value of [Duration.ZERO] means there's no timeout. + * + * Defaults to `request()`. + */ + fun write(write: Duration?) = apply { this.write = write } + + /** Alias for calling [Builder.write] with `write.orElse(null)`. */ + fun write(write: Optional) = write(write.getOrNull()) + + /** + * The maximum time allowed for a complete HTTP call, not including retries. + * + * This includes resolving DNS, connecting, writing the request body, server processing, as + * well as reading the response body. + * + * A value of [Duration.ZERO] means there's no timeout. + * + * Defaults to `Duration.ofMinutes(1)`. + */ + fun request(request: Duration?) = apply { this.request = request } + + /** Alias for calling [Builder.request] with `request.orElse(null)`. */ + fun request(request: Optional) = request(request.getOrNull()) + + /** + * Returns an immutable instance of [Timeout]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Timeout = Timeout(connect, read, write, request) + } + + @JvmSynthetic + internal fun assign(target: Timeout): Timeout = + target + .toBuilder() + .apply { + connect?.let(this::connect) + read?.let(this::read) + write?.let(this::write) + request?.let(this::request) + } + .build() + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Timeout && + connect == other.connect && + read == other.read && + write == other.write && + request == other.request + } + + override fun hashCode(): Int = Objects.hash(connect, read, write, request) + + override fun toString() = + "Timeout{connect=$connect, read=$read, write=$write, request=$request}" +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/Utils.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/Utils.kt new file mode 100644 index 0000000..2076536 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/Utils.kt @@ -0,0 +1,115 @@ +@file:JvmName("Utils") + +package com.imagekit.api.core + +import com.imagekit.api.errors.ImageKitInvalidDataException +import java.util.Collections +import java.util.SortedMap +import java.util.concurrent.CompletableFuture +import java.util.concurrent.locks.Lock + +@JvmSynthetic +internal fun T?.getOrThrow(name: String): T = + this ?: throw ImageKitInvalidDataException("`${name}` is not present") + +@JvmSynthetic +internal fun List.toImmutable(): List = + if (isEmpty()) Collections.emptyList() else Collections.unmodifiableList(toList()) + +@JvmSynthetic +internal fun Map.toImmutable(): Map = + if (isEmpty()) immutableEmptyMap() else Collections.unmodifiableMap(toMap()) + +@JvmSynthetic internal fun immutableEmptyMap(): Map = Collections.emptyMap() + +@JvmSynthetic +internal fun , V> SortedMap.toImmutable(): SortedMap = + if (isEmpty()) Collections.emptySortedMap() + else Collections.unmodifiableSortedMap(toSortedMap(comparator())) + +/** + * Returns all elements that yield the largest value for the given function, or an empty list if + * there are zero elements. + * + * This is similar to [Sequence.maxByOrNull] except it returns _all_ elements that yield the largest + * value; not just the first one. + */ +@JvmSynthetic +internal fun > Sequence.allMaxBy(selector: (T) -> R): List { + var maxValue: R? = null + val maxElements = mutableListOf() + + val iterator = iterator() + while (iterator.hasNext()) { + val element = iterator.next() + val value = selector(element) + if (maxValue == null || value > maxValue) { + maxValue = value + maxElements.clear() + maxElements.add(element) + } else if (value == maxValue) { + maxElements.add(element) + } + } + + return maxElements +} + +/** + * Returns whether [this] is equal to [other]. + * + * This differs from [Object.equals] because it also deeply equates arrays based on their contents, + * even when there are arrays directly nested within other arrays. + */ +@JvmSynthetic +internal infix fun Any?.contentEquals(other: Any?): Boolean = + arrayOf(this).contentDeepEquals(arrayOf(other)) + +/** + * Returns a hash of the given sequence of [values]. + * + * This differs from [java.util.Objects.hash] because it also deeply hashes arrays based on their + * contents, even when there are arrays directly nested within other arrays. + */ +@JvmSynthetic internal fun contentHash(vararg values: Any?): Int = values.contentDeepHashCode() + +/** + * Returns a [String] representation of [this]. + * + * This differs from [Object.toString] because it also deeply stringifies arrays based on their + * contents, even when there are arrays directly nested within other arrays. + */ +@JvmSynthetic +internal fun Any?.contentToString(): String { + var string = arrayOf(this).contentDeepToString() + if (string.startsWith('[')) { + string = string.substring(1) + } + if (string.endsWith(']')) { + string = string.substring(0, string.length - 1) + } + return string +} + +internal interface Enum + +/** + * Executes the given [action] while holding the lock, returning a [CompletableFuture] with the + * result. + * + * @param action The asynchronous action to execute while holding the lock + * @return A [CompletableFuture] that completes with the result of the action + */ +@JvmSynthetic +internal fun Lock.withLockAsync(action: () -> CompletableFuture): CompletableFuture { + lock() + val future = + try { + action() + } catch (e: Throwable) { + unlock() + throw e + } + future.whenComplete { _, _ -> unlock() } + return future +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/Values.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/Values.kt new file mode 100644 index 0000000..43bda41 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/Values.kt @@ -0,0 +1,723 @@ +package com.imagekit.api.core + +import com.fasterxml.jackson.annotation.JacksonAnnotationsInside +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonInclude +import com.fasterxml.jackson.core.JsonGenerator +import com.fasterxml.jackson.core.ObjectCodec +import com.fasterxml.jackson.core.type.TypeReference +import com.fasterxml.jackson.databind.BeanProperty +import com.fasterxml.jackson.databind.DeserializationContext +import com.fasterxml.jackson.databind.JavaType +import com.fasterxml.jackson.databind.JsonDeserializer +import com.fasterxml.jackson.databind.JsonNode +import com.fasterxml.jackson.databind.SerializerProvider +import com.fasterxml.jackson.databind.annotation.JsonDeserialize +import com.fasterxml.jackson.databind.annotation.JsonSerialize +import com.fasterxml.jackson.databind.node.JsonNodeType.ARRAY +import com.fasterxml.jackson.databind.node.JsonNodeType.BINARY +import com.fasterxml.jackson.databind.node.JsonNodeType.BOOLEAN +import com.fasterxml.jackson.databind.node.JsonNodeType.MISSING +import com.fasterxml.jackson.databind.node.JsonNodeType.NULL +import com.fasterxml.jackson.databind.node.JsonNodeType.NUMBER +import com.fasterxml.jackson.databind.node.JsonNodeType.OBJECT +import com.fasterxml.jackson.databind.node.JsonNodeType.POJO +import com.fasterxml.jackson.databind.node.JsonNodeType.STRING +import com.fasterxml.jackson.databind.ser.std.NullSerializer +import com.imagekit.api.errors.ImageKitInvalidDataException +import java.io.InputStream +import java.util.Objects +import java.util.Optional + +/** + * A class representing a serializable JSON field. + * + * It can either be a [KnownValue] value of type [T], matching the type the SDK expects, or an + * arbitrary JSON value that bypasses the type system (via [JsonValue]). + */ +@JsonDeserialize(using = JsonField.Deserializer::class) +sealed class JsonField { + + /** + * Returns whether this field is missing, which means it will be omitted from the serialized + * JSON entirely. + */ + fun isMissing(): Boolean = this is JsonMissing + + /** Whether this field is explicitly set to `null`. */ + fun isNull(): Boolean = this is JsonNull + + /** + * Returns an [Optional] containing this field's "known" value, meaning it matches the type the + * SDK expects, or an empty [Optional] if this field contains an arbitrary [JsonValue]. + * + * This is the opposite of [asUnknown]. + */ + fun asKnown(): + Optional< + // Safe because `Optional` is effectively covariant, but Kotlin doesn't know that. + @UnsafeVariance + T + > = Optional.ofNullable((this as? KnownValue)?.value) + + /** + * Returns an [Optional] containing this field's arbitrary [JsonValue], meaning it mismatches + * the type the SDK expects, or an empty [Optional] if this field contains a "known" value. + * + * This is the opposite of [asKnown]. + */ + fun asUnknown(): Optional = Optional.ofNullable(this as? JsonValue) + + /** + * Returns an [Optional] containing this field's boolean value, or an empty [Optional] if it + * doesn't contain a boolean. + * + * This method checks for both a [KnownValue] containing a boolean and for [JsonBoolean]. + */ + fun asBoolean(): Optional = + when (this) { + is JsonBoolean -> Optional.of(value) + is KnownValue -> Optional.ofNullable(value as? Boolean) + else -> Optional.empty() + } + + /** + * Returns an [Optional] containing this field's numerical value, or an empty [Optional] if it + * doesn't contain a number. + * + * This method checks for both a [KnownValue] containing a number and for [JsonNumber]. + */ + fun asNumber(): Optional = + when (this) { + is JsonNumber -> Optional.of(value) + is KnownValue -> Optional.ofNullable(value as? Number) + else -> Optional.empty() + } + + /** + * Returns an [Optional] containing this field's string value, or an empty [Optional] if it + * doesn't contain a string. + * + * This method checks for both a [KnownValue] containing a string and for [JsonString]. + */ + fun asString(): Optional = + when (this) { + is JsonString -> Optional.of(value) + is KnownValue -> Optional.ofNullable(value as? String) + else -> Optional.empty() + } + + fun asStringOrThrow(): String = + asString().orElseThrow { ImageKitInvalidDataException("Value is not a string") } + + /** + * Returns an [Optional] containing this field's list value, or an empty [Optional] if it + * doesn't contain a list. + * + * This method checks for both a [KnownValue] containing a list and for [JsonArray]. + */ + fun asArray(): Optional> = + when (this) { + is JsonArray -> Optional.of(values) + is KnownValue -> + Optional.ofNullable( + (value as? List<*>)?.map { + try { + JsonValue.from(it) + } catch (e: IllegalArgumentException) { + // The known value is a list, but not all values are convertible to + // `JsonValue`. + return Optional.empty() + } + } + ) + else -> Optional.empty() + } + + /** + * Returns an [Optional] containing this field's map value, or an empty [Optional] if it doesn't + * contain a map. + * + * This method checks for both a [KnownValue] containing a map and for [JsonObject]. + */ + fun asObject(): Optional> = + when (this) { + is JsonObject -> Optional.of(values) + is KnownValue -> + Optional.ofNullable( + (value as? Map<*, *>) + ?.map { (key, value) -> + if (key !is String) { + return Optional.empty() + } + + val jsonValue = + try { + JsonValue.from(value) + } catch (e: IllegalArgumentException) { + // The known value is a map, but not all items are convertible + // to `JsonValue`. + return Optional.empty() + } + + key to jsonValue + } + ?.toMap() + ) + else -> Optional.empty() + } + + @JvmSynthetic + internal fun getRequired(name: String): T = + when (this) { + is KnownValue -> value + is JsonMissing -> throw ImageKitInvalidDataException("`$name` is not set") + is JsonNull -> throw ImageKitInvalidDataException("`$name` is null") + else -> throw ImageKitInvalidDataException("`$name` is invalid, received $this") + } + + @JvmSynthetic + internal fun getOptional( + name: String + ): Optional< + // Safe because `Optional` is effectively covariant, but Kotlin doesn't know that. + @UnsafeVariance + T + > = + when (this) { + is KnownValue -> Optional.of(value) + is JsonMissing, + is JsonNull -> Optional.empty() + else -> throw ImageKitInvalidDataException("`$name` is invalid, received $this") + } + + @JvmSynthetic + internal fun map(transform: (T) -> R): JsonField = + when (this) { + is KnownValue -> KnownValue.of(transform(value)) + is JsonValue -> this + } + + @JvmSynthetic internal fun accept(consume: (T) -> Unit) = asKnown().ifPresent(consume) + + /** Returns the result of calling the [visitor] method corresponding to this field's state. */ + fun accept(visitor: Visitor): R = + when (this) { + is KnownValue -> visitor.visitKnown(value) + is JsonValue -> accept(visitor as JsonValue.Visitor) + } + + /** + * An interface that defines how to map each possible state of a `JsonField` to a value of + * type [R]. + */ + interface Visitor : JsonValue.Visitor { + + fun visitKnown(value: T): R = visitDefault() + } + + companion object { + + /** Returns a [JsonField] containing the given "known" [value]. */ + @JvmStatic fun of(value: T): JsonField = KnownValue.of(value) + + /** + * Returns a [JsonField] containing the given "known" [value], or [JsonNull] if [value] is + * null. + */ + @JvmStatic + fun ofNullable(value: T?): JsonField = + when (value) { + null -> JsonNull.of() + else -> KnownValue.of(value) + } + } + + /** + * This class is a Jackson filter that can be used to exclude missing properties from objects. + * This filter should not be used directly and should instead use the @ExcludeMissing + * annotation. + */ + class IsMissing { + + override fun equals(other: Any?): Boolean = other is JsonMissing + + override fun hashCode(): Int = Objects.hash() + } + + class Deserializer(private val type: JavaType? = null) : + BaseDeserializer>(JsonField::class) { + + override fun createContextual( + context: DeserializationContext, + property: BeanProperty?, + ): JsonDeserializer> = Deserializer(context.contextualType?.containedType(0)) + + override fun ObjectCodec.deserialize(node: JsonNode): JsonField<*> = + type?.let { tryDeserialize(node, type) }?.let { of(it) } + ?: JsonValue.fromJsonNode(node) + + override fun getNullValue(context: DeserializationContext): JsonField<*> = JsonNull.of() + } +} + +/** + * A class representing an arbitrary JSON value. + * + * It is immutable and assignable to any [JsonField], regardless of its expected type (i.e. its + * generic type argument). + */ +@JsonDeserialize(using = JsonValue.Deserializer::class) +sealed class JsonValue : JsonField() { + + fun convert(type: TypeReference): R? = JSON_MAPPER.convertValue(this, type) + + fun convert(type: Class): R? = JSON_MAPPER.convertValue(this, type) + + /** Returns the result of calling the [visitor] method corresponding to this value's variant. */ + fun accept(visitor: Visitor): R = + when (this) { + is JsonMissing -> visitor.visitMissing() + is JsonNull -> visitor.visitNull() + is JsonBoolean -> visitor.visitBoolean(value) + is JsonNumber -> visitor.visitNumber(value) + is JsonString -> visitor.visitString(value) + is JsonArray -> visitor.visitArray(values) + is JsonObject -> visitor.visitObject(values) + } + + /** + * An interface that defines how to map each variant state of a [JsonValue] to a value of type + * [R]. + */ + interface Visitor { + + fun visitNull(): R = visitDefault() + + fun visitMissing(): R = visitDefault() + + fun visitBoolean(value: Boolean): R = visitDefault() + + fun visitNumber(value: Number): R = visitDefault() + + fun visitString(value: String): R = visitDefault() + + fun visitArray(values: List): R = visitDefault() + + fun visitObject(values: Map): R = visitDefault() + + /** + * The default implementation for unimplemented visitor methods. + * + * @throws IllegalArgumentException in the default implementation. + */ + fun visitDefault(): R = throw IllegalArgumentException("Unexpected value") + } + + companion object { + + private val JSON_MAPPER = jsonMapper() + + /** + * Converts the given [value] to a [JsonValue]. + * + * This method works best on primitive types, [List] values, [Map] values, and nested + * combinations of these. For example: + * ```java + * // Create primitive JSON values + * JsonValue nullValue = JsonValue.from(null); + * JsonValue booleanValue = JsonValue.from(true); + * JsonValue numberValue = JsonValue.from(42); + * JsonValue stringValue = JsonValue.from("Hello World!"); + * + * // Create a JSON array value equivalent to `["Hello", "World"]` + * JsonValue arrayValue = JsonValue.from(List.of("Hello", "World")); + * + * // Create a JSON object value equivalent to `{ "a": 1, "b": 2 }` + * JsonValue objectValue = JsonValue.from(Map.of( + * "a", 1, + * "b", 2 + * )); + * + * // Create an arbitrarily nested JSON equivalent to: + * // { + * // "a": [1, 2], + * // "b": [3, 4] + * // } + * JsonValue complexValue = JsonValue.from(Map.of( + * "a", List.of(1, 2), + * "b", List.of(3, 4) + * )); + * ``` + * + * @throws IllegalArgumentException if [value] is not JSON serializable. + */ + @JvmStatic + fun from(value: Any?): JsonValue = + when (value) { + null -> JsonNull.of() + is JsonValue -> value + else -> JSON_MAPPER.convertValue(value, JsonValue::class.java) + } + + /** + * Returns a [JsonValue] converted from the given Jackson [JsonNode]. + * + * @throws IllegalStateException for unsupported node types. + */ + @JvmStatic + fun fromJsonNode(node: JsonNode): JsonValue = + when (node.nodeType) { + MISSING -> JsonMissing.of() + NULL -> JsonNull.of() + BOOLEAN -> JsonBoolean.of(node.booleanValue()) + NUMBER -> JsonNumber.of(node.numberValue()) + STRING -> JsonString.of(node.textValue()) + ARRAY -> + JsonArray.of(node.elements().asSequence().map { fromJsonNode(it) }.toList()) + OBJECT -> + JsonObject.of( + node.fields().asSequence().map { it.key to fromJsonNode(it.value) }.toMap() + ) + BINARY, + POJO, + null -> throw IllegalStateException("Unexpected JsonNode type: ${node.nodeType}") + } + } + + class Deserializer : BaseDeserializer(JsonValue::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): JsonValue = fromJsonNode(node) + + override fun getNullValue(context: DeserializationContext?): JsonValue = JsonNull.of() + } +} + +/** + * A class representing a "known" JSON serializable value of type [T], matching the type the SDK + * expects. + * + * It is assignable to `JsonField`. + */ +class KnownValue +private constructor( + @com.fasterxml.jackson.annotation.JsonValue @get:JvmName("value") val value: T +) : JsonField() { + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is KnownValue<*> && value contentEquals other.value + } + + override fun hashCode() = contentHash(value) + + override fun toString() = value.contentToString() + + companion object { + + /** Returns a [KnownValue] containing the given [value]. */ + @JsonCreator @JvmStatic fun of(value: T) = KnownValue(value) + } +} + +/** + * A [JsonValue] representing an omitted JSON field. + * + * An instance of this class will cause a JSON field to be omitted from the serialized JSON + * entirely. + */ +@JsonSerialize(using = JsonMissing.Serializer::class) +class JsonMissing : JsonValue() { + + override fun toString() = "" + + companion object { + + private val INSTANCE: JsonMissing = JsonMissing() + + /** Returns the singleton instance of [JsonMissing]. */ + @JvmStatic fun of() = INSTANCE + } + + class Serializer : BaseSerializer(JsonMissing::class) { + + override fun serialize( + value: JsonMissing, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + throw IllegalStateException("JsonMissing cannot be serialized") + } + } +} + +/** A [JsonValue] representing a JSON `null` value. */ +@JsonSerialize(using = NullSerializer::class) +class JsonNull : JsonValue() { + + override fun toString() = "null" + + companion object { + + private val INSTANCE: JsonNull = JsonNull() + + /** Returns the singleton instance of [JsonMissing]. */ + @JsonCreator @JvmStatic fun of() = INSTANCE + } +} + +/** A [JsonValue] representing a JSON boolean value. */ +class JsonBoolean +private constructor( + @get:com.fasterxml.jackson.annotation.JsonValue @get:JvmName("value") val value: Boolean +) : JsonValue() { + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is JsonBoolean && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + + companion object { + + /** Returns a [JsonBoolean] containing the given [value]. */ + @JsonCreator @JvmStatic fun of(value: Boolean) = JsonBoolean(value) + } +} + +/** A [JsonValue] representing a JSON number value. */ +class JsonNumber +private constructor( + @get:com.fasterxml.jackson.annotation.JsonValue @get:JvmName("value") val value: Number +) : JsonValue() { + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is JsonNumber && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + + companion object { + + /** Returns a [JsonNumber] containing the given [value]. */ + @JsonCreator @JvmStatic fun of(value: Number) = JsonNumber(value) + } +} + +/** A [JsonValue] representing a JSON string value. */ +class JsonString +private constructor( + @get:com.fasterxml.jackson.annotation.JsonValue @get:JvmName("value") val value: String +) : JsonValue() { + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is JsonString && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value + + companion object { + + /** Returns a [JsonString] containing the given [value]. */ + @JsonCreator @JvmStatic fun of(value: String) = JsonString(value) + } +} + +/** A [JsonValue] representing a JSON array value. */ +class JsonArray +private constructor( + @get:com.fasterxml.jackson.annotation.JsonValue + @get:JvmName("values") + val values: List +) : JsonValue() { + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is JsonArray && values == other.values + } + + override fun hashCode() = values.hashCode() + + override fun toString() = values.toString() + + companion object { + + /** Returns a [JsonArray] containing the given [values]. */ + @JsonCreator @JvmStatic fun of(values: List) = JsonArray(values.toImmutable()) + } +} + +/** A [JsonValue] representing a JSON object value. */ +class JsonObject +private constructor( + @get:com.fasterxml.jackson.annotation.JsonValue + @get:JvmName("values") + val values: Map +) : JsonValue() { + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is JsonObject && values == other.values + } + + override fun hashCode() = values.hashCode() + + override fun toString() = values.toString() + + companion object { + + /** Returns a [JsonObject] containing the given [values]. */ + @JsonCreator + @JvmStatic + fun of(values: Map) = JsonObject(values.toImmutable()) + } +} + +/** A Jackson annotation for excluding fields set to [JsonMissing] from the serialized JSON. */ +@JacksonAnnotationsInside +@JsonInclude(JsonInclude.Include.CUSTOM, valueFilter = JsonField.IsMissing::class) +annotation class ExcludeMissing + +/** A class representing a field in a `multipart/form-data` request. */ +class MultipartField +private constructor( + /** A [JsonField] value, which will be serialized to zero or more parts. */ + @get:com.fasterxml.jackson.annotation.JsonValue @get:JvmName("value") val value: JsonField, + /** A content type for the serialized parts. */ + @get:JvmName("contentType") val contentType: String, + private val filename: String?, +) { + + companion object { + + /** + * Returns a [MultipartField] containing the given [value] as a [KnownValue]. + * + * [contentType] will be set to `application/octet-stream` if [value] is binary data, or + * `text/plain; charset=utf-8` otherwise. + */ + @JvmStatic fun of(value: T?) = builder().value(value).build() + + /** + * Returns a [MultipartField] containing the given [value]. + * + * [contentType] will be set to `application/octet-stream` if [value] is binary data, or + * `text/plain; charset=utf-8` otherwise. + */ + @JvmStatic fun of(value: JsonField) = builder().value(value).build() + + /** + * Returns a mutable builder for constructing an instance of [MultipartField]. + * + * The following fields are required: + * ```java + * .value() + * ``` + * + * If [contentType] is unset, then it will be set to `application/octet-stream` if [value] + * is binary data, or `text/plain; charset=utf-8` otherwise. + */ + @JvmStatic fun builder() = Builder() + } + + /** Returns the filename directive that will be included in the serialized field. */ + fun filename(): Optional = Optional.ofNullable(filename) + + @JvmSynthetic + internal fun map(transform: (T) -> R): MultipartField = + builder().value(value.map(transform)).contentType(contentType).filename(filename).build() + + /** A builder for [MultipartField]. */ + class Builder internal constructor() { + + private var value: JsonField? = null + private var contentType: String? = null + private var filename: String? = null + + fun value(value: JsonField) = apply { this.value = value } + + fun value(value: T?) = value(JsonField.ofNullable(value)) + + fun contentType(contentType: String) = apply { this.contentType = contentType } + + fun filename(filename: String?) = apply { this.filename = filename } + + /** Alias for calling [Builder.filename] with `filename.orElse(null)`. */ + fun filename(filename: Optional) = filename(filename.orElse(null)) + + /** + * Returns an immutable instance of [MultipartField]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .value() + * ``` + * + * If [contentType] is unset, then it will be set to `application/octet-stream` if [value] + * is binary data, or `text/plain; charset=utf-8` otherwise. + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): MultipartField { + val value = checkRequired("value", value) + return MultipartField( + value, + contentType + ?: if ( + value is KnownValue && + (value.value is InputStream || value.value is ByteArray) + ) + "application/octet-stream" + else "text/plain; charset=utf-8", + filename, + ) + } + } + + private val hashCode: Int by lazy { contentHash(value, contentType, filename) } + + override fun hashCode(): Int = hashCode + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is MultipartField<*> && + value == other.value && + contentType == other.contentType && + filename == other.filename + } + + override fun toString(): String = + "MultipartField{value=$value, contentType=$contentType, filename=$filename}" +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/handlers/EmptyHandler.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/handlers/EmptyHandler.kt new file mode 100644 index 0000000..3828715 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/handlers/EmptyHandler.kt @@ -0,0 +1,12 @@ +@file:JvmName("EmptyHandler") + +package com.imagekit.api.core.handlers + +import com.imagekit.api.core.http.HttpResponse +import com.imagekit.api.core.http.HttpResponse.Handler + +@JvmSynthetic internal fun emptyHandler(): Handler = EmptyHandlerInternal + +private object EmptyHandlerInternal : Handler { + override fun handle(response: HttpResponse): Void? = null +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/handlers/ErrorHandler.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/handlers/ErrorHandler.kt new file mode 100644 index 0000000..203fb65 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/handlers/ErrorHandler.kt @@ -0,0 +1,84 @@ +// File generated from our OpenAPI spec by Stainless. + +@file:JvmName("ErrorHandler") + +package com.imagekit.api.core.handlers + +import com.fasterxml.jackson.databind.json.JsonMapper +import com.imagekit.api.core.JsonMissing +import com.imagekit.api.core.JsonValue +import com.imagekit.api.core.http.HttpResponse +import com.imagekit.api.core.http.HttpResponse.Handler +import com.imagekit.api.errors.BadRequestException +import com.imagekit.api.errors.InternalServerException +import com.imagekit.api.errors.NotFoundException +import com.imagekit.api.errors.PermissionDeniedException +import com.imagekit.api.errors.RateLimitException +import com.imagekit.api.errors.UnauthorizedException +import com.imagekit.api.errors.UnexpectedStatusCodeException +import com.imagekit.api.errors.UnprocessableEntityException + +@JvmSynthetic +internal fun errorBodyHandler(jsonMapper: JsonMapper): Handler { + val handler = jsonHandler(jsonMapper) + + return object : Handler { + override fun handle(response: HttpResponse): JsonValue = + try { + handler.handle(response) + } catch (e: Exception) { + JsonMissing.of() + } + } +} + +@JvmSynthetic +internal fun errorHandler(errorBodyHandler: Handler): Handler = + object : Handler { + override fun handle(response: HttpResponse): HttpResponse = + when (val statusCode = response.statusCode()) { + in 200..299 -> response + 400 -> + throw BadRequestException.builder() + .headers(response.headers()) + .body(errorBodyHandler.handle(response)) + .build() + 401 -> + throw UnauthorizedException.builder() + .headers(response.headers()) + .body(errorBodyHandler.handle(response)) + .build() + 403 -> + throw PermissionDeniedException.builder() + .headers(response.headers()) + .body(errorBodyHandler.handle(response)) + .build() + 404 -> + throw NotFoundException.builder() + .headers(response.headers()) + .body(errorBodyHandler.handle(response)) + .build() + 422 -> + throw UnprocessableEntityException.builder() + .headers(response.headers()) + .body(errorBodyHandler.handle(response)) + .build() + 429 -> + throw RateLimitException.builder() + .headers(response.headers()) + .body(errorBodyHandler.handle(response)) + .build() + in 500..599 -> + throw InternalServerException.builder() + .statusCode(statusCode) + .headers(response.headers()) + .body(errorBodyHandler.handle(response)) + .build() + else -> + throw UnexpectedStatusCodeException.builder() + .statusCode(statusCode) + .headers(response.headers()) + .body(errorBodyHandler.handle(response)) + .build() + } + } diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/handlers/JsonHandler.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/handlers/JsonHandler.kt new file mode 100644 index 0000000..7eedf38 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/handlers/JsonHandler.kt @@ -0,0 +1,20 @@ +@file:JvmName("JsonHandler") + +package com.imagekit.api.core.handlers + +import com.fasterxml.jackson.databind.json.JsonMapper +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.imagekit.api.core.http.HttpResponse +import com.imagekit.api.core.http.HttpResponse.Handler +import com.imagekit.api.errors.ImageKitInvalidDataException + +@JvmSynthetic +internal inline fun jsonHandler(jsonMapper: JsonMapper): Handler = + object : Handler { + override fun handle(response: HttpResponse): T = + try { + jsonMapper.readValue(response.body(), jacksonTypeRef()) + } catch (e: Exception) { + throw ImageKitInvalidDataException("Error reading response", e) + } + } diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/handlers/StringHandler.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/handlers/StringHandler.kt new file mode 100644 index 0000000..7c37450 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/handlers/StringHandler.kt @@ -0,0 +1,13 @@ +@file:JvmName("StringHandler") + +package com.imagekit.api.core.handlers + +import com.imagekit.api.core.http.HttpResponse +import com.imagekit.api.core.http.HttpResponse.Handler + +@JvmSynthetic internal fun stringHandler(): Handler = StringHandlerInternal + +private object StringHandlerInternal : Handler { + override fun handle(response: HttpResponse): String = + response.body().readBytes().toString(Charsets.UTF_8) +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/http/AsyncStreamResponse.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/http/AsyncStreamResponse.kt new file mode 100644 index 0000000..21385e3 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/http/AsyncStreamResponse.kt @@ -0,0 +1,157 @@ +package com.imagekit.api.core.http + +import com.imagekit.api.core.http.AsyncStreamResponse.Handler +import java.util.Optional +import java.util.concurrent.CompletableFuture +import java.util.concurrent.Executor +import java.util.concurrent.atomic.AtomicReference + +/** + * A class providing access to an API response as an asynchronous stream of chunks of type [T], + * where each chunk can be individually processed as soon as it arrives instead of waiting on the + * full response. + */ +interface AsyncStreamResponse { + + /** + * Registers [handler] to be called for events of this stream. + * + * [handler]'s methods will be called in the client's configured or default thread pool. + * + * @throws IllegalStateException if [subscribe] has already been called. + */ + fun subscribe(handler: Handler): AsyncStreamResponse + + /** + * Registers [handler] to be called for events of this stream. + * + * [handler]'s methods will be called in the given [executor]. + * + * @throws IllegalStateException if [subscribe] has already been called. + */ + fun subscribe(handler: Handler, executor: Executor): AsyncStreamResponse + + /** + * Returns a future that completes when a stream is fully consumed, errors, or gets closed + * early. + */ + fun onCompleteFuture(): CompletableFuture + + /** + * Closes this resource, relinquishing any underlying resources. + * + * This is purposefully not inherited from [AutoCloseable] because this response should not be + * synchronously closed via try-with-resources. + */ + fun close() + + /** A class for handling streaming events. */ + fun interface Handler { + + /** Called whenever a chunk is received. */ + fun onNext(value: T) + + /** + * Called when a stream is fully consumed, errors, or gets closed early. + * + * [onNext] will not be called once this method is called. + * + * @param error Non-empty if the stream completed due to an error. + */ + fun onComplete(error: Optional) {} + } +} + +@JvmSynthetic +internal fun CompletableFuture>.toAsync(streamHandlerExecutor: Executor) = + PhantomReachableClosingAsyncStreamResponse( + object : AsyncStreamResponse { + + private val onCompleteFuture = CompletableFuture() + private val state = AtomicReference(State.NEW) + + init { + this@toAsync.whenComplete { _, error -> + // If an error occurs from the original future, then we should resolve the + // `onCompleteFuture` even if `subscribe` has not been called. + error?.let(onCompleteFuture::completeExceptionally) + } + } + + override fun subscribe(handler: Handler): AsyncStreamResponse = + subscribe(handler, streamHandlerExecutor) + + override fun subscribe( + handler: Handler, + executor: Executor, + ): AsyncStreamResponse = apply { + // TODO(JDK): Use `compareAndExchange` once targeting JDK 9. + check(state.compareAndSet(State.NEW, State.SUBSCRIBED)) { + if (state.get() == State.SUBSCRIBED) "Cannot subscribe more than once" + else "Cannot subscribe after the response is closed" + } + + this@toAsync.whenCompleteAsync( + { streamResponse, futureError -> + if (state.get() == State.CLOSED) { + // Avoid doing any work if `close` was called before the future + // completed. + return@whenCompleteAsync + } + + if (futureError != null) { + // An error occurred before we started passing chunks to the handler. + handler.onComplete(Optional.of(futureError)) + return@whenCompleteAsync + } + + var streamError: Throwable? = null + try { + streamResponse.stream().forEach(handler::onNext) + } catch (e: Throwable) { + streamError = e + } + + try { + handler.onComplete(Optional.ofNullable(streamError)) + } finally { + try { + // Notify completion via the `onCompleteFuture` as well. This is in + // a separate `try-finally` block so that we still complete the + // future if `handler.onComplete` throws. + if (streamError == null) { + onCompleteFuture.complete(null) + } else { + onCompleteFuture.completeExceptionally(streamError) + } + } finally { + close() + } + } + }, + executor, + ) + } + + override fun onCompleteFuture(): CompletableFuture = onCompleteFuture + + override fun close() { + val previousState = state.getAndSet(State.CLOSED) + if (previousState == State.CLOSED) { + return + } + + this@toAsync.whenComplete { streamResponse, error -> streamResponse?.close() } + // When the stream is closed, we should always consider it closed. If it closed due + // to an error, then we will have already completed the future earlier, and this + // will be a no-op. + onCompleteFuture.complete(null) + } + } + ) + +private enum class State { + NEW, + SUBSCRIBED, + CLOSED, +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/http/Headers.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/http/Headers.kt new file mode 100644 index 0000000..9c6ac03 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/http/Headers.kt @@ -0,0 +1,115 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.core.http + +import com.imagekit.api.core.JsonArray +import com.imagekit.api.core.JsonBoolean +import com.imagekit.api.core.JsonMissing +import com.imagekit.api.core.JsonNull +import com.imagekit.api.core.JsonNumber +import com.imagekit.api.core.JsonObject +import com.imagekit.api.core.JsonString +import com.imagekit.api.core.JsonValue +import com.imagekit.api.core.toImmutable +import java.util.TreeMap + +class Headers +private constructor( + private val map: Map>, + @get:JvmName("size") val size: Int, +) { + + fun isEmpty(): Boolean = map.isEmpty() + + fun names(): Set = map.keys + + fun values(name: String): List = map[name].orEmpty() + + fun toBuilder(): Builder = Builder().putAll(map) + + companion object { + + @JvmStatic fun builder() = Builder() + } + + class Builder internal constructor() { + + private val map: MutableMap> = + TreeMap(String.CASE_INSENSITIVE_ORDER) + private var size: Int = 0 + + fun put(name: String, value: JsonValue): Builder = apply { + when (value) { + is JsonMissing, + is JsonNull -> {} + is JsonBoolean -> put(name, value.value.toString()) + is JsonNumber -> put(name, value.value.toString()) + is JsonString -> put(name, value.value) + is JsonArray -> value.values.forEach { put(name, it) } + is JsonObject -> + value.values.forEach { (nestedName, value) -> put("$name.$nestedName", value) } + } + } + + fun put(name: String, value: String) = apply { + map.getOrPut(name) { mutableListOf() }.add(value) + size++ + } + + fun put(name: String, values: Iterable) = apply { values.forEach { put(name, it) } } + + fun putAll(headers: Map>) = apply { headers.forEach(::put) } + + fun putAll(headers: Headers) = apply { + headers.names().forEach { put(it, headers.values(it)) } + } + + fun replace(name: String, value: String) = apply { + remove(name) + put(name, value) + } + + fun replace(name: String, values: Iterable) = apply { + remove(name) + put(name, values) + } + + fun replaceAll(headers: Map>) = apply { + headers.forEach(::replace) + } + + fun replaceAll(headers: Headers) = apply { + headers.names().forEach { replace(it, headers.values(it)) } + } + + fun remove(name: String) = apply { size -= map.remove(name).orEmpty().size } + + fun removeAll(names: Set) = apply { names.forEach(::remove) } + + fun clear() = apply { + map.clear() + size = 0 + } + + fun build() = + Headers( + map.mapValuesTo(TreeMap(String.CASE_INSENSITIVE_ORDER)) { (_, values) -> + values.toImmutable() + } + .toImmutable(), + size, + ) + } + + override fun hashCode(): Int = map.hashCode() + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Headers && map == other.map + } + + override fun toString(): String = "Headers{map=$map}" +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/http/HttpClient.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/http/HttpClient.kt new file mode 100644 index 0000000..c26e515 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/http/HttpClient.kt @@ -0,0 +1,26 @@ +package com.imagekit.api.core.http + +import com.imagekit.api.core.RequestOptions +import java.lang.AutoCloseable +import java.util.concurrent.CompletableFuture + +interface HttpClient : AutoCloseable { + + fun execute( + request: HttpRequest, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponse + + fun execute(request: HttpRequest): HttpResponse = execute(request, RequestOptions.none()) + + fun executeAsync( + request: HttpRequest, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + fun executeAsync(request: HttpRequest): CompletableFuture = + executeAsync(request, RequestOptions.none()) + + /** Overridden from [AutoCloseable] to not have a checked exception in its signature. */ + override fun close() +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/http/HttpMethod.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/http/HttpMethod.kt new file mode 100644 index 0000000..8f320c3 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/http/HttpMethod.kt @@ -0,0 +1,13 @@ +package com.imagekit.api.core.http + +enum class HttpMethod { + GET, + HEAD, + POST, + PUT, + DELETE, + CONNECT, + OPTIONS, + TRACE, + PATCH, +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/http/HttpRequest.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/http/HttpRequest.kt new file mode 100644 index 0000000..7cbf385 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/http/HttpRequest.kt @@ -0,0 +1,146 @@ +package com.imagekit.api.core.http + +import com.imagekit.api.core.checkRequired +import com.imagekit.api.core.toImmutable + +class HttpRequest +private constructor( + @get:JvmName("method") val method: HttpMethod, + @get:JvmName("baseUrl") val baseUrl: String, + @get:JvmName("pathSegments") val pathSegments: List, + @get:JvmName("headers") val headers: Headers, + @get:JvmName("queryParams") val queryParams: QueryParams, + @get:JvmName("body") val body: HttpRequestBody?, +) { + + fun toBuilder(): Builder = Builder().from(this) + + override fun toString(): String = + "HttpRequest{method=$method, baseUrl=$baseUrl, pathSegments=$pathSegments, headers=$headers, queryParams=$queryParams, body=$body}" + + companion object { + @JvmStatic fun builder() = Builder() + } + + class Builder internal constructor() { + + private var method: HttpMethod? = null + private var baseUrl: String? = null + private var pathSegments: MutableList = mutableListOf() + private var headers: Headers.Builder = Headers.builder() + private var queryParams: QueryParams.Builder = QueryParams.builder() + private var body: HttpRequestBody? = null + + @JvmSynthetic + internal fun from(request: HttpRequest) = apply { + method = request.method + baseUrl = request.baseUrl + pathSegments = request.pathSegments.toMutableList() + headers = request.headers.toBuilder() + queryParams = request.queryParams.toBuilder() + body = request.body + } + + fun method(method: HttpMethod) = apply { this.method = method } + + fun baseUrl(baseUrl: String) = apply { this.baseUrl = baseUrl } + + fun addPathSegment(pathSegment: String) = apply { pathSegments.add(pathSegment) } + + fun addPathSegments(vararg pathSegments: String) = apply { + this.pathSegments.addAll(pathSegments) + } + + fun headers(headers: Headers) = apply { + this.headers.clear() + putAllHeaders(headers) + } + + fun headers(headers: Map>) = apply { + this.headers.clear() + putAllHeaders(headers) + } + + fun putHeader(name: String, value: String) = apply { headers.put(name, value) } + + fun putHeaders(name: String, values: Iterable) = apply { headers.put(name, values) } + + fun putAllHeaders(headers: Headers) = apply { this.headers.putAll(headers) } + + fun putAllHeaders(headers: Map>) = apply { + this.headers.putAll(headers) + } + + fun replaceHeaders(name: String, value: String) = apply { headers.replace(name, value) } + + fun replaceHeaders(name: String, values: Iterable) = apply { + headers.replace(name, values) + } + + fun replaceAllHeaders(headers: Headers) = apply { this.headers.replaceAll(headers) } + + fun replaceAllHeaders(headers: Map>) = apply { + this.headers.replaceAll(headers) + } + + fun removeHeaders(name: String) = apply { headers.remove(name) } + + fun removeAllHeaders(names: Set) = apply { headers.removeAll(names) } + + fun queryParams(queryParams: QueryParams) = apply { + this.queryParams.clear() + putAllQueryParams(queryParams) + } + + fun queryParams(queryParams: Map>) = apply { + this.queryParams.clear() + putAllQueryParams(queryParams) + } + + fun putQueryParam(key: String, value: String) = apply { queryParams.put(key, value) } + + fun putQueryParams(key: String, values: Iterable) = apply { + queryParams.put(key, values) + } + + fun putAllQueryParams(queryParams: QueryParams) = apply { + this.queryParams.putAll(queryParams) + } + + fun putAllQueryParams(queryParams: Map>) = apply { + this.queryParams.putAll(queryParams) + } + + fun replaceQueryParams(key: String, value: String) = apply { + queryParams.replace(key, value) + } + + fun replaceQueryParams(key: String, values: Iterable) = apply { + queryParams.replace(key, values) + } + + fun replaceAllQueryParams(queryParams: QueryParams) = apply { + this.queryParams.replaceAll(queryParams) + } + + fun replaceAllQueryParams(queryParams: Map>) = apply { + this.queryParams.replaceAll(queryParams) + } + + fun removeQueryParams(key: String) = apply { queryParams.remove(key) } + + fun removeAllQueryParams(keys: Set) = apply { queryParams.removeAll(keys) } + + fun body(body: HttpRequestBody) = apply { this.body = body } + + fun build(): HttpRequest = + HttpRequest( + checkRequired("method", method), + checkRequired("baseUrl", baseUrl), + pathSegments.toImmutable(), + headers.build(), + queryParams.build(), + body, + ) + } +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/http/HttpRequestBodies.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/http/HttpRequestBodies.kt new file mode 100644 index 0000000..82008d2 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/http/HttpRequestBodies.kt @@ -0,0 +1,128 @@ +// File generated from our OpenAPI spec by Stainless. + +@file:JvmName("HttpRequestBodies") + +package com.imagekit.api.core.http + +import com.fasterxml.jackson.databind.JsonNode +import com.fasterxml.jackson.databind.json.JsonMapper +import com.fasterxml.jackson.databind.node.JsonNodeType +import com.imagekit.api.core.MultipartField +import com.imagekit.api.errors.ImageKitInvalidDataException +import java.io.InputStream +import java.io.OutputStream +import kotlin.jvm.optionals.getOrNull +import org.apache.hc.client5.http.entity.mime.MultipartEntityBuilder +import org.apache.hc.core5.http.ContentType +import org.apache.hc.core5.http.HttpEntity + +@JvmSynthetic +internal inline fun json(jsonMapper: JsonMapper, value: T): HttpRequestBody = + object : HttpRequestBody { + private val bytes: ByteArray by lazy { jsonMapper.writeValueAsBytes(value) } + + override fun writeTo(outputStream: OutputStream) = outputStream.write(bytes) + + override fun contentType(): String = "application/json" + + override fun contentLength(): Long = bytes.size.toLong() + + override fun repeatable(): Boolean = true + + override fun close() {} + } + +@JvmSynthetic +internal fun multipartFormData( + jsonMapper: JsonMapper, + fields: Map>, +): HttpRequestBody = + object : HttpRequestBody { + private val entity: HttpEntity by lazy { + MultipartEntityBuilder.create() + .apply { + fields.forEach { (name, field) -> + val knownValue = field.value.asKnown().getOrNull() + val parts = + if (knownValue is InputStream) { + // Read directly from the `InputStream` instead of reading it all + // into memory due to the `jsonMapper` serialization below. + sequenceOf(name to knownValue) + } else { + val node = jsonMapper.valueToTree(field.value) + serializePart(name, node) + } + + parts.forEach { (name, bytes) -> + addBinaryBody( + name, + bytes, + ContentType.parseLenient(field.contentType), + field.filename().getOrNull(), + ) + } + } + } + .build() + } + + private fun serializePart( + name: String, + node: JsonNode, + ): Sequence> = + when (node.nodeType) { + JsonNodeType.MISSING, + JsonNodeType.NULL -> emptySequence() + JsonNodeType.BINARY -> sequenceOf(name to node.binaryValue().inputStream()) + JsonNodeType.STRING -> sequenceOf(name to node.textValue().inputStream()) + JsonNodeType.BOOLEAN -> + sequenceOf(name to node.booleanValue().toString().inputStream()) + JsonNodeType.NUMBER -> + sequenceOf(name to node.numberValue().toString().inputStream()) + JsonNodeType.ARRAY -> + sequenceOf( + name to + node + .elements() + .asSequence() + .mapNotNull { element -> + when (element.nodeType) { + JsonNodeType.MISSING, + JsonNodeType.NULL -> null + JsonNodeType.STRING -> node.textValue() + JsonNodeType.BOOLEAN -> node.booleanValue().toString() + JsonNodeType.NUMBER -> node.numberValue().toString() + null, + JsonNodeType.BINARY, + JsonNodeType.ARRAY, + JsonNodeType.OBJECT, + JsonNodeType.POJO -> + throw ImageKitInvalidDataException( + "Unexpected JsonNode type in array: ${node.nodeType}" + ) + } + } + .joinToString(",") + .inputStream() + ) + JsonNodeType.OBJECT -> + node.fields().asSequence().flatMap { (key, value) -> + serializePart("$name[$key]", value) + } + JsonNodeType.POJO, + null -> + throw ImageKitInvalidDataException("Unexpected JsonNode type: ${node.nodeType}") + } + + private fun String.inputStream(): InputStream = toByteArray().inputStream() + + override fun writeTo(outputStream: OutputStream) = entity.writeTo(outputStream) + + override fun contentType(): String = entity.contentType + + override fun contentLength(): Long = entity.contentLength + + override fun repeatable(): Boolean = entity.isRepeatable + + override fun close() = entity.close() + } diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/http/HttpRequestBody.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/http/HttpRequestBody.kt new file mode 100644 index 0000000..3126971 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/http/HttpRequestBody.kt @@ -0,0 +1,25 @@ +package com.imagekit.api.core.http + +import java.io.OutputStream +import java.lang.AutoCloseable + +interface HttpRequestBody : AutoCloseable { + + fun writeTo(outputStream: OutputStream) + + fun contentType(): String? + + fun contentLength(): Long + + /** + * Determines if a request can be repeated in a meaningful way, for example before doing a + * retry. + * + * The most typical case when a request can't be retried is if the request body is being + * streamed. In this case the body data isn't available on subsequent attempts. + */ + fun repeatable(): Boolean + + /** Overridden from [AutoCloseable] to not have a checked exception in its signature. */ + override fun close() +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/http/HttpResponse.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/http/HttpResponse.kt new file mode 100644 index 0000000..4df614c --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/http/HttpResponse.kt @@ -0,0 +1,22 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.core.http + +import java.io.InputStream + +interface HttpResponse : AutoCloseable { + + fun statusCode(): Int + + fun headers(): Headers + + fun body(): InputStream + + /** Overridden from [AutoCloseable] to not have a checked exception in its signature. */ + override fun close() + + interface Handler { + + fun handle(response: HttpResponse): T + } +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/http/HttpResponseFor.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/http/HttpResponseFor.kt new file mode 100644 index 0000000..e8951c9 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/http/HttpResponseFor.kt @@ -0,0 +1,25 @@ +package com.imagekit.api.core.http + +import java.io.InputStream + +interface HttpResponseFor : HttpResponse { + + fun parse(): T +} + +@JvmSynthetic +internal fun HttpResponse.parseable(parse: () -> T): HttpResponseFor = + object : HttpResponseFor { + + private val parsed: T by lazy { parse() } + + override fun parse(): T = parsed + + override fun statusCode(): Int = this@parseable.statusCode() + + override fun headers(): Headers = this@parseable.headers() + + override fun body(): InputStream = this@parseable.body() + + override fun close() = this@parseable.close() + } diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/http/PhantomReachableClosingAsyncStreamResponse.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/http/PhantomReachableClosingAsyncStreamResponse.kt new file mode 100644 index 0000000..791212d --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/http/PhantomReachableClosingAsyncStreamResponse.kt @@ -0,0 +1,56 @@ +package com.imagekit.api.core.http + +import com.imagekit.api.core.closeWhenPhantomReachable +import com.imagekit.api.core.http.AsyncStreamResponse.Handler +import java.util.Optional +import java.util.concurrent.CompletableFuture +import java.util.concurrent.Executor + +/** + * A delegating wrapper around an `AsyncStreamResponse` that closes it once it's only phantom + * reachable. + * + * This class ensures the `AsyncStreamResponse` is closed even if the user forgets to close it. + */ +internal class PhantomReachableClosingAsyncStreamResponse( + private val asyncStreamResponse: AsyncStreamResponse +) : AsyncStreamResponse { + + /** + * An object used for keeping `asyncStreamResponse` open while the object is still reachable. + */ + private val reachabilityTracker = Object() + + init { + closeWhenPhantomReachable(reachabilityTracker, asyncStreamResponse::close) + } + + override fun subscribe(handler: Handler): AsyncStreamResponse = apply { + asyncStreamResponse.subscribe(TrackedHandler(handler, reachabilityTracker)) + } + + override fun subscribe(handler: Handler, executor: Executor): AsyncStreamResponse = + apply { + asyncStreamResponse.subscribe(TrackedHandler(handler, reachabilityTracker), executor) + } + + override fun onCompleteFuture(): CompletableFuture = + asyncStreamResponse.onCompleteFuture() + + override fun close() = asyncStreamResponse.close() +} + +/** + * A wrapper around a `Handler` that also references a `reachabilityTracker` object. + * + * Referencing the `reachabilityTracker` object prevents it from getting reclaimed while the handler + * is still reachable. + */ +private class TrackedHandler( + private val handler: Handler, + private val reachabilityTracker: Any, +) : Handler { + override fun onNext(value: T) = handler.onNext(value) + + override fun onComplete(error: Optional) = handler.onComplete(error) +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/http/PhantomReachableClosingHttpClient.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/http/PhantomReachableClosingHttpClient.kt new file mode 100644 index 0000000..fc9a25e --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/http/PhantomReachableClosingHttpClient.kt @@ -0,0 +1,26 @@ +package com.imagekit.api.core.http + +import com.imagekit.api.core.RequestOptions +import com.imagekit.api.core.closeWhenPhantomReachable +import java.util.concurrent.CompletableFuture + +/** + * A delegating wrapper around an `HttpClient` that closes it once it's only phantom reachable. + * + * This class ensures the `HttpClient` is closed even if the user forgets to close it. + */ +internal class PhantomReachableClosingHttpClient(private val httpClient: HttpClient) : HttpClient { + init { + closeWhenPhantomReachable(this, httpClient) + } + + override fun execute(request: HttpRequest, requestOptions: RequestOptions): HttpResponse = + httpClient.execute(request, requestOptions) + + override fun executeAsync( + request: HttpRequest, + requestOptions: RequestOptions, + ): CompletableFuture = httpClient.executeAsync(request, requestOptions) + + override fun close() = httpClient.close() +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/http/PhantomReachableClosingStreamResponse.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/http/PhantomReachableClosingStreamResponse.kt new file mode 100644 index 0000000..cf85656 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/http/PhantomReachableClosingStreamResponse.kt @@ -0,0 +1,21 @@ +package com.imagekit.api.core.http + +import com.imagekit.api.core.closeWhenPhantomReachable +import java.util.stream.Stream + +/** + * A delegating wrapper around a `StreamResponse` that closes it once it's only phantom reachable. + * + * This class ensures the `StreamResponse` is closed even if the user forgets to close it. + */ +internal class PhantomReachableClosingStreamResponse( + private val streamResponse: StreamResponse +) : StreamResponse { + init { + closeWhenPhantomReachable(this, streamResponse) + } + + override fun stream(): Stream = streamResponse.stream() + + override fun close() = streamResponse.close() +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/http/QueryParams.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/http/QueryParams.kt new file mode 100644 index 0000000..3f16c45 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/http/QueryParams.kt @@ -0,0 +1,129 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.core.http + +import com.imagekit.api.core.JsonArray +import com.imagekit.api.core.JsonBoolean +import com.imagekit.api.core.JsonMissing +import com.imagekit.api.core.JsonNull +import com.imagekit.api.core.JsonNumber +import com.imagekit.api.core.JsonObject +import com.imagekit.api.core.JsonString +import com.imagekit.api.core.JsonValue +import com.imagekit.api.core.toImmutable + +class QueryParams +private constructor( + private val map: Map>, + @get:JvmName("size") val size: Int, +) { + + fun isEmpty(): Boolean = map.isEmpty() + + fun keys(): Set = map.keys + + fun values(key: String): List = map[key].orEmpty() + + fun toBuilder(): Builder = Builder().putAll(map) + + companion object { + + @JvmStatic fun builder() = Builder() + } + + class Builder internal constructor() { + + private val map: MutableMap> = mutableMapOf() + private var size: Int = 0 + + fun put(key: String, value: JsonValue): Builder = apply { + when (value) { + is JsonMissing, + is JsonNull -> {} + is JsonBoolean -> put(key, value.value.toString()) + is JsonNumber -> put(key, value.value.toString()) + is JsonString -> put(key, value.value) + is JsonArray -> + put( + key, + value.values + .asSequence() + .mapNotNull { + when (it) { + is JsonMissing, + is JsonNull -> null + is JsonBoolean -> it.value.toString() + is JsonNumber -> it.value.toString() + is JsonString -> it.value + is JsonArray, + is JsonObject -> + throw IllegalArgumentException( + "Cannot comma separate non-primitives in query params" + ) + } + } + .joinToString(","), + ) + is JsonObject -> + value.values.forEach { (nestedKey, value) -> put("$key[$nestedKey]", value) } + } + } + + fun put(key: String, value: String) = apply { + map.getOrPut(key) { mutableListOf() }.add(value) + size++ + } + + fun put(key: String, values: Iterable) = apply { values.forEach { put(key, it) } } + + fun putAll(queryParams: Map>) = apply { + queryParams.forEach(::put) + } + + fun putAll(queryParams: QueryParams) = apply { + queryParams.keys().forEach { put(it, queryParams.values(it)) } + } + + fun replace(key: String, value: String) = apply { + remove(key) + put(key, value) + } + + fun replace(key: String, values: Iterable) = apply { + remove(key) + put(key, values) + } + + fun replaceAll(queryParams: Map>) = apply { + queryParams.forEach(::replace) + } + + fun replaceAll(queryParams: QueryParams) = apply { + queryParams.keys().forEach { replace(it, queryParams.values(it)) } + } + + fun remove(key: String) = apply { size -= map.remove(key).orEmpty().size } + + fun removeAll(keys: Set) = apply { keys.forEach(::remove) } + + fun clear() = apply { + map.clear() + size = 0 + } + + fun build() = + QueryParams(map.mapValues { (_, values) -> values.toImmutable() }.toImmutable(), size) + } + + override fun hashCode(): Int = map.hashCode() + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is QueryParams && map == other.map + } + + override fun toString(): String = "QueryParams{map=$map}" +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/http/RetryingHttpClient.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/http/RetryingHttpClient.kt new file mode 100644 index 0000000..e8e45be --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/http/RetryingHttpClient.kt @@ -0,0 +1,288 @@ +package com.imagekit.api.core.http + +import com.imagekit.api.core.RequestOptions +import com.imagekit.api.core.checkRequired +import com.imagekit.api.errors.ImageKitIoException +import com.imagekit.api.errors.ImageKitRetryableException +import java.io.IOException +import java.time.Clock +import java.time.Duration +import java.time.OffsetDateTime +import java.time.format.DateTimeFormatter +import java.time.format.DateTimeParseException +import java.time.temporal.ChronoUnit +import java.util.Timer +import java.util.TimerTask +import java.util.UUID +import java.util.concurrent.CompletableFuture +import java.util.concurrent.ThreadLocalRandom +import java.util.concurrent.TimeUnit +import java.util.function.Function +import kotlin.math.min +import kotlin.math.pow + +class RetryingHttpClient +private constructor( + private val httpClient: HttpClient, + private val sleeper: Sleeper, + private val clock: Clock, + private val maxRetries: Int, + private val idempotencyHeader: String?, +) : HttpClient { + + override fun execute(request: HttpRequest, requestOptions: RequestOptions): HttpResponse { + if (!isRetryable(request) || maxRetries <= 0) { + return httpClient.execute(request, requestOptions) + } + + var modifiedRequest = maybeAddIdempotencyHeader(request) + + // Don't send the current retry count in the headers if the caller set their own value. + val shouldSendRetryCount = + !modifiedRequest.headers.names().contains("X-Stainless-Retry-Count") + + var retries = 0 + + while (true) { + if (shouldSendRetryCount) { + modifiedRequest = setRetryCountHeader(modifiedRequest, retries) + } + + val response = + try { + val response = httpClient.execute(modifiedRequest, requestOptions) + if (++retries > maxRetries || !shouldRetry(response)) { + return response + } + + response + } catch (throwable: Throwable) { + if (++retries > maxRetries || !shouldRetry(throwable)) { + throw throwable + } + + null + } + + val backoffDuration = getRetryBackoffDuration(retries, response) + // All responses must be closed, so close the failed one before retrying. + response?.close() + sleeper.sleep(backoffDuration) + } + } + + override fun executeAsync( + request: HttpRequest, + requestOptions: RequestOptions, + ): CompletableFuture { + if (!isRetryable(request) || maxRetries <= 0) { + return httpClient.executeAsync(request, requestOptions) + } + + val modifiedRequest = maybeAddIdempotencyHeader(request) + + // Don't send the current retry count in the headers if the caller set their own value. + val shouldSendRetryCount = + !modifiedRequest.headers.names().contains("X-Stainless-Retry-Count") + + var retries = 0 + + fun executeWithRetries( + request: HttpRequest, + requestOptions: RequestOptions, + ): CompletableFuture { + val requestWithRetryCount = + if (shouldSendRetryCount) setRetryCountHeader(request, retries) else request + + return httpClient + .executeAsync(requestWithRetryCount, requestOptions) + .handleAsync( + fun( + response: HttpResponse?, + throwable: Throwable?, + ): CompletableFuture { + if (response != null) { + if (++retries > maxRetries || !shouldRetry(response)) { + return CompletableFuture.completedFuture(response) + } + } else { + if (++retries > maxRetries || !shouldRetry(throwable!!)) { + val failedFuture = CompletableFuture() + failedFuture.completeExceptionally(throwable) + return failedFuture + } + } + + val backoffDuration = getRetryBackoffDuration(retries, response) + // All responses must be closed, so close the failed one before retrying. + response?.close() + return sleeper.sleepAsync(backoffDuration).thenCompose { + executeWithRetries(requestWithRetryCount, requestOptions) + } + } + ) { + // Run in the same thread. + it.run() + } + .thenCompose(Function.identity()) + } + + return executeWithRetries(modifiedRequest, requestOptions) + } + + override fun close() = httpClient.close() + + private fun isRetryable(request: HttpRequest): Boolean = + // Some requests, such as when a request body is being streamed, cannot be retried because + // the body data aren't available on subsequent attempts. + request.body?.repeatable() ?: true + + private fun setRetryCountHeader(request: HttpRequest, retries: Int): HttpRequest = + request.toBuilder().replaceHeaders("X-Stainless-Retry-Count", retries.toString()).build() + + private fun idempotencyKey(): String = "stainless-java-retry-${UUID.randomUUID()}" + + private fun maybeAddIdempotencyHeader(request: HttpRequest): HttpRequest { + if (idempotencyHeader == null || request.headers.names().contains(idempotencyHeader)) { + return request + } + + return request + .toBuilder() + // Set a header to uniquely identify the request when retried. + .putHeader(idempotencyHeader, idempotencyKey()) + .build() + } + + private fun shouldRetry(response: HttpResponse): Boolean { + // Note: this is not a standard header + val shouldRetryHeader = response.headers().values("X-Should-Retry").getOrNull(0) + val statusCode = response.statusCode() + + return when { + // If the server explicitly says whether to retry, obey + shouldRetryHeader == "true" -> true + shouldRetryHeader == "false" -> false + + // Retry on request timeouts + statusCode == 408 -> true + // Retry on lock timeouts + statusCode == 409 -> true + // Retry on rate limits + statusCode == 429 -> true + // Retry internal errors + statusCode >= 500 -> true + else -> false + } + } + + private fun shouldRetry(throwable: Throwable): Boolean = + // Only retry known retryable exceptions, other exceptions are not intended to be retried. + throwable is IOException || + throwable is ImageKitIoException || + throwable is ImageKitRetryableException + + private fun getRetryBackoffDuration(retries: Int, response: HttpResponse?): Duration { + // About the Retry-After header: + // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After + response + ?.headers() + ?.let { headers -> + headers + .values("Retry-After-Ms") + .getOrNull(0) + ?.toFloatOrNull() + ?.times(TimeUnit.MILLISECONDS.toNanos(1)) + ?: headers.values("Retry-After").getOrNull(0)?.let { retryAfter -> + retryAfter.toFloatOrNull()?.times(TimeUnit.SECONDS.toNanos(1)) + ?: try { + ChronoUnit.MILLIS.between( + OffsetDateTime.now(clock), + OffsetDateTime.parse( + retryAfter, + DateTimeFormatter.RFC_1123_DATE_TIME, + ), + ) + } catch (e: DateTimeParseException) { + null + } + } + } + ?.let { retryAfterNanos -> + // If the API asks us to wait a certain amount of time (and it's a reasonable + // amount), just + // do what it says. + val retryAfter = Duration.ofNanos(retryAfterNanos.toLong()) + if (retryAfter in Duration.ofNanos(0)..Duration.ofMinutes(1)) { + return retryAfter + } + } + + // Apply exponential backoff, but not more than the max. + val backoffSeconds = min(0.5 * 2.0.pow(retries - 1), 8.0) + + // Apply some jitter + val jitter = 1.0 - 0.25 * ThreadLocalRandom.current().nextDouble() + + return Duration.ofNanos((TimeUnit.SECONDS.toNanos(1) * backoffSeconds * jitter).toLong()) + } + + companion object { + + @JvmStatic fun builder() = Builder() + } + + class Builder internal constructor() { + + private var httpClient: HttpClient? = null + private var sleeper: Sleeper = + object : Sleeper { + + private val timer = Timer("RetryingHttpClient", true) + + override fun sleep(duration: Duration) = Thread.sleep(duration.toMillis()) + + override fun sleepAsync(duration: Duration): CompletableFuture { + val future = CompletableFuture() + timer.schedule( + object : TimerTask() { + override fun run() { + future.complete(null) + } + }, + duration.toMillis(), + ) + return future + } + } + private var clock: Clock = Clock.systemUTC() + private var maxRetries: Int = 2 + private var idempotencyHeader: String? = null + + fun httpClient(httpClient: HttpClient) = apply { this.httpClient = httpClient } + + @JvmSynthetic internal fun sleeper(sleeper: Sleeper) = apply { this.sleeper = sleeper } + + fun clock(clock: Clock) = apply { this.clock = clock } + + fun maxRetries(maxRetries: Int) = apply { this.maxRetries = maxRetries } + + fun idempotencyHeader(header: String) = apply { this.idempotencyHeader = header } + + fun build(): HttpClient = + RetryingHttpClient( + checkRequired("httpClient", httpClient), + sleeper, + clock, + maxRetries, + idempotencyHeader, + ) + } + + internal interface Sleeper { + + fun sleep(duration: Duration) + + fun sleepAsync(duration: Duration): CompletableFuture + } +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/http/StreamResponse.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/http/StreamResponse.kt new file mode 100644 index 0000000..d5427be --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/core/http/StreamResponse.kt @@ -0,0 +1,19 @@ +package com.imagekit.api.core.http + +import java.util.stream.Stream + +interface StreamResponse : AutoCloseable { + + fun stream(): Stream + + /** Overridden from [AutoCloseable] to not have a checked exception in its signature. */ + override fun close() +} + +@JvmSynthetic +internal fun StreamResponse.map(transform: (T) -> R): StreamResponse = + object : StreamResponse { + override fun stream(): Stream = this@map.stream().map(transform) + + override fun close() = this@map.close() + } diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/errors/BadRequestException.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/errors/BadRequestException.kt new file mode 100644 index 0000000..c0928e0 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/errors/BadRequestException.kt @@ -0,0 +1,80 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.errors + +import com.imagekit.api.core.JsonValue +import com.imagekit.api.core.checkRequired +import com.imagekit.api.core.http.Headers +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +class BadRequestException +private constructor(private val headers: Headers, private val body: JsonValue, cause: Throwable?) : + ImageKitServiceException("400: $body", cause) { + + override fun statusCode(): Int = 400 + + override fun headers(): Headers = headers + + override fun body(): JsonValue = body + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [BadRequestException]. + * + * The following fields are required: + * ```java + * .headers() + * .body() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [BadRequestException]. */ + class Builder internal constructor() { + + private var headers: Headers? = null + private var body: JsonValue? = null + private var cause: Throwable? = null + + @JvmSynthetic + internal fun from(badRequestException: BadRequestException) = apply { + headers = badRequestException.headers + body = badRequestException.body + cause = badRequestException.cause + } + + fun headers(headers: Headers) = apply { this.headers = headers } + + fun body(body: JsonValue) = apply { this.body = body } + + fun cause(cause: Throwable?) = apply { this.cause = cause } + + /** Alias for calling [Builder.cause] with `cause.orElse(null)`. */ + fun cause(cause: Optional) = cause(cause.getOrNull()) + + /** + * Returns an immutable instance of [BadRequestException]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .headers() + * .body() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): BadRequestException = + BadRequestException( + checkRequired("headers", headers), + checkRequired("body", body), + cause, + ) + } +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/errors/ImageKitException.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/errors/ImageKitException.kt new file mode 100644 index 0000000..799b887 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/errors/ImageKitException.kt @@ -0,0 +1,5 @@ +package com.imagekit.api.errors + +open class ImageKitException +@JvmOverloads +constructor(message: String? = null, cause: Throwable? = null) : RuntimeException(message, cause) diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/errors/ImageKitInvalidDataException.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/errors/ImageKitInvalidDataException.kt new file mode 100644 index 0000000..5ab2f9b --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/errors/ImageKitInvalidDataException.kt @@ -0,0 +1,5 @@ +package com.imagekit.api.errors + +class ImageKitInvalidDataException +@JvmOverloads +constructor(message: String? = null, cause: Throwable? = null) : ImageKitException(message, cause) diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/errors/ImageKitIoException.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/errors/ImageKitIoException.kt new file mode 100644 index 0000000..0cb3609 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/errors/ImageKitIoException.kt @@ -0,0 +1,5 @@ +package com.imagekit.api.errors + +class ImageKitIoException +@JvmOverloads +constructor(message: String? = null, cause: Throwable? = null) : ImageKitException(message, cause) diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/errors/ImageKitRetryableException.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/errors/ImageKitRetryableException.kt new file mode 100644 index 0000000..a9c4e94 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/errors/ImageKitRetryableException.kt @@ -0,0 +1,14 @@ +package com.imagekit.api.errors + +/** + * Exception that indicates a transient error that can be retried. + * + * When this exception is thrown during an HTTP request, the SDK will automatically retry the + * request up to the maximum number of retries. + * + * @param message A descriptive error message + * @param cause The underlying cause of this exception, if any + */ +class ImageKitRetryableException +@JvmOverloads +constructor(message: String? = null, cause: Throwable? = null) : ImageKitException(message, cause) diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/errors/ImageKitServiceException.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/errors/ImageKitServiceException.kt new file mode 100644 index 0000000..3e8bb7c --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/errors/ImageKitServiceException.kt @@ -0,0 +1,17 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.errors + +import com.imagekit.api.core.JsonValue +import com.imagekit.api.core.http.Headers + +abstract class ImageKitServiceException +protected constructor(message: String, cause: Throwable? = null) : + ImageKitException(message, cause) { + + abstract fun statusCode(): Int + + abstract fun headers(): Headers + + abstract fun body(): JsonValue +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/errors/InternalServerException.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/errors/InternalServerException.kt new file mode 100644 index 0000000..dbdbcc0 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/errors/InternalServerException.kt @@ -0,0 +1,91 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.errors + +import com.imagekit.api.core.JsonValue +import com.imagekit.api.core.checkRequired +import com.imagekit.api.core.http.Headers +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +class InternalServerException +private constructor( + private val statusCode: Int, + private val headers: Headers, + private val body: JsonValue, + cause: Throwable?, +) : ImageKitServiceException("$statusCode: $body", cause) { + + override fun statusCode(): Int = statusCode + + override fun headers(): Headers = headers + + override fun body(): JsonValue = body + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [InternalServerException]. + * + * The following fields are required: + * ```java + * .statusCode() + * .headers() + * .body() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [InternalServerException]. */ + class Builder internal constructor() { + + private var statusCode: Int? = null + private var headers: Headers? = null + private var body: JsonValue? = null + private var cause: Throwable? = null + + @JvmSynthetic + internal fun from(internalServerException: InternalServerException) = apply { + statusCode = internalServerException.statusCode + headers = internalServerException.headers + body = internalServerException.body + cause = internalServerException.cause + } + + fun statusCode(statusCode: Int) = apply { this.statusCode = statusCode } + + fun headers(headers: Headers) = apply { this.headers = headers } + + fun body(body: JsonValue) = apply { this.body = body } + + fun cause(cause: Throwable?) = apply { this.cause = cause } + + /** Alias for calling [Builder.cause] with `cause.orElse(null)`. */ + fun cause(cause: Optional) = cause(cause.getOrNull()) + + /** + * Returns an immutable instance of [InternalServerException]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .statusCode() + * .headers() + * .body() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): InternalServerException = + InternalServerException( + checkRequired("statusCode", statusCode), + checkRequired("headers", headers), + checkRequired("body", body), + cause, + ) + } +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/errors/NotFoundException.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/errors/NotFoundException.kt new file mode 100644 index 0000000..6192616 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/errors/NotFoundException.kt @@ -0,0 +1,76 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.errors + +import com.imagekit.api.core.JsonValue +import com.imagekit.api.core.checkRequired +import com.imagekit.api.core.http.Headers +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +class NotFoundException +private constructor(private val headers: Headers, private val body: JsonValue, cause: Throwable?) : + ImageKitServiceException("404: $body", cause) { + + override fun statusCode(): Int = 404 + + override fun headers(): Headers = headers + + override fun body(): JsonValue = body + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [NotFoundException]. + * + * The following fields are required: + * ```java + * .headers() + * .body() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [NotFoundException]. */ + class Builder internal constructor() { + + private var headers: Headers? = null + private var body: JsonValue? = null + private var cause: Throwable? = null + + @JvmSynthetic + internal fun from(notFoundException: NotFoundException) = apply { + headers = notFoundException.headers + body = notFoundException.body + cause = notFoundException.cause + } + + fun headers(headers: Headers) = apply { this.headers = headers } + + fun body(body: JsonValue) = apply { this.body = body } + + fun cause(cause: Throwable?) = apply { this.cause = cause } + + /** Alias for calling [Builder.cause] with `cause.orElse(null)`. */ + fun cause(cause: Optional) = cause(cause.getOrNull()) + + /** + * Returns an immutable instance of [NotFoundException]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .headers() + * .body() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): NotFoundException = + NotFoundException(checkRequired("headers", headers), checkRequired("body", body), cause) + } +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/errors/PermissionDeniedException.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/errors/PermissionDeniedException.kt new file mode 100644 index 0000000..95f536b --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/errors/PermissionDeniedException.kt @@ -0,0 +1,80 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.errors + +import com.imagekit.api.core.JsonValue +import com.imagekit.api.core.checkRequired +import com.imagekit.api.core.http.Headers +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +class PermissionDeniedException +private constructor(private val headers: Headers, private val body: JsonValue, cause: Throwable?) : + ImageKitServiceException("403: $body", cause) { + + override fun statusCode(): Int = 403 + + override fun headers(): Headers = headers + + override fun body(): JsonValue = body + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [PermissionDeniedException]. + * + * The following fields are required: + * ```java + * .headers() + * .body() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [PermissionDeniedException]. */ + class Builder internal constructor() { + + private var headers: Headers? = null + private var body: JsonValue? = null + private var cause: Throwable? = null + + @JvmSynthetic + internal fun from(permissionDeniedException: PermissionDeniedException) = apply { + headers = permissionDeniedException.headers + body = permissionDeniedException.body + cause = permissionDeniedException.cause + } + + fun headers(headers: Headers) = apply { this.headers = headers } + + fun body(body: JsonValue) = apply { this.body = body } + + fun cause(cause: Throwable?) = apply { this.cause = cause } + + /** Alias for calling [Builder.cause] with `cause.orElse(null)`. */ + fun cause(cause: Optional) = cause(cause.getOrNull()) + + /** + * Returns an immutable instance of [PermissionDeniedException]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .headers() + * .body() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): PermissionDeniedException = + PermissionDeniedException( + checkRequired("headers", headers), + checkRequired("body", body), + cause, + ) + } +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/errors/RateLimitException.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/errors/RateLimitException.kt new file mode 100644 index 0000000..c9d078b --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/errors/RateLimitException.kt @@ -0,0 +1,80 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.errors + +import com.imagekit.api.core.JsonValue +import com.imagekit.api.core.checkRequired +import com.imagekit.api.core.http.Headers +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +class RateLimitException +private constructor(private val headers: Headers, private val body: JsonValue, cause: Throwable?) : + ImageKitServiceException("429: $body", cause) { + + override fun statusCode(): Int = 429 + + override fun headers(): Headers = headers + + override fun body(): JsonValue = body + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [RateLimitException]. + * + * The following fields are required: + * ```java + * .headers() + * .body() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [RateLimitException]. */ + class Builder internal constructor() { + + private var headers: Headers? = null + private var body: JsonValue? = null + private var cause: Throwable? = null + + @JvmSynthetic + internal fun from(rateLimitException: RateLimitException) = apply { + headers = rateLimitException.headers + body = rateLimitException.body + cause = rateLimitException.cause + } + + fun headers(headers: Headers) = apply { this.headers = headers } + + fun body(body: JsonValue) = apply { this.body = body } + + fun cause(cause: Throwable?) = apply { this.cause = cause } + + /** Alias for calling [Builder.cause] with `cause.orElse(null)`. */ + fun cause(cause: Optional) = cause(cause.getOrNull()) + + /** + * Returns an immutable instance of [RateLimitException]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .headers() + * .body() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): RateLimitException = + RateLimitException( + checkRequired("headers", headers), + checkRequired("body", body), + cause, + ) + } +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/errors/UnauthorizedException.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/errors/UnauthorizedException.kt new file mode 100644 index 0000000..46009ee --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/errors/UnauthorizedException.kt @@ -0,0 +1,80 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.errors + +import com.imagekit.api.core.JsonValue +import com.imagekit.api.core.checkRequired +import com.imagekit.api.core.http.Headers +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +class UnauthorizedException +private constructor(private val headers: Headers, private val body: JsonValue, cause: Throwable?) : + ImageKitServiceException("401: $body", cause) { + + override fun statusCode(): Int = 401 + + override fun headers(): Headers = headers + + override fun body(): JsonValue = body + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [UnauthorizedException]. + * + * The following fields are required: + * ```java + * .headers() + * .body() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [UnauthorizedException]. */ + class Builder internal constructor() { + + private var headers: Headers? = null + private var body: JsonValue? = null + private var cause: Throwable? = null + + @JvmSynthetic + internal fun from(unauthorizedException: UnauthorizedException) = apply { + headers = unauthorizedException.headers + body = unauthorizedException.body + cause = unauthorizedException.cause + } + + fun headers(headers: Headers) = apply { this.headers = headers } + + fun body(body: JsonValue) = apply { this.body = body } + + fun cause(cause: Throwable?) = apply { this.cause = cause } + + /** Alias for calling [Builder.cause] with `cause.orElse(null)`. */ + fun cause(cause: Optional) = cause(cause.getOrNull()) + + /** + * Returns an immutable instance of [UnauthorizedException]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .headers() + * .body() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): UnauthorizedException = + UnauthorizedException( + checkRequired("headers", headers), + checkRequired("body", body), + cause, + ) + } +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/errors/UnexpectedStatusCodeException.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/errors/UnexpectedStatusCodeException.kt new file mode 100644 index 0000000..f21d560 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/errors/UnexpectedStatusCodeException.kt @@ -0,0 +1,92 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.errors + +import com.imagekit.api.core.JsonValue +import com.imagekit.api.core.checkRequired +import com.imagekit.api.core.http.Headers +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +class UnexpectedStatusCodeException +private constructor( + private val statusCode: Int, + private val headers: Headers, + private val body: JsonValue, + cause: Throwable?, +) : ImageKitServiceException("$statusCode: $body", cause) { + + override fun statusCode(): Int = statusCode + + override fun headers(): Headers = headers + + override fun body(): JsonValue = body + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [UnexpectedStatusCodeException]. + * + * The following fields are required: + * ```java + * .statusCode() + * .headers() + * .body() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [UnexpectedStatusCodeException]. */ + class Builder internal constructor() { + + private var statusCode: Int? = null + private var headers: Headers? = null + private var body: JsonValue? = null + private var cause: Throwable? = null + + @JvmSynthetic + internal fun from(unexpectedStatusCodeException: UnexpectedStatusCodeException) = apply { + statusCode = unexpectedStatusCodeException.statusCode + headers = unexpectedStatusCodeException.headers + body = unexpectedStatusCodeException.body + cause = unexpectedStatusCodeException.cause + } + + fun statusCode(statusCode: Int) = apply { this.statusCode = statusCode } + + fun headers(headers: Headers) = apply { this.headers = headers } + + fun body(body: JsonValue) = apply { this.body = body } + + fun cause(cause: Throwable?) = apply { this.cause = cause } + + /** Alias for calling [Builder.cause] with `cause.orElse(null)`. */ + fun cause(cause: Optional) = cause(cause.getOrNull()) + + /** + * Returns an immutable instance of [UnexpectedStatusCodeException]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .statusCode() + * .headers() + * .body() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): UnexpectedStatusCodeException = + UnexpectedStatusCodeException( + checkRequired("statusCode", statusCode), + checkRequired("headers", headers), + checkRequired("body", body), + cause, + ) + } +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/errors/UnprocessableEntityException.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/errors/UnprocessableEntityException.kt new file mode 100644 index 0000000..2d46830 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/errors/UnprocessableEntityException.kt @@ -0,0 +1,80 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.errors + +import com.imagekit.api.core.JsonValue +import com.imagekit.api.core.checkRequired +import com.imagekit.api.core.http.Headers +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +class UnprocessableEntityException +private constructor(private val headers: Headers, private val body: JsonValue, cause: Throwable?) : + ImageKitServiceException("422: $body", cause) { + + override fun statusCode(): Int = 422 + + override fun headers(): Headers = headers + + override fun body(): JsonValue = body + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [UnprocessableEntityException]. + * + * The following fields are required: + * ```java + * .headers() + * .body() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [UnprocessableEntityException]. */ + class Builder internal constructor() { + + private var headers: Headers? = null + private var body: JsonValue? = null + private var cause: Throwable? = null + + @JvmSynthetic + internal fun from(unprocessableEntityException: UnprocessableEntityException) = apply { + headers = unprocessableEntityException.headers + body = unprocessableEntityException.body + cause = unprocessableEntityException.cause + } + + fun headers(headers: Headers) = apply { this.headers = headers } + + fun body(body: JsonValue) = apply { this.body = body } + + fun cause(cause: Throwable?) = apply { this.cause = cause } + + /** Alias for calling [Builder.cause] with `cause.orElse(null)`. */ + fun cause(cause: Optional) = cause(cause.getOrNull()) + + /** + * Returns an immutable instance of [UnprocessableEntityException]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .headers() + * .body() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): UnprocessableEntityException = + UnprocessableEntityException( + checkRequired("headers", headers), + checkRequired("body", body), + cause, + ) + } +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/BaseOverlay.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/BaseOverlay.kt new file mode 100644 index 0000000..7030982 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/BaseOverlay.kt @@ -0,0 +1,189 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.imagekit.api.core.ExcludeMissing +import com.imagekit.api.core.JsonField +import com.imagekit.api.core.JsonMissing +import com.imagekit.api.core.JsonValue +import com.imagekit.api.errors.ImageKitInvalidDataException +import java.util.Collections +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +class BaseOverlay +private constructor( + private val position: JsonField, + private val timing: JsonField, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("position") + @ExcludeMissing + position: JsonField = JsonMissing.of(), + @JsonProperty("timing") @ExcludeMissing timing: JsonField = JsonMissing.of(), + ) : this(position, timing, mutableMapOf()) + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun position(): Optional = position.getOptional("position") + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun timing(): Optional = timing.getOptional("timing") + + /** + * Returns the raw JSON value of [position]. + * + * Unlike [position], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("position") @ExcludeMissing fun _position(): JsonField = position + + /** + * Returns the raw JSON value of [timing]. + * + * Unlike [timing], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("timing") @ExcludeMissing fun _timing(): JsonField = timing + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [BaseOverlay]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [BaseOverlay]. */ + class Builder internal constructor() { + + private var position: JsonField = JsonMissing.of() + private var timing: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(baseOverlay: BaseOverlay) = apply { + position = baseOverlay.position + timing = baseOverlay.timing + additionalProperties = baseOverlay.additionalProperties.toMutableMap() + } + + fun position(position: OverlayPosition) = position(JsonField.of(position)) + + /** + * Sets [Builder.position] to an arbitrary JSON value. + * + * You should usually call [Builder.position] with a well-typed [OverlayPosition] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun position(position: JsonField) = apply { this.position = position } + + fun timing(timing: OverlayTiming) = timing(JsonField.of(timing)) + + /** + * Sets [Builder.timing] to an arbitrary JSON value. + * + * You should usually call [Builder.timing] with a well-typed [OverlayTiming] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun timing(timing: JsonField) = apply { this.timing = timing } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [BaseOverlay]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): BaseOverlay = + BaseOverlay(position, timing, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): BaseOverlay = apply { + if (validated) { + return@apply + } + + position().ifPresent { it.validate() } + timing().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (position.asKnown().getOrNull()?.validity() ?: 0) + + (timing.asKnown().getOrNull()?.validity() ?: 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is BaseOverlay && + position == other.position && + timing == other.timing && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(position, timing, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "BaseOverlay{position=$position, timing=$timing, additionalProperties=$additionalProperties}" +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/ImageOverlay.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/ImageOverlay.kt new file mode 100644 index 0000000..3c5b235 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/ImageOverlay.kt @@ -0,0 +1,534 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.imagekit.api.core.Enum +import com.imagekit.api.core.ExcludeMissing +import com.imagekit.api.core.JsonField +import com.imagekit.api.core.JsonMissing +import com.imagekit.api.core.JsonValue +import com.imagekit.api.core.checkKnown +import com.imagekit.api.core.checkRequired +import com.imagekit.api.core.toImmutable +import com.imagekit.api.errors.ImageKitInvalidDataException +import java.util.Collections +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +class ImageOverlay +private constructor( + private val position: JsonField, + private val timing: JsonField, + private val input: JsonField, + private val type: JsonValue, + private val encoding: JsonField, + private val transformation: JsonField>, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("position") + @ExcludeMissing + position: JsonField = JsonMissing.of(), + @JsonProperty("timing") @ExcludeMissing timing: JsonField = JsonMissing.of(), + @JsonProperty("input") @ExcludeMissing input: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(), + @JsonProperty("encoding") @ExcludeMissing encoding: JsonField = JsonMissing.of(), + @JsonProperty("transformation") + @ExcludeMissing + transformation: JsonField> = JsonMissing.of(), + ) : this(position, timing, input, type, encoding, transformation, mutableMapOf()) + + fun toBaseOverlay(): BaseOverlay = + BaseOverlay.builder().position(position).timing(timing).build() + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun position(): Optional = position.getOptional("position") + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun timing(): Optional = timing.getOptional("timing") + + /** + * Specifies the relative path to the image used as an overlay. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun input(): String = input.getRequired("input") + + /** + * Expected to always return the following: + * ```java + * JsonValue.from("image") + * ``` + * + * However, this method can be useful for debugging and logging (e.g. if the server responded + * with an unexpected value). + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type + + /** + * The input path can be included in the layer as either `i-{input}` or + * `ie-{base64_encoded_input}`. By default, the SDK determines the appropriate format + * automatically. To always use base64 encoding (`ie-{base64}`), set this parameter to `base64`. + * To always use plain text (`i-{input}`), set it to `plain`. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun encoding(): Optional = encoding.getOptional("encoding") + + /** + * Array of transformations to be applied to the overlay image. Supported transformations + * depends on the base/parent asset. See overlays on + * [Images](https://imagekit.io/docs/add-overlays-on-images#list-of-supported-image-transformations-in-image-layers) + * and + * [Videos](https://imagekit.io/docs/add-overlays-on-videos#list-of-transformations-supported-on-image-overlay). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun transformation(): Optional> = + transformation.getOptional("transformation") + + /** + * Returns the raw JSON value of [position]. + * + * Unlike [position], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("position") @ExcludeMissing fun _position(): JsonField = position + + /** + * Returns the raw JSON value of [timing]. + * + * Unlike [timing], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("timing") @ExcludeMissing fun _timing(): JsonField = timing + + /** + * Returns the raw JSON value of [input]. + * + * Unlike [input], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("input") @ExcludeMissing fun _input(): JsonField = input + + /** + * Returns the raw JSON value of [encoding]. + * + * Unlike [encoding], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("encoding") @ExcludeMissing fun _encoding(): JsonField = encoding + + /** + * Returns the raw JSON value of [transformation]. + * + * Unlike [transformation], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("transformation") + @ExcludeMissing + fun _transformation(): JsonField> = transformation + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [ImageOverlay]. + * + * The following fields are required: + * ```java + * .input() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ImageOverlay]. */ + class Builder internal constructor() { + + private var position: JsonField = JsonMissing.of() + private var timing: JsonField = JsonMissing.of() + private var input: JsonField? = null + private var type: JsonValue = JsonValue.from("image") + private var encoding: JsonField = JsonMissing.of() + private var transformation: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(imageOverlay: ImageOverlay) = apply { + position = imageOverlay.position + timing = imageOverlay.timing + input = imageOverlay.input + type = imageOverlay.type + encoding = imageOverlay.encoding + transformation = imageOverlay.transformation.map { it.toMutableList() } + additionalProperties = imageOverlay.additionalProperties.toMutableMap() + } + + fun position(position: OverlayPosition) = position(JsonField.of(position)) + + /** + * Sets [Builder.position] to an arbitrary JSON value. + * + * You should usually call [Builder.position] with a well-typed [OverlayPosition] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun position(position: JsonField) = apply { this.position = position } + + fun timing(timing: OverlayTiming) = timing(JsonField.of(timing)) + + /** + * Sets [Builder.timing] to an arbitrary JSON value. + * + * You should usually call [Builder.timing] with a well-typed [OverlayTiming] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun timing(timing: JsonField) = apply { this.timing = timing } + + /** Specifies the relative path to the image used as an overlay. */ + fun input(input: String) = input(JsonField.of(input)) + + /** + * Sets [Builder.input] to an arbitrary JSON value. + * + * You should usually call [Builder.input] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun input(input: JsonField) = apply { this.input = input } + + /** + * Sets the field to an arbitrary JSON value. + * + * It is usually unnecessary to call this method because the field defaults to the + * following: + * ```java + * JsonValue.from("image") + * ``` + * + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun type(type: JsonValue) = apply { this.type = type } + + /** + * The input path can be included in the layer as either `i-{input}` or + * `ie-{base64_encoded_input}`. By default, the SDK determines the appropriate format + * automatically. To always use base64 encoding (`ie-{base64}`), set this parameter to + * `base64`. To always use plain text (`i-{input}`), set it to `plain`. + */ + fun encoding(encoding: Encoding) = encoding(JsonField.of(encoding)) + + /** + * Sets [Builder.encoding] to an arbitrary JSON value. + * + * You should usually call [Builder.encoding] with a well-typed [Encoding] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun encoding(encoding: JsonField) = apply { this.encoding = encoding } + + /** + * Array of transformations to be applied to the overlay image. Supported transformations + * depends on the base/parent asset. See overlays on + * [Images](https://imagekit.io/docs/add-overlays-on-images#list-of-supported-image-transformations-in-image-layers) + * and + * [Videos](https://imagekit.io/docs/add-overlays-on-videos#list-of-transformations-supported-on-image-overlay). + */ + fun transformation(transformation: List) = + transformation(JsonField.of(transformation)) + + /** + * Sets [Builder.transformation] to an arbitrary JSON value. + * + * You should usually call [Builder.transformation] with a well-typed `List` + * value instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun transformation(transformation: JsonField>) = apply { + this.transformation = transformation.map { it.toMutableList() } + } + + /** + * Adds a single [Transformation] to [Builder.transformation]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addTransformation(transformation: Transformation) = apply { + this.transformation = + (this.transformation ?: JsonField.of(mutableListOf())).also { + checkKnown("transformation", it).add(transformation) + } + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ImageOverlay]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .input() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): ImageOverlay = + ImageOverlay( + position, + timing, + checkRequired("input", input), + type, + encoding, + (transformation ?: JsonMissing.of()).map { it.toImmutable() }, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): ImageOverlay = apply { + if (validated) { + return@apply + } + + position().ifPresent { it.validate() } + timing().ifPresent { it.validate() } + input() + _type().let { + if (it != JsonValue.from("image")) { + throw ImageKitInvalidDataException("'type' is invalid, received $it") + } + } + encoding().ifPresent { it.validate() } + transformation().ifPresent { it.forEach { it.validate() } } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (position.asKnown().getOrNull()?.validity() ?: 0) + + (timing.asKnown().getOrNull()?.validity() ?: 0) + + (if (input.asKnown().isPresent) 1 else 0) + + type.let { if (it == JsonValue.from("image")) 1 else 0 } + + (encoding.asKnown().getOrNull()?.validity() ?: 0) + + (transformation.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + /** + * The input path can be included in the layer as either `i-{input}` or + * `ie-{base64_encoded_input}`. By default, the SDK determines the appropriate format + * automatically. To always use base64 encoding (`ie-{base64}`), set this parameter to `base64`. + * To always use plain text (`i-{input}`), set it to `plain`. + */ + class Encoding @JsonCreator private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is on an + * older version than the API, then the API may respond with new members that the SDK is + * unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val AUTO = of("auto") + + @JvmField val PLAIN = of("plain") + + @JvmField val BASE64 = of("base64") + + @JvmStatic fun of(value: String) = Encoding(JsonField.of(value)) + } + + /** An enum containing [Encoding]'s known values. */ + enum class Known { + AUTO, + PLAIN, + BASE64, + } + + /** + * An enum containing [Encoding]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [Encoding] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if the + * SDK is on an older version than the API, then the API may respond with new members that + * the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + AUTO, + PLAIN, + BASE64, + /** An enum member indicating that [Encoding] was instantiated with an unknown value. */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] + * if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you want + * to throw for the unknown case. + */ + fun value(): Value = + when (this) { + AUTO -> Value.AUTO + PLAIN -> Value.PLAIN + BASE64 -> Value.BASE64 + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and don't + * want to throw for the unknown case. + * + * @throws ImageKitInvalidDataException if this class instance's value is a not a known + * member. + */ + fun known(): Known = + when (this) { + AUTO -> Known.AUTO + PLAIN -> Known.PLAIN + BASE64 -> Known.BASE64 + else -> throw ImageKitInvalidDataException("Unknown Encoding: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for debugging + * and generally doesn't throw. + * + * @throws ImageKitInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + ImageKitInvalidDataException("Value is not a String") + } + + private var validated: Boolean = false + + fun validate(): Encoding = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Encoding && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ImageOverlay && + position == other.position && + timing == other.timing && + input == other.input && + type == other.type && + encoding == other.encoding && + transformation == other.transformation && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(position, timing, input, type, encoding, transformation, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ImageOverlay{position=$position, timing=$timing, input=$input, type=$type, encoding=$encoding, transformation=$transformation, additionalProperties=$additionalProperties}" +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/Overlay.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/Overlay.kt new file mode 100644 index 0000000..51a9db0 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/Overlay.kt @@ -0,0 +1,267 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models + +import com.fasterxml.jackson.core.JsonGenerator +import com.fasterxml.jackson.core.ObjectCodec +import com.fasterxml.jackson.databind.JsonNode +import com.fasterxml.jackson.databind.SerializerProvider +import com.fasterxml.jackson.databind.annotation.JsonDeserialize +import com.fasterxml.jackson.databind.annotation.JsonSerialize +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.imagekit.api.core.BaseDeserializer +import com.imagekit.api.core.BaseSerializer +import com.imagekit.api.core.JsonValue +import com.imagekit.api.core.allMaxBy +import com.imagekit.api.core.getOrThrow +import com.imagekit.api.errors.ImageKitInvalidDataException +import java.util.Objects +import java.util.Optional + +/** + * Specifies an overlay to be applied on the parent image or video. ImageKit supports overlays + * including images, text, videos, subtitles, and solid colors. See + * [Overlay using layers](https://imagekit.io/docs/transformations#overlay-using-layers). + */ +@JsonDeserialize(using = Overlay.Deserializer::class) +@JsonSerialize(using = Overlay.Serializer::class) +class Overlay +private constructor( + private val text: TextOverlay? = null, + private val image: ImageOverlay? = null, + private val video: VideoOverlay? = null, + private val subtitle: SubtitleOverlay? = null, + private val solidColor: SolidColorOverlay? = null, + private val _json: JsonValue? = null, +) { + + fun text(): Optional = Optional.ofNullable(text) + + fun image(): Optional = Optional.ofNullable(image) + + fun video(): Optional = Optional.ofNullable(video) + + fun subtitle(): Optional = Optional.ofNullable(subtitle) + + fun solidColor(): Optional = Optional.ofNullable(solidColor) + + fun isText(): Boolean = text != null + + fun isImage(): Boolean = image != null + + fun isVideo(): Boolean = video != null + + fun isSubtitle(): Boolean = subtitle != null + + fun isSolidColor(): Boolean = solidColor != null + + fun asText(): TextOverlay = text.getOrThrow("text") + + fun asImage(): ImageOverlay = image.getOrThrow("image") + + fun asVideo(): VideoOverlay = video.getOrThrow("video") + + fun asSubtitle(): SubtitleOverlay = subtitle.getOrThrow("subtitle") + + fun asSolidColor(): SolidColorOverlay = solidColor.getOrThrow("solidColor") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + text != null -> visitor.visitText(text) + image != null -> visitor.visitImage(image) + video != null -> visitor.visitVideo(video) + subtitle != null -> visitor.visitSubtitle(subtitle) + solidColor != null -> visitor.visitSolidColor(solidColor) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): Overlay = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitText(text: TextOverlay) { + text.validate() + } + + override fun visitImage(image: ImageOverlay) { + image.validate() + } + + override fun visitVideo(video: VideoOverlay) { + video.validate() + } + + override fun visitSubtitle(subtitle: SubtitleOverlay) { + subtitle.validate() + } + + override fun visitSolidColor(solidColor: SolidColorOverlay) { + solidColor.validate() + } + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitText(text: TextOverlay) = text.validity() + + override fun visitImage(image: ImageOverlay) = image.validity() + + override fun visitVideo(video: VideoOverlay) = video.validity() + + override fun visitSubtitle(subtitle: SubtitleOverlay) = subtitle.validity() + + override fun visitSolidColor(solidColor: SolidColorOverlay) = solidColor.validity() + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Overlay && + text == other.text && + image == other.image && + video == other.video && + subtitle == other.subtitle && + solidColor == other.solidColor + } + + override fun hashCode(): Int = Objects.hash(text, image, video, subtitle, solidColor) + + override fun toString(): String = + when { + text != null -> "Overlay{text=$text}" + image != null -> "Overlay{image=$image}" + video != null -> "Overlay{video=$video}" + subtitle != null -> "Overlay{subtitle=$subtitle}" + solidColor != null -> "Overlay{solidColor=$solidColor}" + _json != null -> "Overlay{_unknown=$_json}" + else -> throw IllegalStateException("Invalid Overlay") + } + + companion object { + + @JvmStatic fun ofText(text: TextOverlay) = Overlay(text = text) + + @JvmStatic fun ofImage(image: ImageOverlay) = Overlay(image = image) + + @JvmStatic fun ofVideo(video: VideoOverlay) = Overlay(video = video) + + @JvmStatic fun ofSubtitle(subtitle: SubtitleOverlay) = Overlay(subtitle = subtitle) + + @JvmStatic + fun ofSolidColor(solidColor: SolidColorOverlay) = Overlay(solidColor = solidColor) + } + + /** An interface that defines how to map each variant of [Overlay] to a value of type [T]. */ + interface Visitor { + + fun visitText(text: TextOverlay): T + + fun visitImage(image: ImageOverlay): T + + fun visitVideo(video: VideoOverlay): T + + fun visitSubtitle(subtitle: SubtitleOverlay): T + + fun visitSolidColor(solidColor: SolidColorOverlay): T + + /** + * Maps an unknown variant of [Overlay] to a value of type [T]. + * + * An instance of [Overlay] can contain an unknown variant if it was deserialized from data + * that doesn't match any known variant. For example, if the SDK is on an older version than + * the API, then the API may respond with new variants that the SDK is unaware of. + * + * @throws ImageKitInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw ImageKitInvalidDataException("Unknown Overlay: $json") + } + } + + internal class Deserializer : BaseDeserializer(Overlay::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): Overlay { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + Overlay(text = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + Overlay(image = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + Overlay(video = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + Overlay(subtitle = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + Overlay(solidColor = it, _json = json) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely incompatible with all + // the possible variants (e.g. deserializing from boolean). + 0 -> Overlay(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then use the first + // completely valid match, or simply the first match if none are completely valid. + else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() + } + } + } + + internal class Serializer : BaseSerializer(Overlay::class) { + + override fun serialize( + value: Overlay, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.text != null -> generator.writeObject(value.text) + value.image != null -> generator.writeObject(value.image) + value.video != null -> generator.writeObject(value.video) + value.subtitle != null -> generator.writeObject(value.subtitle) + value.solidColor != null -> generator.writeObject(value.solidColor) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid Overlay") + } + } + } +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/OverlayPosition.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/OverlayPosition.kt new file mode 100644 index 0000000..42f5e18 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/OverlayPosition.kt @@ -0,0 +1,785 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.fasterxml.jackson.core.JsonGenerator +import com.fasterxml.jackson.core.ObjectCodec +import com.fasterxml.jackson.databind.JsonNode +import com.fasterxml.jackson.databind.SerializerProvider +import com.fasterxml.jackson.databind.annotation.JsonDeserialize +import com.fasterxml.jackson.databind.annotation.JsonSerialize +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.imagekit.api.core.BaseDeserializer +import com.imagekit.api.core.BaseSerializer +import com.imagekit.api.core.Enum +import com.imagekit.api.core.ExcludeMissing +import com.imagekit.api.core.JsonField +import com.imagekit.api.core.JsonMissing +import com.imagekit.api.core.JsonValue +import com.imagekit.api.core.allMaxBy +import com.imagekit.api.core.getOrThrow +import com.imagekit.api.errors.ImageKitInvalidDataException +import java.util.Collections +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +class OverlayPosition +private constructor( + private val focus: JsonField, + private val x: JsonField, + private val y: JsonField, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("focus") @ExcludeMissing focus: JsonField = JsonMissing.of(), + @JsonProperty("x") @ExcludeMissing x: JsonField = JsonMissing.of(), + @JsonProperty("y") @ExcludeMissing y: JsonField = JsonMissing.of(), + ) : this(focus, x, y, mutableMapOf()) + + /** + * Specifies the position of the overlay relative to the parent image or video. Maps to `lfo` in + * the URL. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun focus(): Optional = focus.getOptional("focus") + + /** + * Specifies the x-coordinate of the top-left corner of the base asset where the overlay's + * top-left corner will be positioned. It also accepts arithmetic expressions such as + * `bw_mul_0.4` or `bw_sub_cw`. Maps to `lx` in the URL. Learn about + * [Arithmetic expressions](https://imagekit.io/docs/arithmetic-expressions-in-transformations). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun x(): Optional = x.getOptional("x") + + /** + * Specifies the y-coordinate of the top-left corner of the base asset where the overlay's + * top-left corner will be positioned. It also accepts arithmetic expressions such as + * `bh_mul_0.4` or `bh_sub_ch`. Maps to `ly` in the URL. Learn about + * [Arithmetic expressions](https://imagekit.io/docs/arithmetic-expressions-in-transformations). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun y(): Optional = y.getOptional("y") + + /** + * Returns the raw JSON value of [focus]. + * + * Unlike [focus], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("focus") @ExcludeMissing fun _focus(): JsonField = focus + + /** + * Returns the raw JSON value of [x]. + * + * Unlike [x], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("x") @ExcludeMissing fun _x(): JsonField = x + + /** + * Returns the raw JSON value of [y]. + * + * Unlike [y], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("y") @ExcludeMissing fun _y(): JsonField = y + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [OverlayPosition]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [OverlayPosition]. */ + class Builder internal constructor() { + + private var focus: JsonField = JsonMissing.of() + private var x: JsonField = JsonMissing.of() + private var y: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(overlayPosition: OverlayPosition) = apply { + focus = overlayPosition.focus + x = overlayPosition.x + y = overlayPosition.y + additionalProperties = overlayPosition.additionalProperties.toMutableMap() + } + + /** + * Specifies the position of the overlay relative to the parent image or video. Maps to + * `lfo` in the URL. + */ + fun focus(focus: Focus) = focus(JsonField.of(focus)) + + /** + * Sets [Builder.focus] to an arbitrary JSON value. + * + * You should usually call [Builder.focus] with a well-typed [Focus] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun focus(focus: JsonField) = apply { this.focus = focus } + + /** + * Specifies the x-coordinate of the top-left corner of the base asset where the overlay's + * top-left corner will be positioned. It also accepts arithmetic expressions such as + * `bw_mul_0.4` or `bw_sub_cw`. Maps to `lx` in the URL. Learn about + * [Arithmetic expressions](https://imagekit.io/docs/arithmetic-expressions-in-transformations). + */ + fun x(x: X) = x(JsonField.of(x)) + + /** + * Sets [Builder.x] to an arbitrary JSON value. + * + * You should usually call [Builder.x] with a well-typed [X] value instead. This method is + * primarily for setting the field to an undocumented or not yet supported value. + */ + fun x(x: JsonField) = apply { this.x = x } + + /** Alias for calling [x] with `X.ofNumber(number)`. */ + fun x(number: Double) = x(X.ofNumber(number)) + + /** Alias for calling [x] with `X.ofString(string)`. */ + fun x(string: String) = x(X.ofString(string)) + + /** + * Specifies the y-coordinate of the top-left corner of the base asset where the overlay's + * top-left corner will be positioned. It also accepts arithmetic expressions such as + * `bh_mul_0.4` or `bh_sub_ch`. Maps to `ly` in the URL. Learn about + * [Arithmetic expressions](https://imagekit.io/docs/arithmetic-expressions-in-transformations). + */ + fun y(y: Y) = y(JsonField.of(y)) + + /** + * Sets [Builder.y] to an arbitrary JSON value. + * + * You should usually call [Builder.y] with a well-typed [Y] value instead. This method is + * primarily for setting the field to an undocumented or not yet supported value. + */ + fun y(y: JsonField) = apply { this.y = y } + + /** Alias for calling [y] with `Y.ofNumber(number)`. */ + fun y(number: Double) = y(Y.ofNumber(number)) + + /** Alias for calling [y] with `Y.ofString(string)`. */ + fun y(string: String) = y(Y.ofString(string)) + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [OverlayPosition]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): OverlayPosition = + OverlayPosition(focus, x, y, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): OverlayPosition = apply { + if (validated) { + return@apply + } + + focus().ifPresent { it.validate() } + x().ifPresent { it.validate() } + y().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (focus.asKnown().getOrNull()?.validity() ?: 0) + + (x.asKnown().getOrNull()?.validity() ?: 0) + + (y.asKnown().getOrNull()?.validity() ?: 0) + + /** + * Specifies the position of the overlay relative to the parent image or video. Maps to `lfo` in + * the URL. + */ + class Focus @JsonCreator private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is on an + * older version than the API, then the API may respond with new members that the SDK is + * unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val CENTER = of("center") + + @JvmField val TOP = of("top") + + @JvmField val LEFT = of("left") + + @JvmField val BOTTOM = of("bottom") + + @JvmField val RIGHT = of("right") + + @JvmField val TOP_LEFT = of("top_left") + + @JvmField val TOP_RIGHT = of("top_right") + + @JvmField val BOTTOM_LEFT = of("bottom_left") + + @JvmField val BOTTOM_RIGHT = of("bottom_right") + + @JvmStatic fun of(value: String) = Focus(JsonField.of(value)) + } + + /** An enum containing [Focus]'s known values. */ + enum class Known { + CENTER, + TOP, + LEFT, + BOTTOM, + RIGHT, + TOP_LEFT, + TOP_RIGHT, + BOTTOM_LEFT, + BOTTOM_RIGHT, + } + + /** + * An enum containing [Focus]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [Focus] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if the + * SDK is on an older version than the API, then the API may respond with new members that + * the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + CENTER, + TOP, + LEFT, + BOTTOM, + RIGHT, + TOP_LEFT, + TOP_RIGHT, + BOTTOM_LEFT, + BOTTOM_RIGHT, + /** An enum member indicating that [Focus] was instantiated with an unknown value. */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] + * if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you want + * to throw for the unknown case. + */ + fun value(): Value = + when (this) { + CENTER -> Value.CENTER + TOP -> Value.TOP + LEFT -> Value.LEFT + BOTTOM -> Value.BOTTOM + RIGHT -> Value.RIGHT + TOP_LEFT -> Value.TOP_LEFT + TOP_RIGHT -> Value.TOP_RIGHT + BOTTOM_LEFT -> Value.BOTTOM_LEFT + BOTTOM_RIGHT -> Value.BOTTOM_RIGHT + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and don't + * want to throw for the unknown case. + * + * @throws ImageKitInvalidDataException if this class instance's value is a not a known + * member. + */ + fun known(): Known = + when (this) { + CENTER -> Known.CENTER + TOP -> Known.TOP + LEFT -> Known.LEFT + BOTTOM -> Known.BOTTOM + RIGHT -> Known.RIGHT + TOP_LEFT -> Known.TOP_LEFT + TOP_RIGHT -> Known.TOP_RIGHT + BOTTOM_LEFT -> Known.BOTTOM_LEFT + BOTTOM_RIGHT -> Known.BOTTOM_RIGHT + else -> throw ImageKitInvalidDataException("Unknown Focus: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for debugging + * and generally doesn't throw. + * + * @throws ImageKitInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + ImageKitInvalidDataException("Value is not a String") + } + + private var validated: Boolean = false + + fun validate(): Focus = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Focus && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + /** + * Specifies the x-coordinate of the top-left corner of the base asset where the overlay's + * top-left corner will be positioned. It also accepts arithmetic expressions such as + * `bw_mul_0.4` or `bw_sub_cw`. Maps to `lx` in the URL. Learn about + * [Arithmetic expressions](https://imagekit.io/docs/arithmetic-expressions-in-transformations). + */ + @JsonDeserialize(using = X.Deserializer::class) + @JsonSerialize(using = X.Serializer::class) + class X + private constructor( + private val number: Double? = null, + private val string: String? = null, + private val _json: JsonValue? = null, + ) { + + fun number(): Optional = Optional.ofNullable(number) + + fun string(): Optional = Optional.ofNullable(string) + + fun isNumber(): Boolean = number != null + + fun isString(): Boolean = string != null + + fun asNumber(): Double = number.getOrThrow("number") + + fun asString(): String = string.getOrThrow("string") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + number != null -> visitor.visitNumber(number) + string != null -> visitor.visitString(string) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): X = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitNumber(number: Double) {} + + override fun visitString(string: String) {} + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitNumber(number: Double) = 1 + + override fun visitString(string: String) = 1 + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is X && number == other.number && string == other.string + } + + override fun hashCode(): Int = Objects.hash(number, string) + + override fun toString(): String = + when { + number != null -> "X{number=$number}" + string != null -> "X{string=$string}" + _json != null -> "X{_unknown=$_json}" + else -> throw IllegalStateException("Invalid X") + } + + companion object { + + @JvmStatic fun ofNumber(number: Double) = X(number = number) + + @JvmStatic fun ofString(string: String) = X(string = string) + } + + /** An interface that defines how to map each variant of [X] to a value of type [T]. */ + interface Visitor { + + fun visitNumber(number: Double): T + + fun visitString(string: String): T + + /** + * Maps an unknown variant of [X] to a value of type [T]. + * + * An instance of [X] can contain an unknown variant if it was deserialized from data + * that doesn't match any known variant. For example, if the SDK is on an older version + * than the API, then the API may respond with new variants that the SDK is unaware of. + * + * @throws ImageKitInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw ImageKitInvalidDataException("Unknown X: $json") + } + } + + internal class Deserializer : BaseDeserializer(X::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): X { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + X(number = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + X(string = it, _json = json) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely incompatible with + // all the possible variants (e.g. deserializing from object). + 0 -> X(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then use the first + // completely valid match, or simply the first match if none are completely + // valid. + else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() + } + } + } + + internal class Serializer : BaseSerializer(X::class) { + + override fun serialize( + value: X, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.number != null -> generator.writeObject(value.number) + value.string != null -> generator.writeObject(value.string) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid X") + } + } + } + } + + /** + * Specifies the y-coordinate of the top-left corner of the base asset where the overlay's + * top-left corner will be positioned. It also accepts arithmetic expressions such as + * `bh_mul_0.4` or `bh_sub_ch`. Maps to `ly` in the URL. Learn about + * [Arithmetic expressions](https://imagekit.io/docs/arithmetic-expressions-in-transformations). + */ + @JsonDeserialize(using = Y.Deserializer::class) + @JsonSerialize(using = Y.Serializer::class) + class Y + private constructor( + private val number: Double? = null, + private val string: String? = null, + private val _json: JsonValue? = null, + ) { + + fun number(): Optional = Optional.ofNullable(number) + + fun string(): Optional = Optional.ofNullable(string) + + fun isNumber(): Boolean = number != null + + fun isString(): Boolean = string != null + + fun asNumber(): Double = number.getOrThrow("number") + + fun asString(): String = string.getOrThrow("string") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + number != null -> visitor.visitNumber(number) + string != null -> visitor.visitString(string) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): Y = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitNumber(number: Double) {} + + override fun visitString(string: String) {} + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitNumber(number: Double) = 1 + + override fun visitString(string: String) = 1 + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Y && number == other.number && string == other.string + } + + override fun hashCode(): Int = Objects.hash(number, string) + + override fun toString(): String = + when { + number != null -> "Y{number=$number}" + string != null -> "Y{string=$string}" + _json != null -> "Y{_unknown=$_json}" + else -> throw IllegalStateException("Invalid Y") + } + + companion object { + + @JvmStatic fun ofNumber(number: Double) = Y(number = number) + + @JvmStatic fun ofString(string: String) = Y(string = string) + } + + /** An interface that defines how to map each variant of [Y] to a value of type [T]. */ + interface Visitor { + + fun visitNumber(number: Double): T + + fun visitString(string: String): T + + /** + * Maps an unknown variant of [Y] to a value of type [T]. + * + * An instance of [Y] can contain an unknown variant if it was deserialized from data + * that doesn't match any known variant. For example, if the SDK is on an older version + * than the API, then the API may respond with new variants that the SDK is unaware of. + * + * @throws ImageKitInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw ImageKitInvalidDataException("Unknown Y: $json") + } + } + + internal class Deserializer : BaseDeserializer(Y::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): Y { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + Y(number = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + Y(string = it, _json = json) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely incompatible with + // all the possible variants (e.g. deserializing from object). + 0 -> Y(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then use the first + // completely valid match, or simply the first match if none are completely + // valid. + else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() + } + } + } + + internal class Serializer : BaseSerializer(Y::class) { + + override fun serialize( + value: Y, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.number != null -> generator.writeObject(value.number) + value.string != null -> generator.writeObject(value.string) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid Y") + } + } + } + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is OverlayPosition && + focus == other.focus && + x == other.x && + y == other.y && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(focus, x, y, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "OverlayPosition{focus=$focus, x=$x, y=$y, additionalProperties=$additionalProperties}" +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/OverlayTiming.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/OverlayTiming.kt new file mode 100644 index 0000000..4d94f49 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/OverlayTiming.kt @@ -0,0 +1,801 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.fasterxml.jackson.core.JsonGenerator +import com.fasterxml.jackson.core.ObjectCodec +import com.fasterxml.jackson.databind.JsonNode +import com.fasterxml.jackson.databind.SerializerProvider +import com.fasterxml.jackson.databind.annotation.JsonDeserialize +import com.fasterxml.jackson.databind.annotation.JsonSerialize +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.imagekit.api.core.BaseDeserializer +import com.imagekit.api.core.BaseSerializer +import com.imagekit.api.core.ExcludeMissing +import com.imagekit.api.core.JsonField +import com.imagekit.api.core.JsonMissing +import com.imagekit.api.core.JsonValue +import com.imagekit.api.core.allMaxBy +import com.imagekit.api.core.getOrThrow +import com.imagekit.api.errors.ImageKitInvalidDataException +import java.util.Collections +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +class OverlayTiming +private constructor( + private val duration: JsonField, + private val end: JsonField, + private val start: JsonField, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("duration") @ExcludeMissing duration: JsonField = JsonMissing.of(), + @JsonProperty("end") @ExcludeMissing end: JsonField = JsonMissing.of(), + @JsonProperty("start") @ExcludeMissing start: JsonField = JsonMissing.of(), + ) : this(duration, end, start, mutableMapOf()) + + /** + * Specifies the duration (in seconds) during which the overlay should appear on the base video. + * Accepts a positive number up to two decimal places (e.g., `20` or `20.50`) and arithmetic + * expressions such as `bdu_mul_0.4` or `bdu_sub_idu`. Applies only if the base asset is a + * video. Maps to `ldu` in the URL. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun duration(): Optional = duration.getOptional("duration") + + /** + * Specifies the end time (in seconds) for when the overlay should disappear from the base + * video. If both end and duration are provided, duration is ignored. Accepts a positive number + * up to two decimal places (e.g., `20` or `20.50`) and arithmetic expressions such as + * `bdu_mul_0.4` or `bdu_sub_idu`. Applies only if the base asset is a video. Maps to `leo` in + * the URL. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun end(): Optional = end.getOptional("end") + + /** + * Specifies the start time (in seconds) for when the overlay should appear on the base video. + * Accepts a positive number up to two decimal places (e.g., `20` or `20.50`) and arithmetic + * expressions such as `bdu_mul_0.4` or `bdu_sub_idu`. Applies only if the base asset is a + * video. Maps to `lso` in the URL. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun start(): Optional = start.getOptional("start") + + /** + * Returns the raw JSON value of [duration]. + * + * Unlike [duration], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("duration") @ExcludeMissing fun _duration(): JsonField = duration + + /** + * Returns the raw JSON value of [end]. + * + * Unlike [end], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("end") @ExcludeMissing fun _end(): JsonField = end + + /** + * Returns the raw JSON value of [start]. + * + * Unlike [start], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("start") @ExcludeMissing fun _start(): JsonField = start + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [OverlayTiming]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [OverlayTiming]. */ + class Builder internal constructor() { + + private var duration: JsonField = JsonMissing.of() + private var end: JsonField = JsonMissing.of() + private var start: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(overlayTiming: OverlayTiming) = apply { + duration = overlayTiming.duration + end = overlayTiming.end + start = overlayTiming.start + additionalProperties = overlayTiming.additionalProperties.toMutableMap() + } + + /** + * Specifies the duration (in seconds) during which the overlay should appear on the base + * video. Accepts a positive number up to two decimal places (e.g., `20` or `20.50`) and + * arithmetic expressions such as `bdu_mul_0.4` or `bdu_sub_idu`. Applies only if the base + * asset is a video. Maps to `ldu` in the URL. + */ + fun duration(duration: Duration) = duration(JsonField.of(duration)) + + /** + * Sets [Builder.duration] to an arbitrary JSON value. + * + * You should usually call [Builder.duration] with a well-typed [Duration] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun duration(duration: JsonField) = apply { this.duration = duration } + + /** Alias for calling [duration] with `Duration.ofNumber(number)`. */ + fun duration(number: Double) = duration(Duration.ofNumber(number)) + + /** Alias for calling [duration] with `Duration.ofString(string)`. */ + fun duration(string: String) = duration(Duration.ofString(string)) + + /** + * Specifies the end time (in seconds) for when the overlay should disappear from the base + * video. If both end and duration are provided, duration is ignored. Accepts a positive + * number up to two decimal places (e.g., `20` or `20.50`) and arithmetic expressions such + * as `bdu_mul_0.4` or `bdu_sub_idu`. Applies only if the base asset is a video. Maps to + * `leo` in the URL. + */ + fun end(end: End) = end(JsonField.of(end)) + + /** + * Sets [Builder.end] to an arbitrary JSON value. + * + * You should usually call [Builder.end] with a well-typed [End] value instead. This method + * is primarily for setting the field to an undocumented or not yet supported value. + */ + fun end(end: JsonField) = apply { this.end = end } + + /** Alias for calling [end] with `End.ofNumber(number)`. */ + fun end(number: Double) = end(End.ofNumber(number)) + + /** Alias for calling [end] with `End.ofString(string)`. */ + fun end(string: String) = end(End.ofString(string)) + + /** + * Specifies the start time (in seconds) for when the overlay should appear on the base + * video. Accepts a positive number up to two decimal places (e.g., `20` or `20.50`) and + * arithmetic expressions such as `bdu_mul_0.4` or `bdu_sub_idu`. Applies only if the base + * asset is a video. Maps to `lso` in the URL. + */ + fun start(start: Start) = start(JsonField.of(start)) + + /** + * Sets [Builder.start] to an arbitrary JSON value. + * + * You should usually call [Builder.start] with a well-typed [Start] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun start(start: JsonField) = apply { this.start = start } + + /** Alias for calling [start] with `Start.ofNumber(number)`. */ + fun start(number: Double) = start(Start.ofNumber(number)) + + /** Alias for calling [start] with `Start.ofString(string)`. */ + fun start(string: String) = start(Start.ofString(string)) + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [OverlayTiming]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): OverlayTiming = + OverlayTiming(duration, end, start, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): OverlayTiming = apply { + if (validated) { + return@apply + } + + duration().ifPresent { it.validate() } + end().ifPresent { it.validate() } + start().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (duration.asKnown().getOrNull()?.validity() ?: 0) + + (end.asKnown().getOrNull()?.validity() ?: 0) + + (start.asKnown().getOrNull()?.validity() ?: 0) + + /** + * Specifies the duration (in seconds) during which the overlay should appear on the base video. + * Accepts a positive number up to two decimal places (e.g., `20` or `20.50`) and arithmetic + * expressions such as `bdu_mul_0.4` or `bdu_sub_idu`. Applies only if the base asset is a + * video. Maps to `ldu` in the URL. + */ + @JsonDeserialize(using = Duration.Deserializer::class) + @JsonSerialize(using = Duration.Serializer::class) + class Duration + private constructor( + private val number: Double? = null, + private val string: String? = null, + private val _json: JsonValue? = null, + ) { + + fun number(): Optional = Optional.ofNullable(number) + + fun string(): Optional = Optional.ofNullable(string) + + fun isNumber(): Boolean = number != null + + fun isString(): Boolean = string != null + + fun asNumber(): Double = number.getOrThrow("number") + + fun asString(): String = string.getOrThrow("string") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + number != null -> visitor.visitNumber(number) + string != null -> visitor.visitString(string) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): Duration = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitNumber(number: Double) {} + + override fun visitString(string: String) {} + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitNumber(number: Double) = 1 + + override fun visitString(string: String) = 1 + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Duration && number == other.number && string == other.string + } + + override fun hashCode(): Int = Objects.hash(number, string) + + override fun toString(): String = + when { + number != null -> "Duration{number=$number}" + string != null -> "Duration{string=$string}" + _json != null -> "Duration{_unknown=$_json}" + else -> throw IllegalStateException("Invalid Duration") + } + + companion object { + + @JvmStatic fun ofNumber(number: Double) = Duration(number = number) + + @JvmStatic fun ofString(string: String) = Duration(string = string) + } + + /** + * An interface that defines how to map each variant of [Duration] to a value of type [T]. + */ + interface Visitor { + + fun visitNumber(number: Double): T + + fun visitString(string: String): T + + /** + * Maps an unknown variant of [Duration] to a value of type [T]. + * + * An instance of [Duration] can contain an unknown variant if it was deserialized from + * data that doesn't match any known variant. For example, if the SDK is on an older + * version than the API, then the API may respond with new variants that the SDK is + * unaware of. + * + * @throws ImageKitInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw ImageKitInvalidDataException("Unknown Duration: $json") + } + } + + internal class Deserializer : BaseDeserializer(Duration::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): Duration { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + Duration(number = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + Duration(string = it, _json = json) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely incompatible with + // all the possible variants (e.g. deserializing from object). + 0 -> Duration(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then use the first + // completely valid match, or simply the first match if none are completely + // valid. + else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() + } + } + } + + internal class Serializer : BaseSerializer(Duration::class) { + + override fun serialize( + value: Duration, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.number != null -> generator.writeObject(value.number) + value.string != null -> generator.writeObject(value.string) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid Duration") + } + } + } + } + + /** + * Specifies the end time (in seconds) for when the overlay should disappear from the base + * video. If both end and duration are provided, duration is ignored. Accepts a positive number + * up to two decimal places (e.g., `20` or `20.50`) and arithmetic expressions such as + * `bdu_mul_0.4` or `bdu_sub_idu`. Applies only if the base asset is a video. Maps to `leo` in + * the URL. + */ + @JsonDeserialize(using = End.Deserializer::class) + @JsonSerialize(using = End.Serializer::class) + class End + private constructor( + private val number: Double? = null, + private val string: String? = null, + private val _json: JsonValue? = null, + ) { + + fun number(): Optional = Optional.ofNullable(number) + + fun string(): Optional = Optional.ofNullable(string) + + fun isNumber(): Boolean = number != null + + fun isString(): Boolean = string != null + + fun asNumber(): Double = number.getOrThrow("number") + + fun asString(): String = string.getOrThrow("string") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + number != null -> visitor.visitNumber(number) + string != null -> visitor.visitString(string) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): End = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitNumber(number: Double) {} + + override fun visitString(string: String) {} + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitNumber(number: Double) = 1 + + override fun visitString(string: String) = 1 + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is End && number == other.number && string == other.string + } + + override fun hashCode(): Int = Objects.hash(number, string) + + override fun toString(): String = + when { + number != null -> "End{number=$number}" + string != null -> "End{string=$string}" + _json != null -> "End{_unknown=$_json}" + else -> throw IllegalStateException("Invalid End") + } + + companion object { + + @JvmStatic fun ofNumber(number: Double) = End(number = number) + + @JvmStatic fun ofString(string: String) = End(string = string) + } + + /** An interface that defines how to map each variant of [End] to a value of type [T]. */ + interface Visitor { + + fun visitNumber(number: Double): T + + fun visitString(string: String): T + + /** + * Maps an unknown variant of [End] to a value of type [T]. + * + * An instance of [End] can contain an unknown variant if it was deserialized from data + * that doesn't match any known variant. For example, if the SDK is on an older version + * than the API, then the API may respond with new variants that the SDK is unaware of. + * + * @throws ImageKitInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw ImageKitInvalidDataException("Unknown End: $json") + } + } + + internal class Deserializer : BaseDeserializer(End::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): End { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + End(number = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + End(string = it, _json = json) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely incompatible with + // all the possible variants (e.g. deserializing from object). + 0 -> End(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then use the first + // completely valid match, or simply the first match if none are completely + // valid. + else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() + } + } + } + + internal class Serializer : BaseSerializer(End::class) { + + override fun serialize( + value: End, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.number != null -> generator.writeObject(value.number) + value.string != null -> generator.writeObject(value.string) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid End") + } + } + } + } + + /** + * Specifies the start time (in seconds) for when the overlay should appear on the base video. + * Accepts a positive number up to two decimal places (e.g., `20` or `20.50`) and arithmetic + * expressions such as `bdu_mul_0.4` or `bdu_sub_idu`. Applies only if the base asset is a + * video. Maps to `lso` in the URL. + */ + @JsonDeserialize(using = Start.Deserializer::class) + @JsonSerialize(using = Start.Serializer::class) + class Start + private constructor( + private val number: Double? = null, + private val string: String? = null, + private val _json: JsonValue? = null, + ) { + + fun number(): Optional = Optional.ofNullable(number) + + fun string(): Optional = Optional.ofNullable(string) + + fun isNumber(): Boolean = number != null + + fun isString(): Boolean = string != null + + fun asNumber(): Double = number.getOrThrow("number") + + fun asString(): String = string.getOrThrow("string") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + number != null -> visitor.visitNumber(number) + string != null -> visitor.visitString(string) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): Start = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitNumber(number: Double) {} + + override fun visitString(string: String) {} + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitNumber(number: Double) = 1 + + override fun visitString(string: String) = 1 + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Start && number == other.number && string == other.string + } + + override fun hashCode(): Int = Objects.hash(number, string) + + override fun toString(): String = + when { + number != null -> "Start{number=$number}" + string != null -> "Start{string=$string}" + _json != null -> "Start{_unknown=$_json}" + else -> throw IllegalStateException("Invalid Start") + } + + companion object { + + @JvmStatic fun ofNumber(number: Double) = Start(number = number) + + @JvmStatic fun ofString(string: String) = Start(string = string) + } + + /** An interface that defines how to map each variant of [Start] to a value of type [T]. */ + interface Visitor { + + fun visitNumber(number: Double): T + + fun visitString(string: String): T + + /** + * Maps an unknown variant of [Start] to a value of type [T]. + * + * An instance of [Start] can contain an unknown variant if it was deserialized from + * data that doesn't match any known variant. For example, if the SDK is on an older + * version than the API, then the API may respond with new variants that the SDK is + * unaware of. + * + * @throws ImageKitInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw ImageKitInvalidDataException("Unknown Start: $json") + } + } + + internal class Deserializer : BaseDeserializer(Start::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): Start { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + Start(number = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + Start(string = it, _json = json) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely incompatible with + // all the possible variants (e.g. deserializing from object). + 0 -> Start(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then use the first + // completely valid match, or simply the first match if none are completely + // valid. + else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() + } + } + } + + internal class Serializer : BaseSerializer(Start::class) { + + override fun serialize( + value: Start, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.number != null -> generator.writeObject(value.number) + value.string != null -> generator.writeObject(value.string) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid Start") + } + } + } + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is OverlayTiming && + duration == other.duration && + end == other.end && + start == other.start && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(duration, end, start, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "OverlayTiming{duration=$duration, end=$end, start=$start, additionalProperties=$additionalProperties}" +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/SolidColorOverlay.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/SolidColorOverlay.kt new file mode 100644 index 0000000..882fbd6 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/SolidColorOverlay.kt @@ -0,0 +1,359 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.imagekit.api.core.ExcludeMissing +import com.imagekit.api.core.JsonField +import com.imagekit.api.core.JsonMissing +import com.imagekit.api.core.JsonValue +import com.imagekit.api.core.checkKnown +import com.imagekit.api.core.checkRequired +import com.imagekit.api.core.toImmutable +import com.imagekit.api.errors.ImageKitInvalidDataException +import java.util.Collections +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +class SolidColorOverlay +private constructor( + private val position: JsonField, + private val timing: JsonField, + private val color: JsonField, + private val type: JsonValue, + private val transformation: JsonField>, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("position") + @ExcludeMissing + position: JsonField = JsonMissing.of(), + @JsonProperty("timing") @ExcludeMissing timing: JsonField = JsonMissing.of(), + @JsonProperty("color") @ExcludeMissing color: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(), + @JsonProperty("transformation") + @ExcludeMissing + transformation: JsonField> = JsonMissing.of(), + ) : this(position, timing, color, type, transformation, mutableMapOf()) + + fun toBaseOverlay(): BaseOverlay = + BaseOverlay.builder().position(position).timing(timing).build() + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun position(): Optional = position.getOptional("position") + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun timing(): Optional = timing.getOptional("timing") + + /** + * Specifies the color of the block using an RGB hex code (e.g., `FF0000`), an RGBA code (e.g., + * `FFAABB50`), or a color name (e.g., `red`). If an 8-character value is provided, the last two + * characters represent the opacity level (from `00` for 0.00 to `99` for 0.99). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun color(): String = color.getRequired("color") + + /** + * Expected to always return the following: + * ```java + * JsonValue.from("solidColor") + * ``` + * + * However, this method can be useful for debugging and logging (e.g. if the server responded + * with an unexpected value). + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type + + /** + * Control width and height of the solid color overlay. Supported transformations depend on the + * base/parent asset. See overlays on + * [Images](https://imagekit.io/docs/add-overlays-on-images#apply-transformation-on-solid-color-overlay) + * and + * [Videos](https://imagekit.io/docs/add-overlays-on-videos#apply-transformations-on-solid-color-block-overlay). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun transformation(): Optional> = + transformation.getOptional("transformation") + + /** + * Returns the raw JSON value of [position]. + * + * Unlike [position], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("position") @ExcludeMissing fun _position(): JsonField = position + + /** + * Returns the raw JSON value of [timing]. + * + * Unlike [timing], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("timing") @ExcludeMissing fun _timing(): JsonField = timing + + /** + * Returns the raw JSON value of [color]. + * + * Unlike [color], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("color") @ExcludeMissing fun _color(): JsonField = color + + /** + * Returns the raw JSON value of [transformation]. + * + * Unlike [transformation], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("transformation") + @ExcludeMissing + fun _transformation(): JsonField> = transformation + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [SolidColorOverlay]. + * + * The following fields are required: + * ```java + * .color() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [SolidColorOverlay]. */ + class Builder internal constructor() { + + private var position: JsonField = JsonMissing.of() + private var timing: JsonField = JsonMissing.of() + private var color: JsonField? = null + private var type: JsonValue = JsonValue.from("solidColor") + private var transformation: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(solidColorOverlay: SolidColorOverlay) = apply { + position = solidColorOverlay.position + timing = solidColorOverlay.timing + color = solidColorOverlay.color + type = solidColorOverlay.type + transformation = solidColorOverlay.transformation.map { it.toMutableList() } + additionalProperties = solidColorOverlay.additionalProperties.toMutableMap() + } + + fun position(position: OverlayPosition) = position(JsonField.of(position)) + + /** + * Sets [Builder.position] to an arbitrary JSON value. + * + * You should usually call [Builder.position] with a well-typed [OverlayPosition] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun position(position: JsonField) = apply { this.position = position } + + fun timing(timing: OverlayTiming) = timing(JsonField.of(timing)) + + /** + * Sets [Builder.timing] to an arbitrary JSON value. + * + * You should usually call [Builder.timing] with a well-typed [OverlayTiming] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun timing(timing: JsonField) = apply { this.timing = timing } + + /** + * Specifies the color of the block using an RGB hex code (e.g., `FF0000`), an RGBA code + * (e.g., `FFAABB50`), or a color name (e.g., `red`). If an 8-character value is provided, + * the last two characters represent the opacity level (from `00` for 0.00 to `99` for + * 0.99). + */ + fun color(color: String) = color(JsonField.of(color)) + + /** + * Sets [Builder.color] to an arbitrary JSON value. + * + * You should usually call [Builder.color] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun color(color: JsonField) = apply { this.color = color } + + /** + * Sets the field to an arbitrary JSON value. + * + * It is usually unnecessary to call this method because the field defaults to the + * following: + * ```java + * JsonValue.from("solidColor") + * ``` + * + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun type(type: JsonValue) = apply { this.type = type } + + /** + * Control width and height of the solid color overlay. Supported transformations depend on + * the base/parent asset. See overlays on + * [Images](https://imagekit.io/docs/add-overlays-on-images#apply-transformation-on-solid-color-overlay) + * and + * [Videos](https://imagekit.io/docs/add-overlays-on-videos#apply-transformations-on-solid-color-block-overlay). + */ + fun transformation(transformation: List) = + transformation(JsonField.of(transformation)) + + /** + * Sets [Builder.transformation] to an arbitrary JSON value. + * + * You should usually call [Builder.transformation] with a well-typed + * `List` value instead. This method is primarily for + * setting the field to an undocumented or not yet supported value. + */ + fun transformation(transformation: JsonField>) = + apply { + this.transformation = transformation.map { it.toMutableList() } + } + + /** + * Adds a single [SolidColorOverlayTransformation] to [Builder.transformation]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addTransformation(transformation: SolidColorOverlayTransformation) = apply { + this.transformation = + (this.transformation ?: JsonField.of(mutableListOf())).also { + checkKnown("transformation", it).add(transformation) + } + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [SolidColorOverlay]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .color() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): SolidColorOverlay = + SolidColorOverlay( + position, + timing, + checkRequired("color", color), + type, + (transformation ?: JsonMissing.of()).map { it.toImmutable() }, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): SolidColorOverlay = apply { + if (validated) { + return@apply + } + + position().ifPresent { it.validate() } + timing().ifPresent { it.validate() } + color() + _type().let { + if (it != JsonValue.from("solidColor")) { + throw ImageKitInvalidDataException("'type' is invalid, received $it") + } + } + transformation().ifPresent { it.forEach { it.validate() } } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (position.asKnown().getOrNull()?.validity() ?: 0) + + (timing.asKnown().getOrNull()?.validity() ?: 0) + + (if (color.asKnown().isPresent) 1 else 0) + + type.let { if (it == JsonValue.from("solidColor")) 1 else 0 } + + (transformation.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is SolidColorOverlay && + position == other.position && + timing == other.timing && + color == other.color && + type == other.type && + transformation == other.transformation && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(position, timing, color, type, transformation, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "SolidColorOverlay{position=$position, timing=$timing, color=$color, type=$type, transformation=$transformation, additionalProperties=$additionalProperties}" +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/SolidColorOverlayTransformation.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/SolidColorOverlayTransformation.kt new file mode 100644 index 0000000..8d69770 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/SolidColorOverlayTransformation.kt @@ -0,0 +1,1112 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.fasterxml.jackson.core.JsonGenerator +import com.fasterxml.jackson.core.ObjectCodec +import com.fasterxml.jackson.databind.JsonNode +import com.fasterxml.jackson.databind.SerializerProvider +import com.fasterxml.jackson.databind.annotation.JsonDeserialize +import com.fasterxml.jackson.databind.annotation.JsonSerialize +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.imagekit.api.core.BaseDeserializer +import com.imagekit.api.core.BaseSerializer +import com.imagekit.api.core.ExcludeMissing +import com.imagekit.api.core.JsonField +import com.imagekit.api.core.JsonMissing +import com.imagekit.api.core.JsonValue +import com.imagekit.api.core.allMaxBy +import com.imagekit.api.core.getOrThrow +import com.imagekit.api.errors.ImageKitInvalidDataException +import java.util.Collections +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +class SolidColorOverlayTransformation +private constructor( + private val alpha: JsonField, + private val background: JsonField, + private val gradient: JsonField, + private val height: JsonField, + private val radius: JsonField, + private val width: JsonField, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("alpha") @ExcludeMissing alpha: JsonField = JsonMissing.of(), + @JsonProperty("background") + @ExcludeMissing + background: JsonField = JsonMissing.of(), + @JsonProperty("gradient") @ExcludeMissing gradient: JsonField = JsonMissing.of(), + @JsonProperty("height") @ExcludeMissing height: JsonField = JsonMissing.of(), + @JsonProperty("radius") @ExcludeMissing radius: JsonField = JsonMissing.of(), + @JsonProperty("width") @ExcludeMissing width: JsonField = JsonMissing.of(), + ) : this(alpha, background, gradient, height, radius, width, mutableMapOf()) + + /** + * Specifies the transparency level of the solid color overlay. Accepts integers from `1` to + * `9`. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun alpha(): Optional = alpha.getOptional("alpha") + + /** + * Specifies the background color of the solid color overlay. Accepts an RGB hex code (e.g., + * `FF0000`), an RGBA code (e.g., `FFAABB50`), or a color name. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun background(): Optional = background.getOptional("background") + + /** + * Creates a linear gradient with two colors. Pass `true` for a default gradient, or provide a + * string for a custom gradient. Only works if the base asset is an image. See + * [gradient](https://imagekit.io/docs/effects-and-enhancements#gradient---e-gradient). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun gradient(): Optional = gradient.getOptional("gradient") + + /** + * Controls the height of the solid color overlay. Accepts a numeric value or an arithmetic + * expression. Learn about + * [arithmetic expressions](https://imagekit.io/docs/arithmetic-expressions-in-transformations). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun height(): Optional = height.getOptional("height") + + /** + * Specifies the corner radius of the solid color overlay. Set to `max` for circular or oval + * shape. See [radius](https://imagekit.io/docs/effects-and-enhancements#radius---r). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun radius(): Optional = radius.getOptional("radius") + + /** + * Controls the width of the solid color overlay. Accepts a numeric value or an arithmetic + * expression (e.g., `bw_mul_0.2` or `bh_div_2`). Learn about + * [arithmetic expressions](https://imagekit.io/docs/arithmetic-expressions-in-transformations). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun width(): Optional = width.getOptional("width") + + /** + * Returns the raw JSON value of [alpha]. + * + * Unlike [alpha], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("alpha") @ExcludeMissing fun _alpha(): JsonField = alpha + + /** + * Returns the raw JSON value of [background]. + * + * Unlike [background], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("background") @ExcludeMissing fun _background(): JsonField = background + + /** + * Returns the raw JSON value of [gradient]. + * + * Unlike [gradient], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("gradient") @ExcludeMissing fun _gradient(): JsonField = gradient + + /** + * Returns the raw JSON value of [height]. + * + * Unlike [height], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("height") @ExcludeMissing fun _height(): JsonField = height + + /** + * Returns the raw JSON value of [radius]. + * + * Unlike [radius], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("radius") @ExcludeMissing fun _radius(): JsonField = radius + + /** + * Returns the raw JSON value of [width]. + * + * Unlike [width], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("width") @ExcludeMissing fun _width(): JsonField = width + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [SolidColorOverlayTransformation]. + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [SolidColorOverlayTransformation]. */ + class Builder internal constructor() { + + private var alpha: JsonField = JsonMissing.of() + private var background: JsonField = JsonMissing.of() + private var gradient: JsonField = JsonMissing.of() + private var height: JsonField = JsonMissing.of() + private var radius: JsonField = JsonMissing.of() + private var width: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(solidColorOverlayTransformation: SolidColorOverlayTransformation) = + apply { + alpha = solidColorOverlayTransformation.alpha + background = solidColorOverlayTransformation.background + gradient = solidColorOverlayTransformation.gradient + height = solidColorOverlayTransformation.height + radius = solidColorOverlayTransformation.radius + width = solidColorOverlayTransformation.width + additionalProperties = + solidColorOverlayTransformation.additionalProperties.toMutableMap() + } + + /** + * Specifies the transparency level of the solid color overlay. Accepts integers from `1` to + * `9`. + */ + fun alpha(alpha: Double) = alpha(JsonField.of(alpha)) + + /** + * Sets [Builder.alpha] to an arbitrary JSON value. + * + * You should usually call [Builder.alpha] with a well-typed [Double] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun alpha(alpha: JsonField) = apply { this.alpha = alpha } + + /** + * Specifies the background color of the solid color overlay. Accepts an RGB hex code (e.g., + * `FF0000`), an RGBA code (e.g., `FFAABB50`), or a color name. + */ + fun background(background: String) = background(JsonField.of(background)) + + /** + * Sets [Builder.background] to an arbitrary JSON value. + * + * You should usually call [Builder.background] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun background(background: JsonField) = apply { this.background = background } + + /** + * Creates a linear gradient with two colors. Pass `true` for a default gradient, or provide + * a string for a custom gradient. Only works if the base asset is an image. See + * [gradient](https://imagekit.io/docs/effects-and-enhancements#gradient---e-gradient). + */ + fun gradient(gradient: Gradient) = gradient(JsonField.of(gradient)) + + /** + * Sets [Builder.gradient] to an arbitrary JSON value. + * + * You should usually call [Builder.gradient] with a well-typed [Gradient] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun gradient(gradient: JsonField) = apply { this.gradient = gradient } + + /** Alias for calling [gradient] with `Gradient.ofTrue()`. */ + fun gradientTrue() = gradient(Gradient.ofTrue()) + + /** Alias for calling [gradient] with `Gradient.ofString(string)`. */ + fun gradient(string: String) = gradient(Gradient.ofString(string)) + + /** + * Controls the height of the solid color overlay. Accepts a numeric value or an arithmetic + * expression. Learn about + * [arithmetic expressions](https://imagekit.io/docs/arithmetic-expressions-in-transformations). + */ + fun height(height: Height) = height(JsonField.of(height)) + + /** + * Sets [Builder.height] to an arbitrary JSON value. + * + * You should usually call [Builder.height] with a well-typed [Height] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun height(height: JsonField) = apply { this.height = height } + + /** Alias for calling [height] with `Height.ofNumber(number)`. */ + fun height(number: Double) = height(Height.ofNumber(number)) + + /** Alias for calling [height] with `Height.ofString(string)`. */ + fun height(string: String) = height(Height.ofString(string)) + + /** + * Specifies the corner radius of the solid color overlay. Set to `max` for circular or oval + * shape. See [radius](https://imagekit.io/docs/effects-and-enhancements#radius---r). + */ + fun radius(radius: Radius) = radius(JsonField.of(radius)) + + /** + * Sets [Builder.radius] to an arbitrary JSON value. + * + * You should usually call [Builder.radius] with a well-typed [Radius] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun radius(radius: JsonField) = apply { this.radius = radius } + + /** Alias for calling [radius] with `Radius.ofNumber(number)`. */ + fun radius(number: Double) = radius(Radius.ofNumber(number)) + + /** Alias for calling [radius] with `Radius.ofMax()`. */ + fun radiusMax() = radius(Radius.ofMax()) + + /** + * Controls the width of the solid color overlay. Accepts a numeric value or an arithmetic + * expression (e.g., `bw_mul_0.2` or `bh_div_2`). Learn about + * [arithmetic expressions](https://imagekit.io/docs/arithmetic-expressions-in-transformations). + */ + fun width(width: Width) = width(JsonField.of(width)) + + /** + * Sets [Builder.width] to an arbitrary JSON value. + * + * You should usually call [Builder.width] with a well-typed [Width] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun width(width: JsonField) = apply { this.width = width } + + /** Alias for calling [width] with `Width.ofNumber(number)`. */ + fun width(number: Double) = width(Width.ofNumber(number)) + + /** Alias for calling [width] with `Width.ofString(string)`. */ + fun width(string: String) = width(Width.ofString(string)) + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [SolidColorOverlayTransformation]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): SolidColorOverlayTransformation = + SolidColorOverlayTransformation( + alpha, + background, + gradient, + height, + radius, + width, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): SolidColorOverlayTransformation = apply { + if (validated) { + return@apply + } + + alpha() + background() + gradient().ifPresent { it.validate() } + height().ifPresent { it.validate() } + radius().ifPresent { it.validate() } + width().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (alpha.asKnown().isPresent) 1 else 0) + + (if (background.asKnown().isPresent) 1 else 0) + + (gradient.asKnown().getOrNull()?.validity() ?: 0) + + (height.asKnown().getOrNull()?.validity() ?: 0) + + (radius.asKnown().getOrNull()?.validity() ?: 0) + + (width.asKnown().getOrNull()?.validity() ?: 0) + + /** + * Creates a linear gradient with two colors. Pass `true` for a default gradient, or provide a + * string for a custom gradient. Only works if the base asset is an image. See + * [gradient](https://imagekit.io/docs/effects-and-enhancements#gradient---e-gradient). + */ + @JsonDeserialize(using = Gradient.Deserializer::class) + @JsonSerialize(using = Gradient.Serializer::class) + class Gradient + private constructor( + private val true_: JsonValue? = null, + private val string: String? = null, + private val _json: JsonValue? = null, + ) { + + fun true_(): Optional = Optional.ofNullable(true_) + + fun string(): Optional = Optional.ofNullable(string) + + fun isTrue(): Boolean = true_ != null + + fun isString(): Boolean = string != null + + fun asTrue(): JsonValue = true_.getOrThrow("true_") + + fun asString(): String = string.getOrThrow("string") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + true_ != null -> visitor.visitTrue(true_) + string != null -> visitor.visitString(string) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): Gradient = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitTrue(true_: JsonValue) { + true_.let { + if (it != JsonValue.from(true)) { + throw ImageKitInvalidDataException( + "'true_' is invalid, received $it" + ) + } + } + } + + override fun visitString(string: String) {} + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitTrue(true_: JsonValue) = + true_.let { if (it == JsonValue.from(true)) 1 else 0 } + + override fun visitString(string: String) = 1 + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Gradient && true_ == other.true_ && string == other.string + } + + override fun hashCode(): Int = Objects.hash(true_, string) + + override fun toString(): String = + when { + true_ != null -> "Gradient{true_=$true_}" + string != null -> "Gradient{string=$string}" + _json != null -> "Gradient{_unknown=$_json}" + else -> throw IllegalStateException("Invalid Gradient") + } + + companion object { + + @JvmStatic fun ofTrue() = Gradient(true_ = JsonValue.from(true)) + + @JvmStatic fun ofString(string: String) = Gradient(string = string) + } + + /** + * An interface that defines how to map each variant of [Gradient] to a value of type [T]. + */ + interface Visitor { + + fun visitTrue(true_: JsonValue): T + + fun visitString(string: String): T + + /** + * Maps an unknown variant of [Gradient] to a value of type [T]. + * + * An instance of [Gradient] can contain an unknown variant if it was deserialized from + * data that doesn't match any known variant. For example, if the SDK is on an older + * version than the API, then the API may respond with new variants that the SDK is + * unaware of. + * + * @throws ImageKitInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw ImageKitInvalidDataException("Unknown Gradient: $json") + } + } + + internal class Deserializer : BaseDeserializer(Gradient::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): Gradient { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef()) + ?.let { Gradient(true_ = it, _json = json) } + ?.takeIf { it.isValid() }, + tryDeserialize(node, jacksonTypeRef())?.let { + Gradient(string = it, _json = json) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely incompatible with + // all the possible variants (e.g. deserializing from object). + 0 -> Gradient(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then use the first + // completely valid match, or simply the first match if none are completely + // valid. + else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() + } + } + } + + internal class Serializer : BaseSerializer(Gradient::class) { + + override fun serialize( + value: Gradient, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.true_ != null -> generator.writeObject(value.true_) + value.string != null -> generator.writeObject(value.string) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid Gradient") + } + } + } + } + + /** + * Controls the height of the solid color overlay. Accepts a numeric value or an arithmetic + * expression. Learn about + * [arithmetic expressions](https://imagekit.io/docs/arithmetic-expressions-in-transformations). + */ + @JsonDeserialize(using = Height.Deserializer::class) + @JsonSerialize(using = Height.Serializer::class) + class Height + private constructor( + private val number: Double? = null, + private val string: String? = null, + private val _json: JsonValue? = null, + ) { + + fun number(): Optional = Optional.ofNullable(number) + + fun string(): Optional = Optional.ofNullable(string) + + fun isNumber(): Boolean = number != null + + fun isString(): Boolean = string != null + + fun asNumber(): Double = number.getOrThrow("number") + + fun asString(): String = string.getOrThrow("string") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + number != null -> visitor.visitNumber(number) + string != null -> visitor.visitString(string) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): Height = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitNumber(number: Double) {} + + override fun visitString(string: String) {} + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitNumber(number: Double) = 1 + + override fun visitString(string: String) = 1 + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Height && number == other.number && string == other.string + } + + override fun hashCode(): Int = Objects.hash(number, string) + + override fun toString(): String = + when { + number != null -> "Height{number=$number}" + string != null -> "Height{string=$string}" + _json != null -> "Height{_unknown=$_json}" + else -> throw IllegalStateException("Invalid Height") + } + + companion object { + + @JvmStatic fun ofNumber(number: Double) = Height(number = number) + + @JvmStatic fun ofString(string: String) = Height(string = string) + } + + /** An interface that defines how to map each variant of [Height] to a value of type [T]. */ + interface Visitor { + + fun visitNumber(number: Double): T + + fun visitString(string: String): T + + /** + * Maps an unknown variant of [Height] to a value of type [T]. + * + * An instance of [Height] can contain an unknown variant if it was deserialized from + * data that doesn't match any known variant. For example, if the SDK is on an older + * version than the API, then the API may respond with new variants that the SDK is + * unaware of. + * + * @throws ImageKitInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw ImageKitInvalidDataException("Unknown Height: $json") + } + } + + internal class Deserializer : BaseDeserializer(Height::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): Height { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + Height(number = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + Height(string = it, _json = json) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely incompatible with + // all the possible variants (e.g. deserializing from object). + 0 -> Height(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then use the first + // completely valid match, or simply the first match if none are completely + // valid. + else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() + } + } + } + + internal class Serializer : BaseSerializer(Height::class) { + + override fun serialize( + value: Height, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.number != null -> generator.writeObject(value.number) + value.string != null -> generator.writeObject(value.string) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid Height") + } + } + } + } + + /** + * Specifies the corner radius of the solid color overlay. Set to `max` for circular or oval + * shape. See [radius](https://imagekit.io/docs/effects-and-enhancements#radius---r). + */ + @JsonDeserialize(using = Radius.Deserializer::class) + @JsonSerialize(using = Radius.Serializer::class) + class Radius + private constructor( + private val number: Double? = null, + private val max: JsonValue? = null, + private val _json: JsonValue? = null, + ) { + + fun number(): Optional = Optional.ofNullable(number) + + fun max(): Optional = Optional.ofNullable(max) + + fun isNumber(): Boolean = number != null + + fun isMax(): Boolean = max != null + + fun asNumber(): Double = number.getOrThrow("number") + + fun asMax(): JsonValue = max.getOrThrow("max") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + number != null -> visitor.visitNumber(number) + max != null -> visitor.visitMax(max) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): Radius = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitNumber(number: Double) {} + + override fun visitMax(max: JsonValue) { + max.let { + if (it != JsonValue.from("max")) { + throw ImageKitInvalidDataException("'max' is invalid, received $it") + } + } + } + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitNumber(number: Double) = 1 + + override fun visitMax(max: JsonValue) = + max.let { if (it == JsonValue.from("max")) 1 else 0 } + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Radius && number == other.number && max == other.max + } + + override fun hashCode(): Int = Objects.hash(number, max) + + override fun toString(): String = + when { + number != null -> "Radius{number=$number}" + max != null -> "Radius{max=$max}" + _json != null -> "Radius{_unknown=$_json}" + else -> throw IllegalStateException("Invalid Radius") + } + + companion object { + + @JvmStatic fun ofNumber(number: Double) = Radius(number = number) + + @JvmStatic fun ofMax() = Radius(max = JsonValue.from("max")) + } + + /** An interface that defines how to map each variant of [Radius] to a value of type [T]. */ + interface Visitor { + + fun visitNumber(number: Double): T + + fun visitMax(max: JsonValue): T + + /** + * Maps an unknown variant of [Radius] to a value of type [T]. + * + * An instance of [Radius] can contain an unknown variant if it was deserialized from + * data that doesn't match any known variant. For example, if the SDK is on an older + * version than the API, then the API may respond with new variants that the SDK is + * unaware of. + * + * @throws ImageKitInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw ImageKitInvalidDataException("Unknown Radius: $json") + } + } + + internal class Deserializer : BaseDeserializer(Radius::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): Radius { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef()) + ?.let { Radius(max = it, _json = json) } + ?.takeIf { it.isValid() }, + tryDeserialize(node, jacksonTypeRef())?.let { + Radius(number = it, _json = json) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely incompatible with + // all the possible variants (e.g. deserializing from object). + 0 -> Radius(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then use the first + // completely valid match, or simply the first match if none are completely + // valid. + else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() + } + } + } + + internal class Serializer : BaseSerializer(Radius::class) { + + override fun serialize( + value: Radius, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.number != null -> generator.writeObject(value.number) + value.max != null -> generator.writeObject(value.max) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid Radius") + } + } + } + } + + /** + * Controls the width of the solid color overlay. Accepts a numeric value or an arithmetic + * expression (e.g., `bw_mul_0.2` or `bh_div_2`). Learn about + * [arithmetic expressions](https://imagekit.io/docs/arithmetic-expressions-in-transformations). + */ + @JsonDeserialize(using = Width.Deserializer::class) + @JsonSerialize(using = Width.Serializer::class) + class Width + private constructor( + private val number: Double? = null, + private val string: String? = null, + private val _json: JsonValue? = null, + ) { + + fun number(): Optional = Optional.ofNullable(number) + + fun string(): Optional = Optional.ofNullable(string) + + fun isNumber(): Boolean = number != null + + fun isString(): Boolean = string != null + + fun asNumber(): Double = number.getOrThrow("number") + + fun asString(): String = string.getOrThrow("string") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + number != null -> visitor.visitNumber(number) + string != null -> visitor.visitString(string) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): Width = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitNumber(number: Double) {} + + override fun visitString(string: String) {} + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitNumber(number: Double) = 1 + + override fun visitString(string: String) = 1 + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Width && number == other.number && string == other.string + } + + override fun hashCode(): Int = Objects.hash(number, string) + + override fun toString(): String = + when { + number != null -> "Width{number=$number}" + string != null -> "Width{string=$string}" + _json != null -> "Width{_unknown=$_json}" + else -> throw IllegalStateException("Invalid Width") + } + + companion object { + + @JvmStatic fun ofNumber(number: Double) = Width(number = number) + + @JvmStatic fun ofString(string: String) = Width(string = string) + } + + /** An interface that defines how to map each variant of [Width] to a value of type [T]. */ + interface Visitor { + + fun visitNumber(number: Double): T + + fun visitString(string: String): T + + /** + * Maps an unknown variant of [Width] to a value of type [T]. + * + * An instance of [Width] can contain an unknown variant if it was deserialized from + * data that doesn't match any known variant. For example, if the SDK is on an older + * version than the API, then the API may respond with new variants that the SDK is + * unaware of. + * + * @throws ImageKitInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw ImageKitInvalidDataException("Unknown Width: $json") + } + } + + internal class Deserializer : BaseDeserializer(Width::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): Width { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + Width(number = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + Width(string = it, _json = json) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely incompatible with + // all the possible variants (e.g. deserializing from object). + 0 -> Width(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then use the first + // completely valid match, or simply the first match if none are completely + // valid. + else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() + } + } + } + + internal class Serializer : BaseSerializer(Width::class) { + + override fun serialize( + value: Width, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.number != null -> generator.writeObject(value.number) + value.string != null -> generator.writeObject(value.string) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid Width") + } + } + } + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is SolidColorOverlayTransformation && + alpha == other.alpha && + background == other.background && + gradient == other.gradient && + height == other.height && + radius == other.radius && + width == other.width && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(alpha, background, gradient, height, radius, width, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "SolidColorOverlayTransformation{alpha=$alpha, background=$background, gradient=$gradient, height=$height, radius=$radius, width=$width, additionalProperties=$additionalProperties}" +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/SrcOptions.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/SrcOptions.kt new file mode 100644 index 0000000..24c50b2 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/SrcOptions.kt @@ -0,0 +1,618 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.imagekit.api.core.ExcludeMissing +import com.imagekit.api.core.JsonField +import com.imagekit.api.core.JsonMissing +import com.imagekit.api.core.JsonValue +import com.imagekit.api.core.checkKnown +import com.imagekit.api.core.checkRequired +import com.imagekit.api.core.toImmutable +import com.imagekit.api.errors.ImageKitInvalidDataException +import java.util.Collections +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** + * Options for generating ImageKit URLs with transformations. See the + * [Transformations guide](https://imagekit.io/docs/transformations). + */ +class SrcOptions +private constructor( + private val src: JsonField, + private val urlEndpoint: JsonField, + private val expiresIn: JsonField, + private val queryParameters: JsonField, + private val signed: JsonField, + private val transformation: JsonField>, + private val transformationPosition: JsonField, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("src") @ExcludeMissing src: JsonField = JsonMissing.of(), + @JsonProperty("urlEndpoint") + @ExcludeMissing + urlEndpoint: JsonField = JsonMissing.of(), + @JsonProperty("expiresIn") @ExcludeMissing expiresIn: JsonField = JsonMissing.of(), + @JsonProperty("queryParameters") + @ExcludeMissing + queryParameters: JsonField = JsonMissing.of(), + @JsonProperty("signed") @ExcludeMissing signed: JsonField = JsonMissing.of(), + @JsonProperty("transformation") + @ExcludeMissing + transformation: JsonField> = JsonMissing.of(), + @JsonProperty("transformationPosition") + @ExcludeMissing + transformationPosition: JsonField = JsonMissing.of(), + ) : this( + src, + urlEndpoint, + expiresIn, + queryParameters, + signed, + transformation, + transformationPosition, + mutableMapOf(), + ) + + /** + * Accepts a relative or absolute path of the resource. If a relative path is provided, it is + * appended to the `urlEndpoint`. If an absolute path is provided, `urlEndpoint` is ignored. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun src(): String = src.getRequired("src") + + /** + * Get your urlEndpoint from the + * [ImageKit dashboard](https://imagekit.io/dashboard/url-endpoints). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun urlEndpoint(): String = urlEndpoint.getRequired("urlEndpoint") + + /** + * When you want the signed URL to expire, specified in seconds. If `expiresIn` is anything + * above 0, the URL will always be signed even if `signed` is set to false. If not specified and + * `signed` is `true`, the signed URL will not expire (valid indefinitely). + * + * Example: Setting `expiresIn: 3600` will make the URL expire 1 hour from generation time. + * After the expiry time, the signed URL will no longer be valid and ImageKit will return a 401 + * Unauthorized status code. + * + * [Learn + * more](https://imagekit.io/docs/media-delivery-basic-security#how-to-generate-signed-urls). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun expiresIn(): Optional = expiresIn.getOptional("expiresIn") + + /** + * These are additional query parameters that you want to add to the final URL. They can be any + * query parameters and not necessarily related to ImageKit. This is especially useful if you + * want to add a versioning parameter to your URLs. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun queryParameters(): Optional = + queryParameters.getOptional("queryParameters") + + /** + * Whether to sign the URL or not. Set this to `true` if you want to generate a signed URL. If + * `signed` is `true` and `expiresIn` is not specified, the signed URL will not expire (valid + * indefinitely). Note: If `expiresIn` is set to any value above 0, the URL will always be + * signed regardless of this setting. + * [Learn more](https://imagekit.io/docs/media-delivery-basic-security#how-to-generate-signed-urls). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun signed(): Optional = signed.getOptional("signed") + + /** + * An array of objects specifying the transformations to be applied in the URL. If more than one + * transformation is specified, they are applied in the order they are specified as chained + * transformations. See + * [Chained transformations](https://imagekit.io/docs/transformations#chained-transformations). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun transformation(): Optional> = + transformation.getOptional("transformation") + + /** + * By default, the transformation string is added as a query parameter in the URL, e.g., + * `?tr=w-100,h-100`. If you want to add the transformation string in the path of the URL, set + * this to `path`. Learn more in the + * [Transformations guide](https://imagekit.io/docs/transformations). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun transformationPosition(): Optional = + transformationPosition.getOptional("transformationPosition") + + /** + * Returns the raw JSON value of [src]. + * + * Unlike [src], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("src") @ExcludeMissing fun _src(): JsonField = src + + /** + * Returns the raw JSON value of [urlEndpoint]. + * + * Unlike [urlEndpoint], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("urlEndpoint") @ExcludeMissing fun _urlEndpoint(): JsonField = urlEndpoint + + /** + * Returns the raw JSON value of [expiresIn]. + * + * Unlike [expiresIn], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("expiresIn") @ExcludeMissing fun _expiresIn(): JsonField = expiresIn + + /** + * Returns the raw JSON value of [queryParameters]. + * + * Unlike [queryParameters], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("queryParameters") + @ExcludeMissing + fun _queryParameters(): JsonField = queryParameters + + /** + * Returns the raw JSON value of [signed]. + * + * Unlike [signed], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("signed") @ExcludeMissing fun _signed(): JsonField = signed + + /** + * Returns the raw JSON value of [transformation]. + * + * Unlike [transformation], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("transformation") + @ExcludeMissing + fun _transformation(): JsonField> = transformation + + /** + * Returns the raw JSON value of [transformationPosition]. + * + * Unlike [transformationPosition], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("transformationPosition") + @ExcludeMissing + fun _transformationPosition(): JsonField = transformationPosition + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [SrcOptions]. + * + * The following fields are required: + * ```java + * .src() + * .urlEndpoint() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [SrcOptions]. */ + class Builder internal constructor() { + + private var src: JsonField? = null + private var urlEndpoint: JsonField? = null + private var expiresIn: JsonField = JsonMissing.of() + private var queryParameters: JsonField = JsonMissing.of() + private var signed: JsonField = JsonMissing.of() + private var transformation: JsonField>? = null + private var transformationPosition: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(srcOptions: SrcOptions) = apply { + src = srcOptions.src + urlEndpoint = srcOptions.urlEndpoint + expiresIn = srcOptions.expiresIn + queryParameters = srcOptions.queryParameters + signed = srcOptions.signed + transformation = srcOptions.transformation.map { it.toMutableList() } + transformationPosition = srcOptions.transformationPosition + additionalProperties = srcOptions.additionalProperties.toMutableMap() + } + + /** + * Accepts a relative or absolute path of the resource. If a relative path is provided, it + * is appended to the `urlEndpoint`. If an absolute path is provided, `urlEndpoint` is + * ignored. + */ + fun src(src: String) = src(JsonField.of(src)) + + /** + * Sets [Builder.src] to an arbitrary JSON value. + * + * You should usually call [Builder.src] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun src(src: JsonField) = apply { this.src = src } + + /** + * Get your urlEndpoint from the + * [ImageKit dashboard](https://imagekit.io/dashboard/url-endpoints). + */ + fun urlEndpoint(urlEndpoint: String) = urlEndpoint(JsonField.of(urlEndpoint)) + + /** + * Sets [Builder.urlEndpoint] to an arbitrary JSON value. + * + * You should usually call [Builder.urlEndpoint] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun urlEndpoint(urlEndpoint: JsonField) = apply { this.urlEndpoint = urlEndpoint } + + /** + * When you want the signed URL to expire, specified in seconds. If `expiresIn` is anything + * above 0, the URL will always be signed even if `signed` is set to false. If not specified + * and `signed` is `true`, the signed URL will not expire (valid indefinitely). + * + * Example: Setting `expiresIn: 3600` will make the URL expire 1 hour from generation time. + * After the expiry time, the signed URL will no longer be valid and ImageKit will return a + * 401 Unauthorized status code. + * + * [Learn + * more](https://imagekit.io/docs/media-delivery-basic-security#how-to-generate-signed-urls). + */ + fun expiresIn(expiresIn: Double) = expiresIn(JsonField.of(expiresIn)) + + /** + * Sets [Builder.expiresIn] to an arbitrary JSON value. + * + * You should usually call [Builder.expiresIn] with a well-typed [Double] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun expiresIn(expiresIn: JsonField) = apply { this.expiresIn = expiresIn } + + /** + * These are additional query parameters that you want to add to the final URL. They can be + * any query parameters and not necessarily related to ImageKit. This is especially useful + * if you want to add a versioning parameter to your URLs. + */ + fun queryParameters(queryParameters: QueryParameters) = + queryParameters(JsonField.of(queryParameters)) + + /** + * Sets [Builder.queryParameters] to an arbitrary JSON value. + * + * You should usually call [Builder.queryParameters] with a well-typed [QueryParameters] + * value instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun queryParameters(queryParameters: JsonField) = apply { + this.queryParameters = queryParameters + } + + /** + * Whether to sign the URL or not. Set this to `true` if you want to generate a signed URL. + * If `signed` is `true` and `expiresIn` is not specified, the signed URL will not expire + * (valid indefinitely). Note: If `expiresIn` is set to any value above 0, the URL will + * always be signed regardless of this setting. + * [Learn more](https://imagekit.io/docs/media-delivery-basic-security#how-to-generate-signed-urls). + */ + fun signed(signed: Boolean) = signed(JsonField.of(signed)) + + /** + * Sets [Builder.signed] to an arbitrary JSON value. + * + * You should usually call [Builder.signed] with a well-typed [Boolean] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun signed(signed: JsonField) = apply { this.signed = signed } + + /** + * An array of objects specifying the transformations to be applied in the URL. If more than + * one transformation is specified, they are applied in the order they are specified as + * chained transformations. See + * [Chained transformations](https://imagekit.io/docs/transformations#chained-transformations). + */ + fun transformation(transformation: List) = + transformation(JsonField.of(transformation)) + + /** + * Sets [Builder.transformation] to an arbitrary JSON value. + * + * You should usually call [Builder.transformation] with a well-typed `List` + * value instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun transformation(transformation: JsonField>) = apply { + this.transformation = transformation.map { it.toMutableList() } + } + + /** + * Adds a single [Transformation] to [Builder.transformation]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addTransformation(transformation: Transformation) = apply { + this.transformation = + (this.transformation ?: JsonField.of(mutableListOf())).also { + checkKnown("transformation", it).add(transformation) + } + } + + /** + * By default, the transformation string is added as a query parameter in the URL, e.g., + * `?tr=w-100,h-100`. If you want to add the transformation string in the path of the URL, + * set this to `path`. Learn more in the + * [Transformations guide](https://imagekit.io/docs/transformations). + */ + fun transformationPosition(transformationPosition: TransformationPosition) = + transformationPosition(JsonField.of(transformationPosition)) + + /** + * Sets [Builder.transformationPosition] to an arbitrary JSON value. + * + * You should usually call [Builder.transformationPosition] with a well-typed + * [TransformationPosition] value instead. This method is primarily for setting the field to + * an undocumented or not yet supported value. + */ + fun transformationPosition(transformationPosition: JsonField) = + apply { + this.transformationPosition = transformationPosition + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [SrcOptions]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .src() + * .urlEndpoint() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): SrcOptions = + SrcOptions( + checkRequired("src", src), + checkRequired("urlEndpoint", urlEndpoint), + expiresIn, + queryParameters, + signed, + (transformation ?: JsonMissing.of()).map { it.toImmutable() }, + transformationPosition, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): SrcOptions = apply { + if (validated) { + return@apply + } + + src() + urlEndpoint() + expiresIn() + queryParameters().ifPresent { it.validate() } + signed() + transformation().ifPresent { it.forEach { it.validate() } } + transformationPosition().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (src.asKnown().isPresent) 1 else 0) + + (if (urlEndpoint.asKnown().isPresent) 1 else 0) + + (if (expiresIn.asKnown().isPresent) 1 else 0) + + (queryParameters.asKnown().getOrNull()?.validity() ?: 0) + + (if (signed.asKnown().isPresent) 1 else 0) + + (transformation.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + (transformationPosition.asKnown().getOrNull()?.validity() ?: 0) + + /** + * These are additional query parameters that you want to add to the final URL. They can be any + * query parameters and not necessarily related to ImageKit. This is especially useful if you + * want to add a versioning parameter to your URLs. + */ + class QueryParameters + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [QueryParameters]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [QueryParameters]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(queryParameters: QueryParameters) = apply { + additionalProperties = queryParameters.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [QueryParameters]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): QueryParameters = QueryParameters(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): QueryParameters = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is QueryParameters && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "QueryParameters{additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is SrcOptions && + src == other.src && + urlEndpoint == other.urlEndpoint && + expiresIn == other.expiresIn && + queryParameters == other.queryParameters && + signed == other.signed && + transformation == other.transformation && + transformationPosition == other.transformationPosition && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + src, + urlEndpoint, + expiresIn, + queryParameters, + signed, + transformation, + transformationPosition, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "SrcOptions{src=$src, urlEndpoint=$urlEndpoint, expiresIn=$expiresIn, queryParameters=$queryParameters, signed=$signed, transformation=$transformation, transformationPosition=$transformationPosition, additionalProperties=$additionalProperties}" +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/StreamingResolution.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/StreamingResolution.kt new file mode 100644 index 0000000..f9aa05d --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/StreamingResolution.kt @@ -0,0 +1,168 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models + +import com.fasterxml.jackson.annotation.JsonCreator +import com.imagekit.api.core.Enum +import com.imagekit.api.core.JsonField +import com.imagekit.api.errors.ImageKitInvalidDataException + +/** + * Available streaming resolutions for + * [adaptive bitrate streaming](https://imagekit.io/docs/adaptive-bitrate-streaming) + */ +class StreamingResolution @JsonCreator private constructor(private val value: JsonField) : + Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't match + * any known member, and you want to know that value. For example, if the SDK is on an older + * version than the API, then the API may respond with new members that the SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val _240 = of("240") + + @JvmField val _360 = of("360") + + @JvmField val _480 = of("480") + + @JvmField val _720 = of("720") + + @JvmField val _1080 = of("1080") + + @JvmField val _1440 = of("1440") + + @JvmField val _2160 = of("2160") + + @JvmStatic fun of(value: String) = StreamingResolution(JsonField.of(value)) + } + + /** An enum containing [StreamingResolution]'s known values. */ + enum class Known { + _240, + _360, + _480, + _720, + _1080, + _1440, + _2160, + } + + /** + * An enum containing [StreamingResolution]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [StreamingResolution] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if the SDK + * is on an older version than the API, then the API may respond with new members that the SDK + * is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + _240, + _360, + _480, + _720, + _1080, + _1440, + _2160, + /** + * An enum member indicating that [StreamingResolution] was instantiated with an unknown + * value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] if + * the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you want to + * throw for the unknown case. + */ + fun value(): Value = + when (this) { + _240 -> Value._240 + _360 -> Value._360 + _480 -> Value._480 + _720 -> Value._720 + _1080 -> Value._1080 + _1440 -> Value._1440 + _2160 -> Value._2160 + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and don't want + * to throw for the unknown case. + * + * @throws ImageKitInvalidDataException if this class instance's value is a not a known member. + */ + fun known(): Known = + when (this) { + _240 -> Known._240 + _360 -> Known._360 + _480 -> Known._480 + _720 -> Known._720 + _1080 -> Known._1080 + _1440 -> Known._1440 + _2160 -> Known._2160 + else -> throw ImageKitInvalidDataException("Unknown StreamingResolution: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for debugging and + * generally doesn't throw. + * + * @throws ImageKitInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { ImageKitInvalidDataException("Value is not a String") } + + private var validated: Boolean = false + + fun validate(): StreamingResolution = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is StreamingResolution && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/SubtitleOverlay.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/SubtitleOverlay.kt new file mode 100644 index 0000000..6a0485c --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/SubtitleOverlay.kt @@ -0,0 +1,528 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.imagekit.api.core.Enum +import com.imagekit.api.core.ExcludeMissing +import com.imagekit.api.core.JsonField +import com.imagekit.api.core.JsonMissing +import com.imagekit.api.core.JsonValue +import com.imagekit.api.core.checkKnown +import com.imagekit.api.core.checkRequired +import com.imagekit.api.core.toImmutable +import com.imagekit.api.errors.ImageKitInvalidDataException +import java.util.Collections +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +class SubtitleOverlay +private constructor( + private val position: JsonField, + private val timing: JsonField, + private val input: JsonField, + private val type: JsonValue, + private val encoding: JsonField, + private val transformation: JsonField>, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("position") + @ExcludeMissing + position: JsonField = JsonMissing.of(), + @JsonProperty("timing") @ExcludeMissing timing: JsonField = JsonMissing.of(), + @JsonProperty("input") @ExcludeMissing input: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(), + @JsonProperty("encoding") @ExcludeMissing encoding: JsonField = JsonMissing.of(), + @JsonProperty("transformation") + @ExcludeMissing + transformation: JsonField> = JsonMissing.of(), + ) : this(position, timing, input, type, encoding, transformation, mutableMapOf()) + + fun toBaseOverlay(): BaseOverlay = + BaseOverlay.builder().position(position).timing(timing).build() + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun position(): Optional = position.getOptional("position") + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun timing(): Optional = timing.getOptional("timing") + + /** + * Specifies the relative path to the subtitle file used as an overlay. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun input(): String = input.getRequired("input") + + /** + * Expected to always return the following: + * ```java + * JsonValue.from("subtitle") + * ``` + * + * However, this method can be useful for debugging and logging (e.g. if the server responded + * with an unexpected value). + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type + + /** + * The input path can be included in the layer as either `i-{input}` or + * `ie-{base64_encoded_input}`. By default, the SDK determines the appropriate format + * automatically. To always use base64 encoding (`ie-{base64}`), set this parameter to `base64`. + * To always use plain text (`i-{input}`), set it to `plain`. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun encoding(): Optional = encoding.getOptional("encoding") + + /** + * Control styling of the subtitle. See + * [Styling subtitles](https://imagekit.io/docs/add-overlays-on-videos#styling-controls-for-subtitles-layer). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun transformation(): Optional> = + transformation.getOptional("transformation") + + /** + * Returns the raw JSON value of [position]. + * + * Unlike [position], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("position") @ExcludeMissing fun _position(): JsonField = position + + /** + * Returns the raw JSON value of [timing]. + * + * Unlike [timing], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("timing") @ExcludeMissing fun _timing(): JsonField = timing + + /** + * Returns the raw JSON value of [input]. + * + * Unlike [input], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("input") @ExcludeMissing fun _input(): JsonField = input + + /** + * Returns the raw JSON value of [encoding]. + * + * Unlike [encoding], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("encoding") @ExcludeMissing fun _encoding(): JsonField = encoding + + /** + * Returns the raw JSON value of [transformation]. + * + * Unlike [transformation], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("transformation") + @ExcludeMissing + fun _transformation(): JsonField> = transformation + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [SubtitleOverlay]. + * + * The following fields are required: + * ```java + * .input() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [SubtitleOverlay]. */ + class Builder internal constructor() { + + private var position: JsonField = JsonMissing.of() + private var timing: JsonField = JsonMissing.of() + private var input: JsonField? = null + private var type: JsonValue = JsonValue.from("subtitle") + private var encoding: JsonField = JsonMissing.of() + private var transformation: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(subtitleOverlay: SubtitleOverlay) = apply { + position = subtitleOverlay.position + timing = subtitleOverlay.timing + input = subtitleOverlay.input + type = subtitleOverlay.type + encoding = subtitleOverlay.encoding + transformation = subtitleOverlay.transformation.map { it.toMutableList() } + additionalProperties = subtitleOverlay.additionalProperties.toMutableMap() + } + + fun position(position: OverlayPosition) = position(JsonField.of(position)) + + /** + * Sets [Builder.position] to an arbitrary JSON value. + * + * You should usually call [Builder.position] with a well-typed [OverlayPosition] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun position(position: JsonField) = apply { this.position = position } + + fun timing(timing: OverlayTiming) = timing(JsonField.of(timing)) + + /** + * Sets [Builder.timing] to an arbitrary JSON value. + * + * You should usually call [Builder.timing] with a well-typed [OverlayTiming] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun timing(timing: JsonField) = apply { this.timing = timing } + + /** Specifies the relative path to the subtitle file used as an overlay. */ + fun input(input: String) = input(JsonField.of(input)) + + /** + * Sets [Builder.input] to an arbitrary JSON value. + * + * You should usually call [Builder.input] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun input(input: JsonField) = apply { this.input = input } + + /** + * Sets the field to an arbitrary JSON value. + * + * It is usually unnecessary to call this method because the field defaults to the + * following: + * ```java + * JsonValue.from("subtitle") + * ``` + * + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun type(type: JsonValue) = apply { this.type = type } + + /** + * The input path can be included in the layer as either `i-{input}` or + * `ie-{base64_encoded_input}`. By default, the SDK determines the appropriate format + * automatically. To always use base64 encoding (`ie-{base64}`), set this parameter to + * `base64`. To always use plain text (`i-{input}`), set it to `plain`. + */ + fun encoding(encoding: Encoding) = encoding(JsonField.of(encoding)) + + /** + * Sets [Builder.encoding] to an arbitrary JSON value. + * + * You should usually call [Builder.encoding] with a well-typed [Encoding] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun encoding(encoding: JsonField) = apply { this.encoding = encoding } + + /** + * Control styling of the subtitle. See + * [Styling subtitles](https://imagekit.io/docs/add-overlays-on-videos#styling-controls-for-subtitles-layer). + */ + fun transformation(transformation: List) = + transformation(JsonField.of(transformation)) + + /** + * Sets [Builder.transformation] to an arbitrary JSON value. + * + * You should usually call [Builder.transformation] with a well-typed + * `List` value instead. This method is primarily for setting + * the field to an undocumented or not yet supported value. + */ + fun transformation(transformation: JsonField>) = apply { + this.transformation = transformation.map { it.toMutableList() } + } + + /** + * Adds a single [SubtitleOverlayTransformation] to [Builder.transformation]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addTransformation(transformation: SubtitleOverlayTransformation) = apply { + this.transformation = + (this.transformation ?: JsonField.of(mutableListOf())).also { + checkKnown("transformation", it).add(transformation) + } + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [SubtitleOverlay]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .input() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): SubtitleOverlay = + SubtitleOverlay( + position, + timing, + checkRequired("input", input), + type, + encoding, + (transformation ?: JsonMissing.of()).map { it.toImmutable() }, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): SubtitleOverlay = apply { + if (validated) { + return@apply + } + + position().ifPresent { it.validate() } + timing().ifPresent { it.validate() } + input() + _type().let { + if (it != JsonValue.from("subtitle")) { + throw ImageKitInvalidDataException("'type' is invalid, received $it") + } + } + encoding().ifPresent { it.validate() } + transformation().ifPresent { it.forEach { it.validate() } } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (position.asKnown().getOrNull()?.validity() ?: 0) + + (timing.asKnown().getOrNull()?.validity() ?: 0) + + (if (input.asKnown().isPresent) 1 else 0) + + type.let { if (it == JsonValue.from("subtitle")) 1 else 0 } + + (encoding.asKnown().getOrNull()?.validity() ?: 0) + + (transformation.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + /** + * The input path can be included in the layer as either `i-{input}` or + * `ie-{base64_encoded_input}`. By default, the SDK determines the appropriate format + * automatically. To always use base64 encoding (`ie-{base64}`), set this parameter to `base64`. + * To always use plain text (`i-{input}`), set it to `plain`. + */ + class Encoding @JsonCreator private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is on an + * older version than the API, then the API may respond with new members that the SDK is + * unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val AUTO = of("auto") + + @JvmField val PLAIN = of("plain") + + @JvmField val BASE64 = of("base64") + + @JvmStatic fun of(value: String) = Encoding(JsonField.of(value)) + } + + /** An enum containing [Encoding]'s known values. */ + enum class Known { + AUTO, + PLAIN, + BASE64, + } + + /** + * An enum containing [Encoding]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [Encoding] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if the + * SDK is on an older version than the API, then the API may respond with new members that + * the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + AUTO, + PLAIN, + BASE64, + /** An enum member indicating that [Encoding] was instantiated with an unknown value. */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] + * if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you want + * to throw for the unknown case. + */ + fun value(): Value = + when (this) { + AUTO -> Value.AUTO + PLAIN -> Value.PLAIN + BASE64 -> Value.BASE64 + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and don't + * want to throw for the unknown case. + * + * @throws ImageKitInvalidDataException if this class instance's value is a not a known + * member. + */ + fun known(): Known = + when (this) { + AUTO -> Known.AUTO + PLAIN -> Known.PLAIN + BASE64 -> Known.BASE64 + else -> throw ImageKitInvalidDataException("Unknown Encoding: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for debugging + * and generally doesn't throw. + * + * @throws ImageKitInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + ImageKitInvalidDataException("Value is not a String") + } + + private var validated: Boolean = false + + fun validate(): Encoding = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Encoding && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is SubtitleOverlay && + position == other.position && + timing == other.timing && + input == other.input && + type == other.type && + encoding == other.encoding && + transformation == other.transformation && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(position, timing, input, type, encoding, transformation, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "SubtitleOverlay{position=$position, timing=$timing, input=$input, type=$type, encoding=$encoding, transformation=$transformation, additionalProperties=$additionalProperties}" +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/SubtitleOverlayTransformation.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/SubtitleOverlayTransformation.kt new file mode 100644 index 0000000..11c122d --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/SubtitleOverlayTransformation.kt @@ -0,0 +1,627 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.imagekit.api.core.Enum +import com.imagekit.api.core.ExcludeMissing +import com.imagekit.api.core.JsonField +import com.imagekit.api.core.JsonMissing +import com.imagekit.api.core.JsonValue +import com.imagekit.api.errors.ImageKitInvalidDataException +import java.util.Collections +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** + * Subtitle styling options. + * [Learn more](https://imagekit.io/docs/add-overlays-on-videos#styling-controls-for-subtitles-layer) + * from the docs. + */ +class SubtitleOverlayTransformation +private constructor( + private val background: JsonField, + private val color: JsonField, + private val fontFamily: JsonField, + private val fontOutline: JsonField, + private val fontShadow: JsonField, + private val fontSize: JsonField, + private val typography: JsonField, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("background") + @ExcludeMissing + background: JsonField = JsonMissing.of(), + @JsonProperty("color") @ExcludeMissing color: JsonField = JsonMissing.of(), + @JsonProperty("fontFamily") + @ExcludeMissing + fontFamily: JsonField = JsonMissing.of(), + @JsonProperty("fontOutline") + @ExcludeMissing + fontOutline: JsonField = JsonMissing.of(), + @JsonProperty("fontShadow") + @ExcludeMissing + fontShadow: JsonField = JsonMissing.of(), + @JsonProperty("fontSize") @ExcludeMissing fontSize: JsonField = JsonMissing.of(), + @JsonProperty("typography") + @ExcludeMissing + typography: JsonField = JsonMissing.of(), + ) : this( + background, + color, + fontFamily, + fontOutline, + fontShadow, + fontSize, + typography, + mutableMapOf(), + ) + + /** + * Specifies the subtitle background color using a standard color name, an RGB color code (e.g., + * FF0000), or an RGBA color code (e.g., FFAABB50). + * + * [Subtitle styling + * options](https://imagekit.io/docs/add-overlays-on-videos#styling-controls-for-subtitles-layer) + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun background(): Optional = background.getOptional("background") + + /** + * Sets the font color of the subtitle text using a standard color name, an RGB color code + * (e.g., FF0000), or an RGBA color code (e.g., FFAABB50). + * + * [Subtitle styling + * options](https://imagekit.io/docs/add-overlays-on-videos#styling-controls-for-subtitles-layer) + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun color(): Optional = color.getOptional("color") + + /** + * Font family for subtitles. Refer to the + * [supported fonts](https://imagekit.io/docs/add-overlays-on-images#supported-text-font-list). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun fontFamily(): Optional = fontFamily.getOptional("fontFamily") + + /** + * Sets the font outline of the subtitle text. Requires the outline width (an integer) and the + * outline color (as an RGB color code, RGBA color code, or standard web color name) separated + * by an underscore. Example: `fol-2_blue` (outline width of 2px and outline color blue), + * `fol-2_A1CCDD` (outline width of 2px and outline color `#A1CCDD`) and `fol-2_A1CCDD50` + * (outline width of 2px and outline color `#A1CCDD` at 50% opacity). + * + * [Subtitle styling + * options](https://imagekit.io/docs/add-overlays-on-videos#styling-controls-for-subtitles-layer) + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun fontOutline(): Optional = fontOutline.getOptional("fontOutline") + + /** + * Sets the font shadow for the subtitle text. Requires the shadow color (as an RGB color code, + * RGBA color code, or standard web color name) and shadow indent (an integer) separated by an + * underscore. Example: `fsh-blue_2` (shadow color blue, indent of 2px), `fsh-A1CCDD_3` (shadow + * color `#A1CCDD`, indent of 3px), `fsh-A1CCDD50_3` (shadow color `#A1CCDD` at 50% opacity, + * indent of 3px). + * + * [Subtitle styling + * options](https://imagekit.io/docs/add-overlays-on-videos#styling-controls-for-subtitles-layer) + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun fontShadow(): Optional = fontShadow.getOptional("fontShadow") + + /** + * Sets the font size of subtitle text. + * + * [Subtitle styling + * options](https://imagekit.io/docs/add-overlays-on-videos#styling-controls-for-subtitles-layer) + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun fontSize(): Optional = fontSize.getOptional("fontSize") + + /** + * Sets the typography style of the subtitle text. Supports values are `b` for bold, `i` for + * italics, and `b_i` for bold with italics. + * + * [Subtitle styling + * options](https://imagekit.io/docs/add-overlays-on-videos#styling-controls-for-subtitles-layer) + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun typography(): Optional = typography.getOptional("typography") + + /** + * Returns the raw JSON value of [background]. + * + * Unlike [background], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("background") @ExcludeMissing fun _background(): JsonField = background + + /** + * Returns the raw JSON value of [color]. + * + * Unlike [color], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("color") @ExcludeMissing fun _color(): JsonField = color + + /** + * Returns the raw JSON value of [fontFamily]. + * + * Unlike [fontFamily], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("fontFamily") @ExcludeMissing fun _fontFamily(): JsonField = fontFamily + + /** + * Returns the raw JSON value of [fontOutline]. + * + * Unlike [fontOutline], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("fontOutline") @ExcludeMissing fun _fontOutline(): JsonField = fontOutline + + /** + * Returns the raw JSON value of [fontShadow]. + * + * Unlike [fontShadow], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("fontShadow") @ExcludeMissing fun _fontShadow(): JsonField = fontShadow + + /** + * Returns the raw JSON value of [fontSize]. + * + * Unlike [fontSize], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("fontSize") @ExcludeMissing fun _fontSize(): JsonField = fontSize + + /** + * Returns the raw JSON value of [typography]. + * + * Unlike [typography], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("typography") + @ExcludeMissing + fun _typography(): JsonField = typography + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [SubtitleOverlayTransformation]. + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [SubtitleOverlayTransformation]. */ + class Builder internal constructor() { + + private var background: JsonField = JsonMissing.of() + private var color: JsonField = JsonMissing.of() + private var fontFamily: JsonField = JsonMissing.of() + private var fontOutline: JsonField = JsonMissing.of() + private var fontShadow: JsonField = JsonMissing.of() + private var fontSize: JsonField = JsonMissing.of() + private var typography: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(subtitleOverlayTransformation: SubtitleOverlayTransformation) = apply { + background = subtitleOverlayTransformation.background + color = subtitleOverlayTransformation.color + fontFamily = subtitleOverlayTransformation.fontFamily + fontOutline = subtitleOverlayTransformation.fontOutline + fontShadow = subtitleOverlayTransformation.fontShadow + fontSize = subtitleOverlayTransformation.fontSize + typography = subtitleOverlayTransformation.typography + additionalProperties = subtitleOverlayTransformation.additionalProperties.toMutableMap() + } + + /** + * Specifies the subtitle background color using a standard color name, an RGB color code + * (e.g., FF0000), or an RGBA color code (e.g., FFAABB50). + * + * [Subtitle styling + * options](https://imagekit.io/docs/add-overlays-on-videos#styling-controls-for-subtitles-layer) + */ + fun background(background: String) = background(JsonField.of(background)) + + /** + * Sets [Builder.background] to an arbitrary JSON value. + * + * You should usually call [Builder.background] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun background(background: JsonField) = apply { this.background = background } + + /** + * Sets the font color of the subtitle text using a standard color name, an RGB color code + * (e.g., FF0000), or an RGBA color code (e.g., FFAABB50). + * + * [Subtitle styling + * options](https://imagekit.io/docs/add-overlays-on-videos#styling-controls-for-subtitles-layer) + */ + fun color(color: String) = color(JsonField.of(color)) + + /** + * Sets [Builder.color] to an arbitrary JSON value. + * + * You should usually call [Builder.color] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun color(color: JsonField) = apply { this.color = color } + + /** + * Font family for subtitles. Refer to the + * [supported fonts](https://imagekit.io/docs/add-overlays-on-images#supported-text-font-list). + */ + fun fontFamily(fontFamily: String) = fontFamily(JsonField.of(fontFamily)) + + /** + * Sets [Builder.fontFamily] to an arbitrary JSON value. + * + * You should usually call [Builder.fontFamily] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun fontFamily(fontFamily: JsonField) = apply { this.fontFamily = fontFamily } + + /** + * Sets the font outline of the subtitle text. Requires the outline width (an integer) and + * the outline color (as an RGB color code, RGBA color code, or standard web color name) + * separated by an underscore. Example: `fol-2_blue` (outline width of 2px and outline color + * blue), `fol-2_A1CCDD` (outline width of 2px and outline color `#A1CCDD`) and + * `fol-2_A1CCDD50` (outline width of 2px and outline color `#A1CCDD` at 50% opacity). + * + * [Subtitle styling + * options](https://imagekit.io/docs/add-overlays-on-videos#styling-controls-for-subtitles-layer) + */ + fun fontOutline(fontOutline: String) = fontOutline(JsonField.of(fontOutline)) + + /** + * Sets [Builder.fontOutline] to an arbitrary JSON value. + * + * You should usually call [Builder.fontOutline] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun fontOutline(fontOutline: JsonField) = apply { this.fontOutline = fontOutline } + + /** + * Sets the font shadow for the subtitle text. Requires the shadow color (as an RGB color + * code, RGBA color code, or standard web color name) and shadow indent (an integer) + * separated by an underscore. Example: `fsh-blue_2` (shadow color blue, indent of 2px), + * `fsh-A1CCDD_3` (shadow color `#A1CCDD`, indent of 3px), `fsh-A1CCDD50_3` (shadow color + * `#A1CCDD` at 50% opacity, indent of 3px). + * + * [Subtitle styling + * options](https://imagekit.io/docs/add-overlays-on-videos#styling-controls-for-subtitles-layer) + */ + fun fontShadow(fontShadow: String) = fontShadow(JsonField.of(fontShadow)) + + /** + * Sets [Builder.fontShadow] to an arbitrary JSON value. + * + * You should usually call [Builder.fontShadow] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun fontShadow(fontShadow: JsonField) = apply { this.fontShadow = fontShadow } + + /** + * Sets the font size of subtitle text. + * + * [Subtitle styling + * options](https://imagekit.io/docs/add-overlays-on-videos#styling-controls-for-subtitles-layer) + */ + fun fontSize(fontSize: Double) = fontSize(JsonField.of(fontSize)) + + /** + * Sets [Builder.fontSize] to an arbitrary JSON value. + * + * You should usually call [Builder.fontSize] with a well-typed [Double] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun fontSize(fontSize: JsonField) = apply { this.fontSize = fontSize } + + /** + * Sets the typography style of the subtitle text. Supports values are `b` for bold, `i` for + * italics, and `b_i` for bold with italics. + * + * [Subtitle styling + * options](https://imagekit.io/docs/add-overlays-on-videos#styling-controls-for-subtitles-layer) + */ + fun typography(typography: Typography) = typography(JsonField.of(typography)) + + /** + * Sets [Builder.typography] to an arbitrary JSON value. + * + * You should usually call [Builder.typography] with a well-typed [Typography] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun typography(typography: JsonField) = apply { this.typography = typography } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [SubtitleOverlayTransformation]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): SubtitleOverlayTransformation = + SubtitleOverlayTransformation( + background, + color, + fontFamily, + fontOutline, + fontShadow, + fontSize, + typography, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): SubtitleOverlayTransformation = apply { + if (validated) { + return@apply + } + + background() + color() + fontFamily() + fontOutline() + fontShadow() + fontSize() + typography().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (background.asKnown().isPresent) 1 else 0) + + (if (color.asKnown().isPresent) 1 else 0) + + (if (fontFamily.asKnown().isPresent) 1 else 0) + + (if (fontOutline.asKnown().isPresent) 1 else 0) + + (if (fontShadow.asKnown().isPresent) 1 else 0) + + (if (fontSize.asKnown().isPresent) 1 else 0) + + (typography.asKnown().getOrNull()?.validity() ?: 0) + + /** + * Sets the typography style of the subtitle text. Supports values are `b` for bold, `i` for + * italics, and `b_i` for bold with italics. + * + * [Subtitle styling + * options](https://imagekit.io/docs/add-overlays-on-videos#styling-controls-for-subtitles-layer) + */ + class Typography @JsonCreator private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is on an + * older version than the API, then the API may respond with new members that the SDK is + * unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val B = of("b") + + @JvmField val I = of("i") + + @JvmField val B_I = of("b_i") + + @JvmStatic fun of(value: String) = Typography(JsonField.of(value)) + } + + /** An enum containing [Typography]'s known values. */ + enum class Known { + B, + I, + B_I, + } + + /** + * An enum containing [Typography]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [Typography] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if the + * SDK is on an older version than the API, then the API may respond with new members that + * the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + B, + I, + B_I, + /** + * An enum member indicating that [Typography] was instantiated with an unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] + * if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you want + * to throw for the unknown case. + */ + fun value(): Value = + when (this) { + B -> Value.B + I -> Value.I + B_I -> Value.B_I + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and don't + * want to throw for the unknown case. + * + * @throws ImageKitInvalidDataException if this class instance's value is a not a known + * member. + */ + fun known(): Known = + when (this) { + B -> Known.B + I -> Known.I + B_I -> Known.B_I + else -> throw ImageKitInvalidDataException("Unknown Typography: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for debugging + * and generally doesn't throw. + * + * @throws ImageKitInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + ImageKitInvalidDataException("Value is not a String") + } + + private var validated: Boolean = false + + fun validate(): Typography = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Typography && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is SubtitleOverlayTransformation && + background == other.background && + color == other.color && + fontFamily == other.fontFamily && + fontOutline == other.fontOutline && + fontShadow == other.fontShadow && + fontSize == other.fontSize && + typography == other.typography && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + background, + color, + fontFamily, + fontOutline, + fontShadow, + fontSize, + typography, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "SubtitleOverlayTransformation{background=$background, color=$color, fontFamily=$fontFamily, fontOutline=$fontOutline, fontShadow=$fontShadow, fontSize=$fontSize, typography=$typography, additionalProperties=$additionalProperties}" +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/TextOverlay.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/TextOverlay.kt new file mode 100644 index 0000000..6bd7dfe --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/TextOverlay.kt @@ -0,0 +1,532 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.imagekit.api.core.Enum +import com.imagekit.api.core.ExcludeMissing +import com.imagekit.api.core.JsonField +import com.imagekit.api.core.JsonMissing +import com.imagekit.api.core.JsonValue +import com.imagekit.api.core.checkKnown +import com.imagekit.api.core.checkRequired +import com.imagekit.api.core.toImmutable +import com.imagekit.api.errors.ImageKitInvalidDataException +import java.util.Collections +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +class TextOverlay +private constructor( + private val position: JsonField, + private val timing: JsonField, + private val text: JsonField, + private val type: JsonValue, + private val encoding: JsonField, + private val transformation: JsonField>, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("position") + @ExcludeMissing + position: JsonField = JsonMissing.of(), + @JsonProperty("timing") @ExcludeMissing timing: JsonField = JsonMissing.of(), + @JsonProperty("text") @ExcludeMissing text: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(), + @JsonProperty("encoding") @ExcludeMissing encoding: JsonField = JsonMissing.of(), + @JsonProperty("transformation") + @ExcludeMissing + transformation: JsonField> = JsonMissing.of(), + ) : this(position, timing, text, type, encoding, transformation, mutableMapOf()) + + fun toBaseOverlay(): BaseOverlay = + BaseOverlay.builder().position(position).timing(timing).build() + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun position(): Optional = position.getOptional("position") + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun timing(): Optional = timing.getOptional("timing") + + /** + * Specifies the text to be displayed in the overlay. The SDK automatically handles special + * characters and encoding. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun text(): String = text.getRequired("text") + + /** + * Expected to always return the following: + * ```java + * JsonValue.from("text") + * ``` + * + * However, this method can be useful for debugging and logging (e.g. if the server responded + * with an unexpected value). + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type + + /** + * Text can be included in the layer as either `i-{input}` (plain text) or + * `ie-{base64_encoded_input}` (base64). By default, the SDK selects the appropriate format + * based on the input text. To always use base64 (`ie-{base64}`), set this parameter to + * `base64`. To always use plain text (`i-{input}`), set it to `plain`. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun encoding(): Optional = encoding.getOptional("encoding") + + /** + * Control styling of the text overlay. See + * [Text overlays](https://imagekit.io/docs/add-overlays-on-images#text-overlay). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun transformation(): Optional> = + transformation.getOptional("transformation") + + /** + * Returns the raw JSON value of [position]. + * + * Unlike [position], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("position") @ExcludeMissing fun _position(): JsonField = position + + /** + * Returns the raw JSON value of [timing]. + * + * Unlike [timing], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("timing") @ExcludeMissing fun _timing(): JsonField = timing + + /** + * Returns the raw JSON value of [text]. + * + * Unlike [text], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("text") @ExcludeMissing fun _text(): JsonField = text + + /** + * Returns the raw JSON value of [encoding]. + * + * Unlike [encoding], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("encoding") @ExcludeMissing fun _encoding(): JsonField = encoding + + /** + * Returns the raw JSON value of [transformation]. + * + * Unlike [transformation], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("transformation") + @ExcludeMissing + fun _transformation(): JsonField> = transformation + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [TextOverlay]. + * + * The following fields are required: + * ```java + * .text() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [TextOverlay]. */ + class Builder internal constructor() { + + private var position: JsonField = JsonMissing.of() + private var timing: JsonField = JsonMissing.of() + private var text: JsonField? = null + private var type: JsonValue = JsonValue.from("text") + private var encoding: JsonField = JsonMissing.of() + private var transformation: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(textOverlay: TextOverlay) = apply { + position = textOverlay.position + timing = textOverlay.timing + text = textOverlay.text + type = textOverlay.type + encoding = textOverlay.encoding + transformation = textOverlay.transformation.map { it.toMutableList() } + additionalProperties = textOverlay.additionalProperties.toMutableMap() + } + + fun position(position: OverlayPosition) = position(JsonField.of(position)) + + /** + * Sets [Builder.position] to an arbitrary JSON value. + * + * You should usually call [Builder.position] with a well-typed [OverlayPosition] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun position(position: JsonField) = apply { this.position = position } + + fun timing(timing: OverlayTiming) = timing(JsonField.of(timing)) + + /** + * Sets [Builder.timing] to an arbitrary JSON value. + * + * You should usually call [Builder.timing] with a well-typed [OverlayTiming] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun timing(timing: JsonField) = apply { this.timing = timing } + + /** + * Specifies the text to be displayed in the overlay. The SDK automatically handles special + * characters and encoding. + */ + fun text(text: String) = text(JsonField.of(text)) + + /** + * Sets [Builder.text] to an arbitrary JSON value. + * + * You should usually call [Builder.text] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun text(text: JsonField) = apply { this.text = text } + + /** + * Sets the field to an arbitrary JSON value. + * + * It is usually unnecessary to call this method because the field defaults to the + * following: + * ```java + * JsonValue.from("text") + * ``` + * + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun type(type: JsonValue) = apply { this.type = type } + + /** + * Text can be included in the layer as either `i-{input}` (plain text) or + * `ie-{base64_encoded_input}` (base64). By default, the SDK selects the appropriate format + * based on the input text. To always use base64 (`ie-{base64}`), set this parameter to + * `base64`. To always use plain text (`i-{input}`), set it to `plain`. + */ + fun encoding(encoding: Encoding) = encoding(JsonField.of(encoding)) + + /** + * Sets [Builder.encoding] to an arbitrary JSON value. + * + * You should usually call [Builder.encoding] with a well-typed [Encoding] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun encoding(encoding: JsonField) = apply { this.encoding = encoding } + + /** + * Control styling of the text overlay. See + * [Text overlays](https://imagekit.io/docs/add-overlays-on-images#text-overlay). + */ + fun transformation(transformation: List) = + transformation(JsonField.of(transformation)) + + /** + * Sets [Builder.transformation] to an arbitrary JSON value. + * + * You should usually call [Builder.transformation] with a well-typed + * `List` value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ + fun transformation(transformation: JsonField>) = apply { + this.transformation = transformation.map { it.toMutableList() } + } + + /** + * Adds a single [TextOverlayTransformation] to [Builder.transformation]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addTransformation(transformation: TextOverlayTransformation) = apply { + this.transformation = + (this.transformation ?: JsonField.of(mutableListOf())).also { + checkKnown("transformation", it).add(transformation) + } + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [TextOverlay]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .text() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): TextOverlay = + TextOverlay( + position, + timing, + checkRequired("text", text), + type, + encoding, + (transformation ?: JsonMissing.of()).map { it.toImmutable() }, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): TextOverlay = apply { + if (validated) { + return@apply + } + + position().ifPresent { it.validate() } + timing().ifPresent { it.validate() } + text() + _type().let { + if (it != JsonValue.from("text")) { + throw ImageKitInvalidDataException("'type' is invalid, received $it") + } + } + encoding().ifPresent { it.validate() } + transformation().ifPresent { it.forEach { it.validate() } } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (position.asKnown().getOrNull()?.validity() ?: 0) + + (timing.asKnown().getOrNull()?.validity() ?: 0) + + (if (text.asKnown().isPresent) 1 else 0) + + type.let { if (it == JsonValue.from("text")) 1 else 0 } + + (encoding.asKnown().getOrNull()?.validity() ?: 0) + + (transformation.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + /** + * Text can be included in the layer as either `i-{input}` (plain text) or + * `ie-{base64_encoded_input}` (base64). By default, the SDK selects the appropriate format + * based on the input text. To always use base64 (`ie-{base64}`), set this parameter to + * `base64`. To always use plain text (`i-{input}`), set it to `plain`. + */ + class Encoding @JsonCreator private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is on an + * older version than the API, then the API may respond with new members that the SDK is + * unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val AUTO = of("auto") + + @JvmField val PLAIN = of("plain") + + @JvmField val BASE64 = of("base64") + + @JvmStatic fun of(value: String) = Encoding(JsonField.of(value)) + } + + /** An enum containing [Encoding]'s known values. */ + enum class Known { + AUTO, + PLAIN, + BASE64, + } + + /** + * An enum containing [Encoding]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [Encoding] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if the + * SDK is on an older version than the API, then the API may respond with new members that + * the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + AUTO, + PLAIN, + BASE64, + /** An enum member indicating that [Encoding] was instantiated with an unknown value. */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] + * if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you want + * to throw for the unknown case. + */ + fun value(): Value = + when (this) { + AUTO -> Value.AUTO + PLAIN -> Value.PLAIN + BASE64 -> Value.BASE64 + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and don't + * want to throw for the unknown case. + * + * @throws ImageKitInvalidDataException if this class instance's value is a not a known + * member. + */ + fun known(): Known = + when (this) { + AUTO -> Known.AUTO + PLAIN -> Known.PLAIN + BASE64 -> Known.BASE64 + else -> throw ImageKitInvalidDataException("Unknown Encoding: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for debugging + * and generally doesn't throw. + * + * @throws ImageKitInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + ImageKitInvalidDataException("Value is not a String") + } + + private var validated: Boolean = false + + fun validate(): Encoding = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Encoding && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is TextOverlay && + position == other.position && + timing == other.timing && + text == other.text && + type == other.type && + encoding == other.encoding && + transformation == other.transformation && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(position, timing, text, type, encoding, transformation, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "TextOverlay{position=$position, timing=$timing, text=$text, type=$type, encoding=$encoding, transformation=$transformation, additionalProperties=$additionalProperties}" +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/TextOverlayTransformation.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/TextOverlayTransformation.kt new file mode 100644 index 0000000..c29f846 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/TextOverlayTransformation.kt @@ -0,0 +1,2061 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.fasterxml.jackson.core.JsonGenerator +import com.fasterxml.jackson.core.ObjectCodec +import com.fasterxml.jackson.databind.JsonNode +import com.fasterxml.jackson.databind.SerializerProvider +import com.fasterxml.jackson.databind.annotation.JsonDeserialize +import com.fasterxml.jackson.databind.annotation.JsonSerialize +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.imagekit.api.core.BaseDeserializer +import com.imagekit.api.core.BaseSerializer +import com.imagekit.api.core.Enum +import com.imagekit.api.core.ExcludeMissing +import com.imagekit.api.core.JsonField +import com.imagekit.api.core.JsonMissing +import com.imagekit.api.core.JsonValue +import com.imagekit.api.core.allMaxBy +import com.imagekit.api.core.getOrThrow +import com.imagekit.api.errors.ImageKitInvalidDataException +import java.util.Collections +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +class TextOverlayTransformation +private constructor( + private val alpha: JsonField, + private val background: JsonField, + private val flip: JsonField, + private val fontColor: JsonField, + private val fontFamily: JsonField, + private val fontSize: JsonField, + private val innerAlignment: JsonField, + private val lineHeight: JsonField, + private val padding: JsonField, + private val radius: JsonField, + private val rotation: JsonField, + private val typography: JsonField, + private val width: JsonField, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("alpha") @ExcludeMissing alpha: JsonField = JsonMissing.of(), + @JsonProperty("background") + @ExcludeMissing + background: JsonField = JsonMissing.of(), + @JsonProperty("flip") @ExcludeMissing flip: JsonField = JsonMissing.of(), + @JsonProperty("fontColor") @ExcludeMissing fontColor: JsonField = JsonMissing.of(), + @JsonProperty("fontFamily") + @ExcludeMissing + fontFamily: JsonField = JsonMissing.of(), + @JsonProperty("fontSize") @ExcludeMissing fontSize: JsonField = JsonMissing.of(), + @JsonProperty("innerAlignment") + @ExcludeMissing + innerAlignment: JsonField = JsonMissing.of(), + @JsonProperty("lineHeight") + @ExcludeMissing + lineHeight: JsonField = JsonMissing.of(), + @JsonProperty("padding") @ExcludeMissing padding: JsonField = JsonMissing.of(), + @JsonProperty("radius") @ExcludeMissing radius: JsonField = JsonMissing.of(), + @JsonProperty("rotation") @ExcludeMissing rotation: JsonField = JsonMissing.of(), + @JsonProperty("typography") + @ExcludeMissing + typography: JsonField = JsonMissing.of(), + @JsonProperty("width") @ExcludeMissing width: JsonField = JsonMissing.of(), + ) : this( + alpha, + background, + flip, + fontColor, + fontFamily, + fontSize, + innerAlignment, + lineHeight, + padding, + radius, + rotation, + typography, + width, + mutableMapOf(), + ) + + /** + * Specifies the transparency level of the text overlay. Accepts integers from `1` to `9`. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun alpha(): Optional = alpha.getOptional("alpha") + + /** + * Specifies the background color of the text overlay. Accepts an RGB hex code, an RGBA code, or + * a color name. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun background(): Optional = background.getOptional("background") + + /** + * Flip the text overlay horizontally, vertically, or both. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun flip(): Optional = flip.getOptional("flip") + + /** + * Specifies the font color of the overlaid text. Accepts an RGB hex code (e.g., `FF0000`), an + * RGBA code (e.g., `FFAABB50`), or a color name. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun fontColor(): Optional = fontColor.getOptional("fontColor") + + /** + * Specifies the font family of the overlaid text. Choose from the supported fonts list or use a + * custom font. See + * [Supported fonts](https://imagekit.io/docs/add-overlays-on-images#supported-text-font-list) + * and + * [Custom font](https://imagekit.io/docs/add-overlays-on-images#change-font-family-in-text-overlay). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun fontFamily(): Optional = fontFamily.getOptional("fontFamily") + + /** + * Specifies the font size of the overlaid text. Accepts a numeric value or an arithmetic + * expression. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun fontSize(): Optional = fontSize.getOptional("fontSize") + + /** + * Specifies the inner alignment of the text when width is more than the text length. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun innerAlignment(): Optional = innerAlignment.getOptional("innerAlignment") + + /** + * Specifies the line height of the text overlay. Accepts integer values representing line + * height in points. It can also accept + * [arithmetic expressions](https://imagekit.io/docs/arithmetic-expressions-in-transformations) + * such as `bw_mul_0.2`, or `bh_div_20`. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun lineHeight(): Optional = lineHeight.getOptional("lineHeight") + + /** + * Specifies the padding around the overlaid text. Can be provided as a single positive integer + * or multiple values separated by underscores (following CSS shorthand order). Arithmetic + * expressions are also accepted. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun padding(): Optional = padding.getOptional("padding") + + /** + * Specifies the corner radius of the text overlay. Set to `max` to achieve a circular or oval + * shape. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun radius(): Optional = radius.getOptional("radius") + + /** + * Specifies the rotation angle of the text overlay. Accepts a numeric value for clockwise + * rotation or a string prefixed with "N" for counter-clockwise rotation. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun rotation(): Optional = rotation.getOptional("rotation") + + /** + * Specifies the typography style of the text. Supported values: + * - Single styles: `b` (bold), `i` (italic), `strikethrough`. + * - Combinations: Any combination separated by underscores, e.g., `b_i`, `b_i_strikethrough`. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun typography(): Optional = typography.getOptional("typography") + + /** + * Specifies the maximum width (in pixels) of the overlaid text. The text wraps automatically, + * and arithmetic expressions (e.g., `bw_mul_0.2` or `bh_div_2`) are supported. Useful when used + * in conjunction with the `background`. Learn about + * [Arithmetic expressions](https://imagekit.io/docs/arithmetic-expressions-in-transformations). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun width(): Optional = width.getOptional("width") + + /** + * Returns the raw JSON value of [alpha]. + * + * Unlike [alpha], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("alpha") @ExcludeMissing fun _alpha(): JsonField = alpha + + /** + * Returns the raw JSON value of [background]. + * + * Unlike [background], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("background") @ExcludeMissing fun _background(): JsonField = background + + /** + * Returns the raw JSON value of [flip]. + * + * Unlike [flip], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("flip") @ExcludeMissing fun _flip(): JsonField = flip + + /** + * Returns the raw JSON value of [fontColor]. + * + * Unlike [fontColor], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("fontColor") @ExcludeMissing fun _fontColor(): JsonField = fontColor + + /** + * Returns the raw JSON value of [fontFamily]. + * + * Unlike [fontFamily], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("fontFamily") @ExcludeMissing fun _fontFamily(): JsonField = fontFamily + + /** + * Returns the raw JSON value of [fontSize]. + * + * Unlike [fontSize], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("fontSize") @ExcludeMissing fun _fontSize(): JsonField = fontSize + + /** + * Returns the raw JSON value of [innerAlignment]. + * + * Unlike [innerAlignment], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("innerAlignment") + @ExcludeMissing + fun _innerAlignment(): JsonField = innerAlignment + + /** + * Returns the raw JSON value of [lineHeight]. + * + * Unlike [lineHeight], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("lineHeight") + @ExcludeMissing + fun _lineHeight(): JsonField = lineHeight + + /** + * Returns the raw JSON value of [padding]. + * + * Unlike [padding], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("padding") @ExcludeMissing fun _padding(): JsonField = padding + + /** + * Returns the raw JSON value of [radius]. + * + * Unlike [radius], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("radius") @ExcludeMissing fun _radius(): JsonField = radius + + /** + * Returns the raw JSON value of [rotation]. + * + * Unlike [rotation], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("rotation") @ExcludeMissing fun _rotation(): JsonField = rotation + + /** + * Returns the raw JSON value of [typography]. + * + * Unlike [typography], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("typography") @ExcludeMissing fun _typography(): JsonField = typography + + /** + * Returns the raw JSON value of [width]. + * + * Unlike [width], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("width") @ExcludeMissing fun _width(): JsonField = width + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [TextOverlayTransformation]. + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [TextOverlayTransformation]. */ + class Builder internal constructor() { + + private var alpha: JsonField = JsonMissing.of() + private var background: JsonField = JsonMissing.of() + private var flip: JsonField = JsonMissing.of() + private var fontColor: JsonField = JsonMissing.of() + private var fontFamily: JsonField = JsonMissing.of() + private var fontSize: JsonField = JsonMissing.of() + private var innerAlignment: JsonField = JsonMissing.of() + private var lineHeight: JsonField = JsonMissing.of() + private var padding: JsonField = JsonMissing.of() + private var radius: JsonField = JsonMissing.of() + private var rotation: JsonField = JsonMissing.of() + private var typography: JsonField = JsonMissing.of() + private var width: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(textOverlayTransformation: TextOverlayTransformation) = apply { + alpha = textOverlayTransformation.alpha + background = textOverlayTransformation.background + flip = textOverlayTransformation.flip + fontColor = textOverlayTransformation.fontColor + fontFamily = textOverlayTransformation.fontFamily + fontSize = textOverlayTransformation.fontSize + innerAlignment = textOverlayTransformation.innerAlignment + lineHeight = textOverlayTransformation.lineHeight + padding = textOverlayTransformation.padding + radius = textOverlayTransformation.radius + rotation = textOverlayTransformation.rotation + typography = textOverlayTransformation.typography + width = textOverlayTransformation.width + additionalProperties = textOverlayTransformation.additionalProperties.toMutableMap() + } + + /** + * Specifies the transparency level of the text overlay. Accepts integers from `1` to `9`. + */ + fun alpha(alpha: Double) = alpha(JsonField.of(alpha)) + + /** + * Sets [Builder.alpha] to an arbitrary JSON value. + * + * You should usually call [Builder.alpha] with a well-typed [Double] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun alpha(alpha: JsonField) = apply { this.alpha = alpha } + + /** + * Specifies the background color of the text overlay. Accepts an RGB hex code, an RGBA + * code, or a color name. + */ + fun background(background: String) = background(JsonField.of(background)) + + /** + * Sets [Builder.background] to an arbitrary JSON value. + * + * You should usually call [Builder.background] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun background(background: JsonField) = apply { this.background = background } + + /** Flip the text overlay horizontally, vertically, or both. */ + fun flip(flip: Flip) = flip(JsonField.of(flip)) + + /** + * Sets [Builder.flip] to an arbitrary JSON value. + * + * You should usually call [Builder.flip] with a well-typed [Flip] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun flip(flip: JsonField) = apply { this.flip = flip } + + /** + * Specifies the font color of the overlaid text. Accepts an RGB hex code (e.g., `FF0000`), + * an RGBA code (e.g., `FFAABB50`), or a color name. + */ + fun fontColor(fontColor: String) = fontColor(JsonField.of(fontColor)) + + /** + * Sets [Builder.fontColor] to an arbitrary JSON value. + * + * You should usually call [Builder.fontColor] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun fontColor(fontColor: JsonField) = apply { this.fontColor = fontColor } + + /** + * Specifies the font family of the overlaid text. Choose from the supported fonts list or + * use a custom font. See + * [Supported fonts](https://imagekit.io/docs/add-overlays-on-images#supported-text-font-list) + * and + * [Custom font](https://imagekit.io/docs/add-overlays-on-images#change-font-family-in-text-overlay). + */ + fun fontFamily(fontFamily: String) = fontFamily(JsonField.of(fontFamily)) + + /** + * Sets [Builder.fontFamily] to an arbitrary JSON value. + * + * You should usually call [Builder.fontFamily] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun fontFamily(fontFamily: JsonField) = apply { this.fontFamily = fontFamily } + + /** + * Specifies the font size of the overlaid text. Accepts a numeric value or an arithmetic + * expression. + */ + fun fontSize(fontSize: FontSize) = fontSize(JsonField.of(fontSize)) + + /** + * Sets [Builder.fontSize] to an arbitrary JSON value. + * + * You should usually call [Builder.fontSize] with a well-typed [FontSize] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun fontSize(fontSize: JsonField) = apply { this.fontSize = fontSize } + + /** Alias for calling [fontSize] with `FontSize.ofNumber(number)`. */ + fun fontSize(number: Double) = fontSize(FontSize.ofNumber(number)) + + /** Alias for calling [fontSize] with `FontSize.ofString(string)`. */ + fun fontSize(string: String) = fontSize(FontSize.ofString(string)) + + /** Specifies the inner alignment of the text when width is more than the text length. */ + fun innerAlignment(innerAlignment: InnerAlignment) = + innerAlignment(JsonField.of(innerAlignment)) + + /** + * Sets [Builder.innerAlignment] to an arbitrary JSON value. + * + * You should usually call [Builder.innerAlignment] with a well-typed [InnerAlignment] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun innerAlignment(innerAlignment: JsonField) = apply { + this.innerAlignment = innerAlignment + } + + /** + * Specifies the line height of the text overlay. Accepts integer values representing line + * height in points. It can also accept + * [arithmetic expressions](https://imagekit.io/docs/arithmetic-expressions-in-transformations) + * such as `bw_mul_0.2`, or `bh_div_20`. + */ + fun lineHeight(lineHeight: LineHeight) = lineHeight(JsonField.of(lineHeight)) + + /** + * Sets [Builder.lineHeight] to an arbitrary JSON value. + * + * You should usually call [Builder.lineHeight] with a well-typed [LineHeight] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun lineHeight(lineHeight: JsonField) = apply { this.lineHeight = lineHeight } + + /** Alias for calling [lineHeight] with `LineHeight.ofNumber(number)`. */ + fun lineHeight(number: Double) = lineHeight(LineHeight.ofNumber(number)) + + /** Alias for calling [lineHeight] with `LineHeight.ofString(string)`. */ + fun lineHeight(string: String) = lineHeight(LineHeight.ofString(string)) + + /** + * Specifies the padding around the overlaid text. Can be provided as a single positive + * integer or multiple values separated by underscores (following CSS shorthand order). + * Arithmetic expressions are also accepted. + */ + fun padding(padding: Padding) = padding(JsonField.of(padding)) + + /** + * Sets [Builder.padding] to an arbitrary JSON value. + * + * You should usually call [Builder.padding] with a well-typed [Padding] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun padding(padding: JsonField) = apply { this.padding = padding } + + /** Alias for calling [padding] with `Padding.ofNumber(number)`. */ + fun padding(number: Double) = padding(Padding.ofNumber(number)) + + /** Alias for calling [padding] with `Padding.ofString(string)`. */ + fun padding(string: String) = padding(Padding.ofString(string)) + + /** + * Specifies the corner radius of the text overlay. Set to `max` to achieve a circular or + * oval shape. + */ + fun radius(radius: Radius) = radius(JsonField.of(radius)) + + /** + * Sets [Builder.radius] to an arbitrary JSON value. + * + * You should usually call [Builder.radius] with a well-typed [Radius] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun radius(radius: JsonField) = apply { this.radius = radius } + + /** Alias for calling [radius] with `Radius.ofNumber(number)`. */ + fun radius(number: Double) = radius(Radius.ofNumber(number)) + + /** Alias for calling [radius] with `Radius.ofMax()`. */ + fun radiusMax() = radius(Radius.ofMax()) + + /** + * Specifies the rotation angle of the text overlay. Accepts a numeric value for clockwise + * rotation or a string prefixed with "N" for counter-clockwise rotation. + */ + fun rotation(rotation: Rotation) = rotation(JsonField.of(rotation)) + + /** + * Sets [Builder.rotation] to an arbitrary JSON value. + * + * You should usually call [Builder.rotation] with a well-typed [Rotation] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun rotation(rotation: JsonField) = apply { this.rotation = rotation } + + /** Alias for calling [rotation] with `Rotation.ofNumber(number)`. */ + fun rotation(number: Double) = rotation(Rotation.ofNumber(number)) + + /** Alias for calling [rotation] with `Rotation.ofString(string)`. */ + fun rotation(string: String) = rotation(Rotation.ofString(string)) + + /** + * Specifies the typography style of the text. Supported values: + * - Single styles: `b` (bold), `i` (italic), `strikethrough`. + * - Combinations: Any combination separated by underscores, e.g., `b_i`, + * `b_i_strikethrough`. + */ + fun typography(typography: String) = typography(JsonField.of(typography)) + + /** + * Sets [Builder.typography] to an arbitrary JSON value. + * + * You should usually call [Builder.typography] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun typography(typography: JsonField) = apply { this.typography = typography } + + /** + * Specifies the maximum width (in pixels) of the overlaid text. The text wraps + * automatically, and arithmetic expressions (e.g., `bw_mul_0.2` or `bh_div_2`) are + * supported. Useful when used in conjunction with the `background`. Learn about + * [Arithmetic expressions](https://imagekit.io/docs/arithmetic-expressions-in-transformations). + */ + fun width(width: Width) = width(JsonField.of(width)) + + /** + * Sets [Builder.width] to an arbitrary JSON value. + * + * You should usually call [Builder.width] with a well-typed [Width] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun width(width: JsonField) = apply { this.width = width } + + /** Alias for calling [width] with `Width.ofNumber(number)`. */ + fun width(number: Double) = width(Width.ofNumber(number)) + + /** Alias for calling [width] with `Width.ofString(string)`. */ + fun width(string: String) = width(Width.ofString(string)) + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [TextOverlayTransformation]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): TextOverlayTransformation = + TextOverlayTransformation( + alpha, + background, + flip, + fontColor, + fontFamily, + fontSize, + innerAlignment, + lineHeight, + padding, + radius, + rotation, + typography, + width, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): TextOverlayTransformation = apply { + if (validated) { + return@apply + } + + alpha() + background() + flip().ifPresent { it.validate() } + fontColor() + fontFamily() + fontSize().ifPresent { it.validate() } + innerAlignment().ifPresent { it.validate() } + lineHeight().ifPresent { it.validate() } + padding().ifPresent { it.validate() } + radius().ifPresent { it.validate() } + rotation().ifPresent { it.validate() } + typography() + width().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (alpha.asKnown().isPresent) 1 else 0) + + (if (background.asKnown().isPresent) 1 else 0) + + (flip.asKnown().getOrNull()?.validity() ?: 0) + + (if (fontColor.asKnown().isPresent) 1 else 0) + + (if (fontFamily.asKnown().isPresent) 1 else 0) + + (fontSize.asKnown().getOrNull()?.validity() ?: 0) + + (innerAlignment.asKnown().getOrNull()?.validity() ?: 0) + + (lineHeight.asKnown().getOrNull()?.validity() ?: 0) + + (padding.asKnown().getOrNull()?.validity() ?: 0) + + (radius.asKnown().getOrNull()?.validity() ?: 0) + + (rotation.asKnown().getOrNull()?.validity() ?: 0) + + (if (typography.asKnown().isPresent) 1 else 0) + + (width.asKnown().getOrNull()?.validity() ?: 0) + + /** Flip the text overlay horizontally, vertically, or both. */ + class Flip @JsonCreator private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is on an + * older version than the API, then the API may respond with new members that the SDK is + * unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val H = of("h") + + @JvmField val V = of("v") + + @JvmField val H_V = of("h_v") + + @JvmField val V_H = of("v_h") + + @JvmStatic fun of(value: String) = Flip(JsonField.of(value)) + } + + /** An enum containing [Flip]'s known values. */ + enum class Known { + H, + V, + H_V, + V_H, + } + + /** + * An enum containing [Flip]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [Flip] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if the + * SDK is on an older version than the API, then the API may respond with new members that + * the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + H, + V, + H_V, + V_H, + /** An enum member indicating that [Flip] was instantiated with an unknown value. */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] + * if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you want + * to throw for the unknown case. + */ + fun value(): Value = + when (this) { + H -> Value.H + V -> Value.V + H_V -> Value.H_V + V_H -> Value.V_H + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and don't + * want to throw for the unknown case. + * + * @throws ImageKitInvalidDataException if this class instance's value is a not a known + * member. + */ + fun known(): Known = + when (this) { + H -> Known.H + V -> Known.V + H_V -> Known.H_V + V_H -> Known.V_H + else -> throw ImageKitInvalidDataException("Unknown Flip: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for debugging + * and generally doesn't throw. + * + * @throws ImageKitInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + ImageKitInvalidDataException("Value is not a String") + } + + private var validated: Boolean = false + + fun validate(): Flip = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Flip && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + /** + * Specifies the font size of the overlaid text. Accepts a numeric value or an arithmetic + * expression. + */ + @JsonDeserialize(using = FontSize.Deserializer::class) + @JsonSerialize(using = FontSize.Serializer::class) + class FontSize + private constructor( + private val number: Double? = null, + private val string: String? = null, + private val _json: JsonValue? = null, + ) { + + fun number(): Optional = Optional.ofNullable(number) + + fun string(): Optional = Optional.ofNullable(string) + + fun isNumber(): Boolean = number != null + + fun isString(): Boolean = string != null + + fun asNumber(): Double = number.getOrThrow("number") + + fun asString(): String = string.getOrThrow("string") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + number != null -> visitor.visitNumber(number) + string != null -> visitor.visitString(string) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): FontSize = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitNumber(number: Double) {} + + override fun visitString(string: String) {} + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitNumber(number: Double) = 1 + + override fun visitString(string: String) = 1 + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is FontSize && number == other.number && string == other.string + } + + override fun hashCode(): Int = Objects.hash(number, string) + + override fun toString(): String = + when { + number != null -> "FontSize{number=$number}" + string != null -> "FontSize{string=$string}" + _json != null -> "FontSize{_unknown=$_json}" + else -> throw IllegalStateException("Invalid FontSize") + } + + companion object { + + @JvmStatic fun ofNumber(number: Double) = FontSize(number = number) + + @JvmStatic fun ofString(string: String) = FontSize(string = string) + } + + /** + * An interface that defines how to map each variant of [FontSize] to a value of type [T]. + */ + interface Visitor { + + fun visitNumber(number: Double): T + + fun visitString(string: String): T + + /** + * Maps an unknown variant of [FontSize] to a value of type [T]. + * + * An instance of [FontSize] can contain an unknown variant if it was deserialized from + * data that doesn't match any known variant. For example, if the SDK is on an older + * version than the API, then the API may respond with new variants that the SDK is + * unaware of. + * + * @throws ImageKitInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw ImageKitInvalidDataException("Unknown FontSize: $json") + } + } + + internal class Deserializer : BaseDeserializer(FontSize::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): FontSize { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + FontSize(number = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + FontSize(string = it, _json = json) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely incompatible with + // all the possible variants (e.g. deserializing from object). + 0 -> FontSize(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then use the first + // completely valid match, or simply the first match if none are completely + // valid. + else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() + } + } + } + + internal class Serializer : BaseSerializer(FontSize::class) { + + override fun serialize( + value: FontSize, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.number != null -> generator.writeObject(value.number) + value.string != null -> generator.writeObject(value.string) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid FontSize") + } + } + } + } + + /** Specifies the inner alignment of the text when width is more than the text length. */ + class InnerAlignment @JsonCreator private constructor(private val value: JsonField) : + Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is on an + * older version than the API, then the API may respond with new members that the SDK is + * unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val LEFT = of("left") + + @JvmField val RIGHT = of("right") + + @JvmField val CENTER = of("center") + + @JvmStatic fun of(value: String) = InnerAlignment(JsonField.of(value)) + } + + /** An enum containing [InnerAlignment]'s known values. */ + enum class Known { + LEFT, + RIGHT, + CENTER, + } + + /** + * An enum containing [InnerAlignment]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [InnerAlignment] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if the + * SDK is on an older version than the API, then the API may respond with new members that + * the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + LEFT, + RIGHT, + CENTER, + /** + * An enum member indicating that [InnerAlignment] was instantiated with an unknown + * value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] + * if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you want + * to throw for the unknown case. + */ + fun value(): Value = + when (this) { + LEFT -> Value.LEFT + RIGHT -> Value.RIGHT + CENTER -> Value.CENTER + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and don't + * want to throw for the unknown case. + * + * @throws ImageKitInvalidDataException if this class instance's value is a not a known + * member. + */ + fun known(): Known = + when (this) { + LEFT -> Known.LEFT + RIGHT -> Known.RIGHT + CENTER -> Known.CENTER + else -> throw ImageKitInvalidDataException("Unknown InnerAlignment: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for debugging + * and generally doesn't throw. + * + * @throws ImageKitInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + ImageKitInvalidDataException("Value is not a String") + } + + private var validated: Boolean = false + + fun validate(): InnerAlignment = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is InnerAlignment && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + /** + * Specifies the line height of the text overlay. Accepts integer values representing line + * height in points. It can also accept + * [arithmetic expressions](https://imagekit.io/docs/arithmetic-expressions-in-transformations) + * such as `bw_mul_0.2`, or `bh_div_20`. + */ + @JsonDeserialize(using = LineHeight.Deserializer::class) + @JsonSerialize(using = LineHeight.Serializer::class) + class LineHeight + private constructor( + private val number: Double? = null, + private val string: String? = null, + private val _json: JsonValue? = null, + ) { + + fun number(): Optional = Optional.ofNullable(number) + + fun string(): Optional = Optional.ofNullable(string) + + fun isNumber(): Boolean = number != null + + fun isString(): Boolean = string != null + + fun asNumber(): Double = number.getOrThrow("number") + + fun asString(): String = string.getOrThrow("string") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + number != null -> visitor.visitNumber(number) + string != null -> visitor.visitString(string) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): LineHeight = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitNumber(number: Double) {} + + override fun visitString(string: String) {} + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitNumber(number: Double) = 1 + + override fun visitString(string: String) = 1 + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is LineHeight && number == other.number && string == other.string + } + + override fun hashCode(): Int = Objects.hash(number, string) + + override fun toString(): String = + when { + number != null -> "LineHeight{number=$number}" + string != null -> "LineHeight{string=$string}" + _json != null -> "LineHeight{_unknown=$_json}" + else -> throw IllegalStateException("Invalid LineHeight") + } + + companion object { + + @JvmStatic fun ofNumber(number: Double) = LineHeight(number = number) + + @JvmStatic fun ofString(string: String) = LineHeight(string = string) + } + + /** + * An interface that defines how to map each variant of [LineHeight] to a value of type [T]. + */ + interface Visitor { + + fun visitNumber(number: Double): T + + fun visitString(string: String): T + + /** + * Maps an unknown variant of [LineHeight] to a value of type [T]. + * + * An instance of [LineHeight] can contain an unknown variant if it was deserialized + * from data that doesn't match any known variant. For example, if the SDK is on an + * older version than the API, then the API may respond with new variants that the SDK + * is unaware of. + * + * @throws ImageKitInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw ImageKitInvalidDataException("Unknown LineHeight: $json") + } + } + + internal class Deserializer : BaseDeserializer(LineHeight::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): LineHeight { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + LineHeight(number = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + LineHeight(string = it, _json = json) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely incompatible with + // all the possible variants (e.g. deserializing from object). + 0 -> LineHeight(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then use the first + // completely valid match, or simply the first match if none are completely + // valid. + else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() + } + } + } + + internal class Serializer : BaseSerializer(LineHeight::class) { + + override fun serialize( + value: LineHeight, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.number != null -> generator.writeObject(value.number) + value.string != null -> generator.writeObject(value.string) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid LineHeight") + } + } + } + } + + /** + * Specifies the padding around the overlaid text. Can be provided as a single positive integer + * or multiple values separated by underscores (following CSS shorthand order). Arithmetic + * expressions are also accepted. + */ + @JsonDeserialize(using = Padding.Deserializer::class) + @JsonSerialize(using = Padding.Serializer::class) + class Padding + private constructor( + private val number: Double? = null, + private val string: String? = null, + private val _json: JsonValue? = null, + ) { + + fun number(): Optional = Optional.ofNullable(number) + + fun string(): Optional = Optional.ofNullable(string) + + fun isNumber(): Boolean = number != null + + fun isString(): Boolean = string != null + + fun asNumber(): Double = number.getOrThrow("number") + + fun asString(): String = string.getOrThrow("string") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + number != null -> visitor.visitNumber(number) + string != null -> visitor.visitString(string) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): Padding = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitNumber(number: Double) {} + + override fun visitString(string: String) {} + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitNumber(number: Double) = 1 + + override fun visitString(string: String) = 1 + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Padding && number == other.number && string == other.string + } + + override fun hashCode(): Int = Objects.hash(number, string) + + override fun toString(): String = + when { + number != null -> "Padding{number=$number}" + string != null -> "Padding{string=$string}" + _json != null -> "Padding{_unknown=$_json}" + else -> throw IllegalStateException("Invalid Padding") + } + + companion object { + + @JvmStatic fun ofNumber(number: Double) = Padding(number = number) + + @JvmStatic fun ofString(string: String) = Padding(string = string) + } + + /** + * An interface that defines how to map each variant of [Padding] to a value of type [T]. + */ + interface Visitor { + + fun visitNumber(number: Double): T + + fun visitString(string: String): T + + /** + * Maps an unknown variant of [Padding] to a value of type [T]. + * + * An instance of [Padding] can contain an unknown variant if it was deserialized from + * data that doesn't match any known variant. For example, if the SDK is on an older + * version than the API, then the API may respond with new variants that the SDK is + * unaware of. + * + * @throws ImageKitInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw ImageKitInvalidDataException("Unknown Padding: $json") + } + } + + internal class Deserializer : BaseDeserializer(Padding::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): Padding { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + Padding(number = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + Padding(string = it, _json = json) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely incompatible with + // all the possible variants (e.g. deserializing from object). + 0 -> Padding(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then use the first + // completely valid match, or simply the first match if none are completely + // valid. + else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() + } + } + } + + internal class Serializer : BaseSerializer(Padding::class) { + + override fun serialize( + value: Padding, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.number != null -> generator.writeObject(value.number) + value.string != null -> generator.writeObject(value.string) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid Padding") + } + } + } + } + + /** + * Specifies the corner radius of the text overlay. Set to `max` to achieve a circular or oval + * shape. + */ + @JsonDeserialize(using = Radius.Deserializer::class) + @JsonSerialize(using = Radius.Serializer::class) + class Radius + private constructor( + private val number: Double? = null, + private val max: JsonValue? = null, + private val _json: JsonValue? = null, + ) { + + fun number(): Optional = Optional.ofNullable(number) + + fun max(): Optional = Optional.ofNullable(max) + + fun isNumber(): Boolean = number != null + + fun isMax(): Boolean = max != null + + fun asNumber(): Double = number.getOrThrow("number") + + fun asMax(): JsonValue = max.getOrThrow("max") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + number != null -> visitor.visitNumber(number) + max != null -> visitor.visitMax(max) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): Radius = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitNumber(number: Double) {} + + override fun visitMax(max: JsonValue) { + max.let { + if (it != JsonValue.from("max")) { + throw ImageKitInvalidDataException("'max' is invalid, received $it") + } + } + } + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitNumber(number: Double) = 1 + + override fun visitMax(max: JsonValue) = + max.let { if (it == JsonValue.from("max")) 1 else 0 } + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Radius && number == other.number && max == other.max + } + + override fun hashCode(): Int = Objects.hash(number, max) + + override fun toString(): String = + when { + number != null -> "Radius{number=$number}" + max != null -> "Radius{max=$max}" + _json != null -> "Radius{_unknown=$_json}" + else -> throw IllegalStateException("Invalid Radius") + } + + companion object { + + @JvmStatic fun ofNumber(number: Double) = Radius(number = number) + + @JvmStatic fun ofMax() = Radius(max = JsonValue.from("max")) + } + + /** An interface that defines how to map each variant of [Radius] to a value of type [T]. */ + interface Visitor { + + fun visitNumber(number: Double): T + + fun visitMax(max: JsonValue): T + + /** + * Maps an unknown variant of [Radius] to a value of type [T]. + * + * An instance of [Radius] can contain an unknown variant if it was deserialized from + * data that doesn't match any known variant. For example, if the SDK is on an older + * version than the API, then the API may respond with new variants that the SDK is + * unaware of. + * + * @throws ImageKitInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw ImageKitInvalidDataException("Unknown Radius: $json") + } + } + + internal class Deserializer : BaseDeserializer(Radius::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): Radius { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef()) + ?.let { Radius(max = it, _json = json) } + ?.takeIf { it.isValid() }, + tryDeserialize(node, jacksonTypeRef())?.let { + Radius(number = it, _json = json) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely incompatible with + // all the possible variants (e.g. deserializing from object). + 0 -> Radius(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then use the first + // completely valid match, or simply the first match if none are completely + // valid. + else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() + } + } + } + + internal class Serializer : BaseSerializer(Radius::class) { + + override fun serialize( + value: Radius, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.number != null -> generator.writeObject(value.number) + value.max != null -> generator.writeObject(value.max) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid Radius") + } + } + } + } + + /** + * Specifies the rotation angle of the text overlay. Accepts a numeric value for clockwise + * rotation or a string prefixed with "N" for counter-clockwise rotation. + */ + @JsonDeserialize(using = Rotation.Deserializer::class) + @JsonSerialize(using = Rotation.Serializer::class) + class Rotation + private constructor( + private val number: Double? = null, + private val string: String? = null, + private val _json: JsonValue? = null, + ) { + + fun number(): Optional = Optional.ofNullable(number) + + fun string(): Optional = Optional.ofNullable(string) + + fun isNumber(): Boolean = number != null + + fun isString(): Boolean = string != null + + fun asNumber(): Double = number.getOrThrow("number") + + fun asString(): String = string.getOrThrow("string") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + number != null -> visitor.visitNumber(number) + string != null -> visitor.visitString(string) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): Rotation = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitNumber(number: Double) {} + + override fun visitString(string: String) {} + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitNumber(number: Double) = 1 + + override fun visitString(string: String) = 1 + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Rotation && number == other.number && string == other.string + } + + override fun hashCode(): Int = Objects.hash(number, string) + + override fun toString(): String = + when { + number != null -> "Rotation{number=$number}" + string != null -> "Rotation{string=$string}" + _json != null -> "Rotation{_unknown=$_json}" + else -> throw IllegalStateException("Invalid Rotation") + } + + companion object { + + @JvmStatic fun ofNumber(number: Double) = Rotation(number = number) + + @JvmStatic fun ofString(string: String) = Rotation(string = string) + } + + /** + * An interface that defines how to map each variant of [Rotation] to a value of type [T]. + */ + interface Visitor { + + fun visitNumber(number: Double): T + + fun visitString(string: String): T + + /** + * Maps an unknown variant of [Rotation] to a value of type [T]. + * + * An instance of [Rotation] can contain an unknown variant if it was deserialized from + * data that doesn't match any known variant. For example, if the SDK is on an older + * version than the API, then the API may respond with new variants that the SDK is + * unaware of. + * + * @throws ImageKitInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw ImageKitInvalidDataException("Unknown Rotation: $json") + } + } + + internal class Deserializer : BaseDeserializer(Rotation::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): Rotation { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + Rotation(number = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + Rotation(string = it, _json = json) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely incompatible with + // all the possible variants (e.g. deserializing from object). + 0 -> Rotation(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then use the first + // completely valid match, or simply the first match if none are completely + // valid. + else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() + } + } + } + + internal class Serializer : BaseSerializer(Rotation::class) { + + override fun serialize( + value: Rotation, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.number != null -> generator.writeObject(value.number) + value.string != null -> generator.writeObject(value.string) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid Rotation") + } + } + } + } + + /** + * Specifies the maximum width (in pixels) of the overlaid text. The text wraps automatically, + * and arithmetic expressions (e.g., `bw_mul_0.2` or `bh_div_2`) are supported. Useful when used + * in conjunction with the `background`. Learn about + * [Arithmetic expressions](https://imagekit.io/docs/arithmetic-expressions-in-transformations). + */ + @JsonDeserialize(using = Width.Deserializer::class) + @JsonSerialize(using = Width.Serializer::class) + class Width + private constructor( + private val number: Double? = null, + private val string: String? = null, + private val _json: JsonValue? = null, + ) { + + fun number(): Optional = Optional.ofNullable(number) + + fun string(): Optional = Optional.ofNullable(string) + + fun isNumber(): Boolean = number != null + + fun isString(): Boolean = string != null + + fun asNumber(): Double = number.getOrThrow("number") + + fun asString(): String = string.getOrThrow("string") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + number != null -> visitor.visitNumber(number) + string != null -> visitor.visitString(string) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): Width = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitNumber(number: Double) {} + + override fun visitString(string: String) {} + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitNumber(number: Double) = 1 + + override fun visitString(string: String) = 1 + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Width && number == other.number && string == other.string + } + + override fun hashCode(): Int = Objects.hash(number, string) + + override fun toString(): String = + when { + number != null -> "Width{number=$number}" + string != null -> "Width{string=$string}" + _json != null -> "Width{_unknown=$_json}" + else -> throw IllegalStateException("Invalid Width") + } + + companion object { + + @JvmStatic fun ofNumber(number: Double) = Width(number = number) + + @JvmStatic fun ofString(string: String) = Width(string = string) + } + + /** An interface that defines how to map each variant of [Width] to a value of type [T]. */ + interface Visitor { + + fun visitNumber(number: Double): T + + fun visitString(string: String): T + + /** + * Maps an unknown variant of [Width] to a value of type [T]. + * + * An instance of [Width] can contain an unknown variant if it was deserialized from + * data that doesn't match any known variant. For example, if the SDK is on an older + * version than the API, then the API may respond with new variants that the SDK is + * unaware of. + * + * @throws ImageKitInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw ImageKitInvalidDataException("Unknown Width: $json") + } + } + + internal class Deserializer : BaseDeserializer(Width::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): Width { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + Width(number = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + Width(string = it, _json = json) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely incompatible with + // all the possible variants (e.g. deserializing from object). + 0 -> Width(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then use the first + // completely valid match, or simply the first match if none are completely + // valid. + else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() + } + } + } + + internal class Serializer : BaseSerializer(Width::class) { + + override fun serialize( + value: Width, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.number != null -> generator.writeObject(value.number) + value.string != null -> generator.writeObject(value.string) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid Width") + } + } + } + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is TextOverlayTransformation && + alpha == other.alpha && + background == other.background && + flip == other.flip && + fontColor == other.fontColor && + fontFamily == other.fontFamily && + fontSize == other.fontSize && + innerAlignment == other.innerAlignment && + lineHeight == other.lineHeight && + padding == other.padding && + radius == other.radius && + rotation == other.rotation && + typography == other.typography && + width == other.width && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + alpha, + background, + flip, + fontColor, + fontFamily, + fontSize, + innerAlignment, + lineHeight, + padding, + radius, + rotation, + typography, + width, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "TextOverlayTransformation{alpha=$alpha, background=$background, flip=$flip, fontColor=$fontColor, fontFamily=$fontFamily, fontSize=$fontSize, innerAlignment=$innerAlignment, lineHeight=$lineHeight, padding=$padding, radius=$radius, rotation=$rotation, typography=$typography, width=$width, additionalProperties=$additionalProperties}" +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/Transformation.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/Transformation.kt new file mode 100644 index 0000000..ee1ca86 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/Transformation.kt @@ -0,0 +1,7830 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.fasterxml.jackson.core.JsonGenerator +import com.fasterxml.jackson.core.ObjectCodec +import com.fasterxml.jackson.databind.JsonNode +import com.fasterxml.jackson.databind.SerializerProvider +import com.fasterxml.jackson.databind.annotation.JsonDeserialize +import com.fasterxml.jackson.databind.annotation.JsonSerialize +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.imagekit.api.core.BaseDeserializer +import com.imagekit.api.core.BaseSerializer +import com.imagekit.api.core.Enum +import com.imagekit.api.core.ExcludeMissing +import com.imagekit.api.core.JsonField +import com.imagekit.api.core.JsonMissing +import com.imagekit.api.core.JsonValue +import com.imagekit.api.core.allMaxBy +import com.imagekit.api.core.checkKnown +import com.imagekit.api.core.getOrThrow +import com.imagekit.api.core.toImmutable +import com.imagekit.api.errors.ImageKitInvalidDataException +import java.util.Collections +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** + * The SDK provides easy-to-use names for transformations. These names are converted to the + * corresponding transformation string before being added to the URL. SDKs are updated regularly to + * support new transformations. If you want to use a transformation that is not supported by the + * SDK, You can use the `raw` parameter to pass the transformation string directly. See the + * [Transformations documentation](https://imagekit.io/docs/transformations). + */ +class Transformation +private constructor( + private val aiChangeBackground: JsonField, + private val aiDropShadow: JsonField, + private val aiEdit: JsonField, + private val aiRemoveBackground: JsonField, + private val aiRemoveBackgroundExternal: JsonField, + private val aiRetouch: JsonField, + private val aiUpscale: JsonField, + private val aiVariation: JsonField, + private val aspectRatio: JsonField, + private val audioCodec: JsonField, + private val background: JsonField, + private val blur: JsonField, + private val border: JsonField, + private val colorProfile: JsonField, + private val contrastStretch: JsonField, + private val crop: JsonField, + private val cropMode: JsonField, + private val defaultImage: JsonField, + private val dpr: JsonField, + private val duration: JsonField, + private val endOffset: JsonField, + private val flip: JsonField, + private val focus: JsonField, + private val format: JsonField, + private val gradient: JsonField, + private val grayscale: JsonField, + private val height: JsonField, + private val lossless: JsonField, + private val metadata: JsonField, + private val named: JsonField, + private val opacity: JsonField, + private val original: JsonField, + private val overlay: JsonField, + private val page: JsonField, + private val progressive: JsonField, + private val quality: JsonField, + private val radius: JsonField, + private val raw: JsonField, + private val rotation: JsonField, + private val shadow: JsonField, + private val sharpen: JsonField, + private val startOffset: JsonField, + private val streamingResolutions: JsonField>, + private val trim: JsonField, + private val unsharpMask: JsonField, + private val videoCodec: JsonField, + private val width: JsonField, + private val x: JsonField, + private val xCenter: JsonField, + private val y: JsonField, + private val yCenter: JsonField, + private val zoom: JsonField, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("aiChangeBackground") + @ExcludeMissing + aiChangeBackground: JsonField = JsonMissing.of(), + @JsonProperty("aiDropShadow") + @ExcludeMissing + aiDropShadow: JsonField = JsonMissing.of(), + @JsonProperty("aiEdit") @ExcludeMissing aiEdit: JsonField = JsonMissing.of(), + @JsonProperty("aiRemoveBackground") + @ExcludeMissing + aiRemoveBackground: JsonField = JsonMissing.of(), + @JsonProperty("aiRemoveBackgroundExternal") + @ExcludeMissing + aiRemoveBackgroundExternal: JsonField = JsonMissing.of(), + @JsonProperty("aiRetouch") + @ExcludeMissing + aiRetouch: JsonField = JsonMissing.of(), + @JsonProperty("aiUpscale") + @ExcludeMissing + aiUpscale: JsonField = JsonMissing.of(), + @JsonProperty("aiVariation") + @ExcludeMissing + aiVariation: JsonField = JsonMissing.of(), + @JsonProperty("aspectRatio") + @ExcludeMissing + aspectRatio: JsonField = JsonMissing.of(), + @JsonProperty("audioCodec") + @ExcludeMissing + audioCodec: JsonField = JsonMissing.of(), + @JsonProperty("background") + @ExcludeMissing + background: JsonField = JsonMissing.of(), + @JsonProperty("blur") @ExcludeMissing blur: JsonField = JsonMissing.of(), + @JsonProperty("border") @ExcludeMissing border: JsonField = JsonMissing.of(), + @JsonProperty("colorProfile") + @ExcludeMissing + colorProfile: JsonField = JsonMissing.of(), + @JsonProperty("contrastStretch") + @ExcludeMissing + contrastStretch: JsonField = JsonMissing.of(), + @JsonProperty("crop") @ExcludeMissing crop: JsonField = JsonMissing.of(), + @JsonProperty("cropMode") @ExcludeMissing cropMode: JsonField = JsonMissing.of(), + @JsonProperty("defaultImage") + @ExcludeMissing + defaultImage: JsonField = JsonMissing.of(), + @JsonProperty("dpr") @ExcludeMissing dpr: JsonField = JsonMissing.of(), + @JsonProperty("duration") @ExcludeMissing duration: JsonField = JsonMissing.of(), + @JsonProperty("endOffset") + @ExcludeMissing + endOffset: JsonField = JsonMissing.of(), + @JsonProperty("flip") @ExcludeMissing flip: JsonField = JsonMissing.of(), + @JsonProperty("focus") @ExcludeMissing focus: JsonField = JsonMissing.of(), + @JsonProperty("format") @ExcludeMissing format: JsonField = JsonMissing.of(), + @JsonProperty("gradient") @ExcludeMissing gradient: JsonField = JsonMissing.of(), + @JsonProperty("grayscale") + @ExcludeMissing + grayscale: JsonField = JsonMissing.of(), + @JsonProperty("height") @ExcludeMissing height: JsonField = JsonMissing.of(), + @JsonProperty("lossless") @ExcludeMissing lossless: JsonField = JsonMissing.of(), + @JsonProperty("metadata") @ExcludeMissing metadata: JsonField = JsonMissing.of(), + @JsonProperty("named") @ExcludeMissing named: JsonField = JsonMissing.of(), + @JsonProperty("opacity") @ExcludeMissing opacity: JsonField = JsonMissing.of(), + @JsonProperty("original") @ExcludeMissing original: JsonField = JsonMissing.of(), + @JsonProperty("overlay") @ExcludeMissing overlay: JsonField = JsonMissing.of(), + @JsonProperty("page") @ExcludeMissing page: JsonField = JsonMissing.of(), + @JsonProperty("progressive") + @ExcludeMissing + progressive: JsonField = JsonMissing.of(), + @JsonProperty("quality") @ExcludeMissing quality: JsonField = JsonMissing.of(), + @JsonProperty("radius") @ExcludeMissing radius: JsonField = JsonMissing.of(), + @JsonProperty("raw") @ExcludeMissing raw: JsonField = JsonMissing.of(), + @JsonProperty("rotation") @ExcludeMissing rotation: JsonField = JsonMissing.of(), + @JsonProperty("shadow") @ExcludeMissing shadow: JsonField = JsonMissing.of(), + @JsonProperty("sharpen") @ExcludeMissing sharpen: JsonField = JsonMissing.of(), + @JsonProperty("startOffset") + @ExcludeMissing + startOffset: JsonField = JsonMissing.of(), + @JsonProperty("streamingResolutions") + @ExcludeMissing + streamingResolutions: JsonField> = JsonMissing.of(), + @JsonProperty("trim") @ExcludeMissing trim: JsonField = JsonMissing.of(), + @JsonProperty("unsharpMask") + @ExcludeMissing + unsharpMask: JsonField = JsonMissing.of(), + @JsonProperty("videoCodec") + @ExcludeMissing + videoCodec: JsonField = JsonMissing.of(), + @JsonProperty("width") @ExcludeMissing width: JsonField = JsonMissing.of(), + @JsonProperty("x") @ExcludeMissing x: JsonField = JsonMissing.of(), + @JsonProperty("xCenter") @ExcludeMissing xCenter: JsonField = JsonMissing.of(), + @JsonProperty("y") @ExcludeMissing y: JsonField = JsonMissing.of(), + @JsonProperty("yCenter") @ExcludeMissing yCenter: JsonField = JsonMissing.of(), + @JsonProperty("zoom") @ExcludeMissing zoom: JsonField = JsonMissing.of(), + ) : this( + aiChangeBackground, + aiDropShadow, + aiEdit, + aiRemoveBackground, + aiRemoveBackgroundExternal, + aiRetouch, + aiUpscale, + aiVariation, + aspectRatio, + audioCodec, + background, + blur, + border, + colorProfile, + contrastStretch, + crop, + cropMode, + defaultImage, + dpr, + duration, + endOffset, + flip, + focus, + format, + gradient, + grayscale, + height, + lossless, + metadata, + named, + opacity, + original, + overlay, + page, + progressive, + quality, + radius, + raw, + rotation, + shadow, + sharpen, + startOffset, + streamingResolutions, + trim, + unsharpMask, + videoCodec, + width, + x, + xCenter, + y, + yCenter, + zoom, + mutableMapOf(), + ) + + /** + * Uses AI to change the background. Provide a text prompt or a base64-encoded prompt, e.g., + * `prompt-snow road` or `prompte-[urlencoded_base64_encoded_text]`. Not supported inside + * overlay. See + * [AI Change Background](https://imagekit.io/docs/ai-transformations#change-background-e-changebg). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun aiChangeBackground(): Optional = + aiChangeBackground.getOptional("aiChangeBackground") + + /** + * Adds an AI-based drop shadow around a foreground object on a transparent or removed + * background. Optionally, control the direction, elevation, and saturation of the light source + * (e.g., `az-45` to change light direction). Pass `true` for the default drop shadow, or + * provide a string for a custom drop shadow. Supported inside overlay. See + * [AI Drop Shadow](https://imagekit.io/docs/ai-transformations#ai-drop-shadow-e-dropshadow). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun aiDropShadow(): Optional = aiDropShadow.getOptional("aiDropShadow") + + /** + * Uses AI to edit images based on a text prompt. Provide a text prompt or a base64-encoded + * prompt, e.g., `prompt-snow road` or `prompte-[urlencoded_base64_encoded_text]`. Not supported + * inside overlay. See [AI Edit](https://imagekit.io/docs/ai-transformations#edit-image-e-edit). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun aiEdit(): Optional = aiEdit.getOptional("aiEdit") + + /** + * Applies ImageKit's in-house background removal. Supported inside overlay. See + * [AI Background Removal](https://imagekit.io/docs/ai-transformations#imagekit-background-removal-e-bgremove). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun aiRemoveBackground(): Optional = + aiRemoveBackground.getOptional("aiRemoveBackground") + + /** + * Uses third-party background removal. Note: It is recommended to use aiRemoveBackground, + * ImageKit's in-house solution, which is more cost-effective. Supported inside overlay. See + * [External Background Removal](https://imagekit.io/docs/ai-transformations#background-removal-e-removedotbg). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun aiRemoveBackgroundExternal(): Optional = + aiRemoveBackgroundExternal.getOptional("aiRemoveBackgroundExternal") + + /** + * Performs AI-based retouching to improve faces or product shots. Not supported inside overlay. + * See [AI Retouch](https://imagekit.io/docs/ai-transformations#retouch-e-retouch). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun aiRetouch(): Optional = aiRetouch.getOptional("aiRetouch") + + /** + * Upscales images beyond their original dimensions using AI. Not supported inside overlay. See + * [AI Upscale](https://imagekit.io/docs/ai-transformations#upscale-e-upscale). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun aiUpscale(): Optional = aiUpscale.getOptional("aiUpscale") + + /** + * Generates a variation of an image using AI. This produces a new image with slight variations + * from the original, such as changes in color, texture, and other visual elements, while + * preserving the structure and essence of the original image. Not supported inside overlay. See + * [AI Generate Variations](https://imagekit.io/docs/ai-transformations#generate-variations-of-an-image-e-genvar). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun aiVariation(): Optional = aiVariation.getOptional("aiVariation") + + /** + * Specifies the aspect ratio for the output, e.g., "ar-4-3". Typically used with either width + * or height (but not both). For example: aspectRatio = `4:3`, `4_3`, or an expression like + * `iar_div_2`. See + * [Image resize and crop – Aspect ratio](https://imagekit.io/docs/image-resize-and-crop#aspect-ratio---ar). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun aspectRatio(): Optional = aspectRatio.getOptional("aspectRatio") + + /** + * Specifies the audio codec, e.g., `aac`, `opus`, or `none`. See + * [Audio codec](https://imagekit.io/docs/video-optimization#audio-codec---ac). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun audioCodec(): Optional = audioCodec.getOptional("audioCodec") + + /** + * Specifies the background to be used in conjunction with certain cropping strategies when + * resizing an image. + * - A solid color: e.g., `red`, `F3F3F3`, `AAFF0010`. See + * [Solid color background](https://imagekit.io/docs/effects-and-enhancements#solid-color-background). + * - A blurred background: e.g., `blurred`, `blurred_25_N15`, etc. See + * [Blurred background](https://imagekit.io/docs/effects-and-enhancements#blurred-background). + * - Expand the image boundaries using generative fill: `genfill`. Not supported inside overlay. + * Optionally, control the background scene by passing a text prompt: + * `genfill[:-prompt-${text}]` or `genfill[:-prompte-${urlencoded_base64_encoded_text}]`. See + * [Generative fill background](https://imagekit.io/docs/ai-transformations#generative-fill-bg-genfill). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun background(): Optional = background.getOptional("background") + + /** + * Specifies the Gaussian blur level. Accepts an integer value between 1 and 100, or an + * expression like `bl-10`. See + * [Blur](https://imagekit.io/docs/effects-and-enhancements#blur---bl). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun blur(): Optional = blur.getOptional("blur") + + /** + * Adds a border to the output media. Accepts a string in the format `_` + * (e.g., `5_FFF000` for a 5px yellow border), or an expression like `ih_div_20_FF00FF`. See + * [Border](https://imagekit.io/docs/effects-and-enhancements#border---b). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun border(): Optional = border.getOptional("border") + + /** + * Indicates whether the output image should retain the original color profile. See + * [Color profile](https://imagekit.io/docs/image-optimization#color-profile---cp). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun colorProfile(): Optional = colorProfile.getOptional("colorProfile") + + /** + * Automatically enhances the contrast of an image (contrast stretch). See + * [Contrast Stretch](https://imagekit.io/docs/effects-and-enhancements#contrast-stretch---e-contrast). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun contrastStretch(): Optional = + contrastStretch.getOptional("contrastStretch") + + /** + * Crop modes for image resizing. See + * [Crop modes & focus](https://imagekit.io/docs/image-resize-and-crop#crop-crop-modes--focus). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun crop(): Optional = crop.getOptional("crop") + + /** + * Additional crop modes for image resizing. See + * [Crop modes & focus](https://imagekit.io/docs/image-resize-and-crop#crop-crop-modes--focus). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun cropMode(): Optional = cropMode.getOptional("cropMode") + + /** + * Specifies a fallback image if the resource is not found, e.g., a URL or file path. See + * [Default image](https://imagekit.io/docs/image-transformation#default-image---di). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun defaultImage(): Optional = defaultImage.getOptional("defaultImage") + + /** + * Accepts values between 0.1 and 5, or `auto` for automatic device pixel ratio (DPR) + * calculation. See [DPR](https://imagekit.io/docs/image-resize-and-crop#dpr---dpr). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun dpr(): Optional = dpr.getOptional("dpr") + + /** + * Specifies the duration (in seconds) for trimming videos, e.g., `5` or `10.5`. Typically used + * with startOffset to indicate the length from the start offset. Arithmetic expressions are + * supported. See [Trim videos – Duration](https://imagekit.io/docs/trim-videos#duration---du). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun duration(): Optional = duration.getOptional("duration") + + /** + * Specifies the end offset (in seconds) for trimming videos, e.g., `5` or `10.5`. Typically + * used with startOffset to define a time window. Arithmetic expressions are supported. See + * [Trim videos – End offset](https://imagekit.io/docs/trim-videos#end-offset---eo). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun endOffset(): Optional = endOffset.getOptional("endOffset") + + /** + * Flips or mirrors an image either horizontally, vertically, or both. Acceptable values: `h` + * (horizontal), `v` (vertical), `h_v` (horizontal and vertical), or `v_h`. See + * [Flip](https://imagekit.io/docs/effects-and-enhancements#flip---fl). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun flip(): Optional = flip.getOptional("flip") + + /** + * Refines padding and cropping behavior for pad resize, maintain ratio, and extract crop modes. + * Supports manual positions and coordinate-based focus. With AI-based cropping, you can + * automatically keep key subjects in frame—such as faces or detected objects (e.g., `fo-face`, + * `fo-person`, `fo-car`)— while resizing. + * - See [Focus](https://imagekit.io/docs/image-resize-and-crop#focus---fo). + * - [Object aware + * cropping](https://imagekit.io/docs/image-resize-and-crop#object-aware-cropping---fo-object-name) + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun focus(): Optional = focus.getOptional("focus") + + /** + * Specifies the output format for images or videos, e.g., `jpg`, `png`, `webp`, `mp4`, or + * `auto`. You can also pass `orig` for images to return the original format. ImageKit + * automatically delivers images and videos in the optimal format based on device support unless + * overridden by the dashboard settings or the format parameter. See + * [Image format](https://imagekit.io/docs/image-optimization#format---f) and + * [Video format](https://imagekit.io/docs/video-optimization#format---f). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun format(): Optional = format.getOptional("format") + + /** + * Creates a linear gradient with two colors. Pass `true` for a default gradient, or provide a + * string for a custom gradient. See + * [Gradient](https://imagekit.io/docs/effects-and-enhancements#gradient---e-gradient). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun gradient(): Optional = gradient.getOptional("gradient") + + /** + * Enables a grayscale effect for images. See + * [Grayscale](https://imagekit.io/docs/effects-and-enhancements#grayscale---e-grayscale). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun grayscale(): Optional = grayscale.getOptional("grayscale") + + /** + * Specifies the height of the output. If a value between 0 and 1 is provided, it is treated as + * a percentage (e.g., `0.5` represents 50% of the original height). You can also supply + * arithmetic expressions (e.g., `ih_mul_0.5`). Height transformation – + * [Images](https://imagekit.io/docs/image-resize-and-crop#height---h) · + * [Videos](https://imagekit.io/docs/video-resize-and-crop#height---h) + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun height(): Optional = height.getOptional("height") + + /** + * Specifies whether the output image (in JPEG or PNG) should be compressed losslessly. See + * [Lossless compression](https://imagekit.io/docs/image-optimization#lossless-webp-and-png---lo). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun lossless(): Optional = lossless.getOptional("lossless") + + /** + * By default, ImageKit removes all metadata during automatic image compression. Set this to + * true to preserve metadata. See + * [Image metadata](https://imagekit.io/docs/image-optimization#image-metadata---md). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun metadata(): Optional = metadata.getOptional("metadata") + + /** + * Named transformation reference. See + * [Named transformations](https://imagekit.io/docs/transformations#named-transformations). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun named(): Optional = named.getOptional("named") + + /** + * Specifies the opacity level of the output image. See + * [Opacity](https://imagekit.io/docs/effects-and-enhancements#opacity---o). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun opacity(): Optional = opacity.getOptional("opacity") + + /** + * If set to true, serves the original file without applying any transformations. See + * [Deliver original file as-is](https://imagekit.io/docs/core-delivery-features#deliver-original-file-as-is---orig-true). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun original(): Optional = original.getOptional("original") + + /** + * Specifies an overlay to be applied on the parent image or video. ImageKit supports overlays + * including images, text, videos, subtitles, and solid colors. See + * [Overlay using layers](https://imagekit.io/docs/transformations#overlay-using-layers). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun overlay(): Optional = overlay.getOptional("overlay") + + /** + * Extracts a specific page or frame from multi-page or layered files (PDF, PSD, AI). For + * example, specify by number (e.g., `2`), a range (e.g., `3-4` for the 2nd and 3rd layers), or + * by name (e.g., `name-layer-4` for a PSD layer). See + * [Thumbnail extraction](https://imagekit.io/docs/vector-and-animated-images#get-thumbnail-from-psd-pdf-ai-eps-and-animated-files). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun page(): Optional = page.getOptional("page") + + /** + * Specifies whether the output JPEG image should be rendered progressively. Progressive loading + * begins with a low-quality, pixelated version of the full image, which gradually improves to + * provide a faster perceived load time. See + * [Progressive images](https://imagekit.io/docs/image-optimization#progressive-image---pr). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun progressive(): Optional = progressive.getOptional("progressive") + + /** + * Specifies the quality of the output image for lossy formats such as JPEG, WebP, and AVIF. A + * higher quality value results in a larger file size with better quality, while a lower value + * produces a smaller file size with reduced quality. See + * [Quality](https://imagekit.io/docs/image-optimization#quality---q). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun quality(): Optional = quality.getOptional("quality") + + /** + * Specifies the corner radius for rounded corners (e.g., 20) or `max` for circular or oval + * shape. See [Radius](https://imagekit.io/docs/effects-and-enhancements#radius---r). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun radius(): Optional = radius.getOptional("radius") + + /** + * Pass any transformation not directly supported by the SDK. This transformation string is + * appended to the URL as provided. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun raw(): Optional = raw.getOptional("raw") + + /** + * Specifies the rotation angle in degrees. Positive values rotate the image clockwise; you can + * also use, for example, `N40` for counterclockwise rotation or `auto` to use the orientation + * specified in the image's EXIF data. For videos, only the following values are supported: 0, + * 90, 180, 270, or 360. See + * [Rotate](https://imagekit.io/docs/effects-and-enhancements#rotate---rt). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun rotation(): Optional = rotation.getOptional("rotation") + + /** + * Adds a shadow beneath solid objects in an image with a transparent background. For AI-based + * drop shadows, refer to aiDropShadow. Pass `true` for a default shadow, or provide a string + * for a custom shadow. See + * [Shadow](https://imagekit.io/docs/effects-and-enhancements#shadow---e-shadow). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun shadow(): Optional = shadow.getOptional("shadow") + + /** + * Sharpens the input image, highlighting edges and finer details. Pass `true` for default + * sharpening, or provide a numeric value for custom sharpening. See + * [Sharpen](https://imagekit.io/docs/effects-and-enhancements#sharpen---e-sharpen). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun sharpen(): Optional = sharpen.getOptional("sharpen") + + /** + * Specifies the start offset (in seconds) for trimming videos, e.g., `5` or `10.5`. Arithmetic + * expressions are also supported. See + * [Trim videos – Start offset](https://imagekit.io/docs/trim-videos#start-offset---so). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun startOffset(): Optional = startOffset.getOptional("startOffset") + + /** + * An array of resolutions for adaptive bitrate streaming, e.g., + * [`240`, `360`, `480`, `720`, `1080`]. See + * [Adaptive Bitrate Streaming](https://imagekit.io/docs/adaptive-bitrate-streaming). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun streamingResolutions(): Optional> = + streamingResolutions.getOptional("streamingResolutions") + + /** + * Useful for images with a solid or nearly solid background and a central object. This + * parameter trims the background, leaving only the central object in the output image. See + * [Trim edges](https://imagekit.io/docs/effects-and-enhancements#trim-edges---t). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun trim(): Optional = trim.getOptional("trim") + + /** + * Applies Unsharp Masking (USM), an image sharpening technique. Pass `true` for a default + * unsharp mask, or provide a string for a custom unsharp mask. See + * [Unsharp Mask](https://imagekit.io/docs/effects-and-enhancements#unsharp-mask---e-usm). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun unsharpMask(): Optional = unsharpMask.getOptional("unsharpMask") + + /** + * Specifies the video codec, e.g., `h264`, `vp9`, `av1`, or `none`. See + * [Video codec](https://imagekit.io/docs/video-optimization#video-codec---vc). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun videoCodec(): Optional = videoCodec.getOptional("videoCodec") + + /** + * Specifies the width of the output. If a value between 0 and 1 is provided, it is treated as a + * percentage (e.g., `0.4` represents 40% of the original width). You can also supply arithmetic + * expressions (e.g., `iw_div_2`). Width transformation – + * [Images](https://imagekit.io/docs/image-resize-and-crop#width---w) · + * [Videos](https://imagekit.io/docs/video-resize-and-crop#width---w) + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun width(): Optional = width.getOptional("width") + + /** + * Focus using cropped image coordinates - X coordinate. See + * [Focus using cropped coordinates](https://imagekit.io/docs/image-resize-and-crop#example---focus-using-cropped-image-coordinates). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun x(): Optional = x.getOptional("x") + + /** + * Focus using cropped image coordinates - X center coordinate. See + * [Focus using cropped coordinates](https://imagekit.io/docs/image-resize-and-crop#example---focus-using-cropped-image-coordinates). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun xCenter(): Optional = xCenter.getOptional("xCenter") + + /** + * Focus using cropped image coordinates - Y coordinate. See + * [Focus using cropped coordinates](https://imagekit.io/docs/image-resize-and-crop#example---focus-using-cropped-image-coordinates). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun y(): Optional = y.getOptional("y") + + /** + * Focus using cropped image coordinates - Y center coordinate. See + * [Focus using cropped coordinates](https://imagekit.io/docs/image-resize-and-crop#example---focus-using-cropped-image-coordinates). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun yCenter(): Optional = yCenter.getOptional("yCenter") + + /** + * Accepts a numeric value that determines how much to zoom in or out of the cropped area. It + * should be used in conjunction with fo-face or fo-. See + * [Zoom](https://imagekit.io/docs/image-resize-and-crop#zoom---z). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun zoom(): Optional = zoom.getOptional("zoom") + + /** + * Returns the raw JSON value of [aiChangeBackground]. + * + * Unlike [aiChangeBackground], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("aiChangeBackground") + @ExcludeMissing + fun _aiChangeBackground(): JsonField = aiChangeBackground + + /** + * Returns the raw JSON value of [aiDropShadow]. + * + * Unlike [aiDropShadow], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("aiDropShadow") + @ExcludeMissing + fun _aiDropShadow(): JsonField = aiDropShadow + + /** + * Returns the raw JSON value of [aiEdit]. + * + * Unlike [aiEdit], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("aiEdit") @ExcludeMissing fun _aiEdit(): JsonField = aiEdit + + /** + * Returns the raw JSON value of [aiRemoveBackground]. + * + * Unlike [aiRemoveBackground], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("aiRemoveBackground") + @ExcludeMissing + fun _aiRemoveBackground(): JsonField = aiRemoveBackground + + /** + * Returns the raw JSON value of [aiRemoveBackgroundExternal]. + * + * Unlike [aiRemoveBackgroundExternal], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("aiRemoveBackgroundExternal") + @ExcludeMissing + fun _aiRemoveBackgroundExternal(): JsonField = + aiRemoveBackgroundExternal + + /** + * Returns the raw JSON value of [aiRetouch]. + * + * Unlike [aiRetouch], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("aiRetouch") @ExcludeMissing fun _aiRetouch(): JsonField = aiRetouch + + /** + * Returns the raw JSON value of [aiUpscale]. + * + * Unlike [aiUpscale], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("aiUpscale") @ExcludeMissing fun _aiUpscale(): JsonField = aiUpscale + + /** + * Returns the raw JSON value of [aiVariation]. + * + * Unlike [aiVariation], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("aiVariation") + @ExcludeMissing + fun _aiVariation(): JsonField = aiVariation + + /** + * Returns the raw JSON value of [aspectRatio]. + * + * Unlike [aspectRatio], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("aspectRatio") + @ExcludeMissing + fun _aspectRatio(): JsonField = aspectRatio + + /** + * Returns the raw JSON value of [audioCodec]. + * + * Unlike [audioCodec], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("audioCodec") + @ExcludeMissing + fun _audioCodec(): JsonField = audioCodec + + /** + * Returns the raw JSON value of [background]. + * + * Unlike [background], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("background") @ExcludeMissing fun _background(): JsonField = background + + /** + * Returns the raw JSON value of [blur]. + * + * Unlike [blur], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("blur") @ExcludeMissing fun _blur(): JsonField = blur + + /** + * Returns the raw JSON value of [border]. + * + * Unlike [border], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("border") @ExcludeMissing fun _border(): JsonField = border + + /** + * Returns the raw JSON value of [colorProfile]. + * + * Unlike [colorProfile], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("colorProfile") + @ExcludeMissing + fun _colorProfile(): JsonField = colorProfile + + /** + * Returns the raw JSON value of [contrastStretch]. + * + * Unlike [contrastStretch], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("contrastStretch") + @ExcludeMissing + fun _contrastStretch(): JsonField = contrastStretch + + /** + * Returns the raw JSON value of [crop]. + * + * Unlike [crop], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("crop") @ExcludeMissing fun _crop(): JsonField = crop + + /** + * Returns the raw JSON value of [cropMode]. + * + * Unlike [cropMode], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("cropMode") @ExcludeMissing fun _cropMode(): JsonField = cropMode + + /** + * Returns the raw JSON value of [defaultImage]. + * + * Unlike [defaultImage], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("defaultImage") + @ExcludeMissing + fun _defaultImage(): JsonField = defaultImage + + /** + * Returns the raw JSON value of [dpr]. + * + * Unlike [dpr], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("dpr") @ExcludeMissing fun _dpr(): JsonField = dpr + + /** + * Returns the raw JSON value of [duration]. + * + * Unlike [duration], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("duration") @ExcludeMissing fun _duration(): JsonField = duration + + /** + * Returns the raw JSON value of [endOffset]. + * + * Unlike [endOffset], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("endOffset") @ExcludeMissing fun _endOffset(): JsonField = endOffset + + /** + * Returns the raw JSON value of [flip]. + * + * Unlike [flip], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("flip") @ExcludeMissing fun _flip(): JsonField = flip + + /** + * Returns the raw JSON value of [focus]. + * + * Unlike [focus], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("focus") @ExcludeMissing fun _focus(): JsonField = focus + + /** + * Returns the raw JSON value of [format]. + * + * Unlike [format], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("format") @ExcludeMissing fun _format(): JsonField = format + + /** + * Returns the raw JSON value of [gradient]. + * + * Unlike [gradient], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("gradient") @ExcludeMissing fun _gradient(): JsonField = gradient + + /** + * Returns the raw JSON value of [grayscale]. + * + * Unlike [grayscale], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("grayscale") @ExcludeMissing fun _grayscale(): JsonField = grayscale + + /** + * Returns the raw JSON value of [height]. + * + * Unlike [height], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("height") @ExcludeMissing fun _height(): JsonField = height + + /** + * Returns the raw JSON value of [lossless]. + * + * Unlike [lossless], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("lossless") @ExcludeMissing fun _lossless(): JsonField = lossless + + /** + * Returns the raw JSON value of [metadata]. + * + * Unlike [metadata], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("metadata") @ExcludeMissing fun _metadata(): JsonField = metadata + + /** + * Returns the raw JSON value of [named]. + * + * Unlike [named], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("named") @ExcludeMissing fun _named(): JsonField = named + + /** + * Returns the raw JSON value of [opacity]. + * + * Unlike [opacity], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("opacity") @ExcludeMissing fun _opacity(): JsonField = opacity + + /** + * Returns the raw JSON value of [original]. + * + * Unlike [original], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("original") @ExcludeMissing fun _original(): JsonField = original + + /** + * Returns the raw JSON value of [overlay]. + * + * Unlike [overlay], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("overlay") @ExcludeMissing fun _overlay(): JsonField = overlay + + /** + * Returns the raw JSON value of [page]. + * + * Unlike [page], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("page") @ExcludeMissing fun _page(): JsonField = page + + /** + * Returns the raw JSON value of [progressive]. + * + * Unlike [progressive], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("progressive") + @ExcludeMissing + fun _progressive(): JsonField = progressive + + /** + * Returns the raw JSON value of [quality]. + * + * Unlike [quality], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("quality") @ExcludeMissing fun _quality(): JsonField = quality + + /** + * Returns the raw JSON value of [radius]. + * + * Unlike [radius], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("radius") @ExcludeMissing fun _radius(): JsonField = radius + + /** + * Returns the raw JSON value of [raw]. + * + * Unlike [raw], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("raw") @ExcludeMissing fun _raw(): JsonField = raw + + /** + * Returns the raw JSON value of [rotation]. + * + * Unlike [rotation], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("rotation") @ExcludeMissing fun _rotation(): JsonField = rotation + + /** + * Returns the raw JSON value of [shadow]. + * + * Unlike [shadow], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("shadow") @ExcludeMissing fun _shadow(): JsonField = shadow + + /** + * Returns the raw JSON value of [sharpen]. + * + * Unlike [sharpen], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("sharpen") @ExcludeMissing fun _sharpen(): JsonField = sharpen + + /** + * Returns the raw JSON value of [startOffset]. + * + * Unlike [startOffset], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("startOffset") + @ExcludeMissing + fun _startOffset(): JsonField = startOffset + + /** + * Returns the raw JSON value of [streamingResolutions]. + * + * Unlike [streamingResolutions], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("streamingResolutions") + @ExcludeMissing + fun _streamingResolutions(): JsonField> = streamingResolutions + + /** + * Returns the raw JSON value of [trim]. + * + * Unlike [trim], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("trim") @ExcludeMissing fun _trim(): JsonField = trim + + /** + * Returns the raw JSON value of [unsharpMask]. + * + * Unlike [unsharpMask], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("unsharpMask") + @ExcludeMissing + fun _unsharpMask(): JsonField = unsharpMask + + /** + * Returns the raw JSON value of [videoCodec]. + * + * Unlike [videoCodec], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("videoCodec") + @ExcludeMissing + fun _videoCodec(): JsonField = videoCodec + + /** + * Returns the raw JSON value of [width]. + * + * Unlike [width], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("width") @ExcludeMissing fun _width(): JsonField = width + + /** + * Returns the raw JSON value of [x]. + * + * Unlike [x], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("x") @ExcludeMissing fun _x(): JsonField = x + + /** + * Returns the raw JSON value of [xCenter]. + * + * Unlike [xCenter], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("xCenter") @ExcludeMissing fun _xCenter(): JsonField = xCenter + + /** + * Returns the raw JSON value of [y]. + * + * Unlike [y], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("y") @ExcludeMissing fun _y(): JsonField = y + + /** + * Returns the raw JSON value of [yCenter]. + * + * Unlike [yCenter], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("yCenter") @ExcludeMissing fun _yCenter(): JsonField = yCenter + + /** + * Returns the raw JSON value of [zoom]. + * + * Unlike [zoom], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("zoom") @ExcludeMissing fun _zoom(): JsonField = zoom + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Transformation]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Transformation]. */ + class Builder internal constructor() { + + private var aiChangeBackground: JsonField = JsonMissing.of() + private var aiDropShadow: JsonField = JsonMissing.of() + private var aiEdit: JsonField = JsonMissing.of() + private var aiRemoveBackground: JsonField = JsonMissing.of() + private var aiRemoveBackgroundExternal: JsonField = + JsonMissing.of() + private var aiRetouch: JsonField = JsonMissing.of() + private var aiUpscale: JsonField = JsonMissing.of() + private var aiVariation: JsonField = JsonMissing.of() + private var aspectRatio: JsonField = JsonMissing.of() + private var audioCodec: JsonField = JsonMissing.of() + private var background: JsonField = JsonMissing.of() + private var blur: JsonField = JsonMissing.of() + private var border: JsonField = JsonMissing.of() + private var colorProfile: JsonField = JsonMissing.of() + private var contrastStretch: JsonField = JsonMissing.of() + private var crop: JsonField = JsonMissing.of() + private var cropMode: JsonField = JsonMissing.of() + private var defaultImage: JsonField = JsonMissing.of() + private var dpr: JsonField = JsonMissing.of() + private var duration: JsonField = JsonMissing.of() + private var endOffset: JsonField = JsonMissing.of() + private var flip: JsonField = JsonMissing.of() + private var focus: JsonField = JsonMissing.of() + private var format: JsonField = JsonMissing.of() + private var gradient: JsonField = JsonMissing.of() + private var grayscale: JsonField = JsonMissing.of() + private var height: JsonField = JsonMissing.of() + private var lossless: JsonField = JsonMissing.of() + private var metadata: JsonField = JsonMissing.of() + private var named: JsonField = JsonMissing.of() + private var opacity: JsonField = JsonMissing.of() + private var original: JsonField = JsonMissing.of() + private var overlay: JsonField = JsonMissing.of() + private var page: JsonField = JsonMissing.of() + private var progressive: JsonField = JsonMissing.of() + private var quality: JsonField = JsonMissing.of() + private var radius: JsonField = JsonMissing.of() + private var raw: JsonField = JsonMissing.of() + private var rotation: JsonField = JsonMissing.of() + private var shadow: JsonField = JsonMissing.of() + private var sharpen: JsonField = JsonMissing.of() + private var startOffset: JsonField = JsonMissing.of() + private var streamingResolutions: JsonField>? = null + private var trim: JsonField = JsonMissing.of() + private var unsharpMask: JsonField = JsonMissing.of() + private var videoCodec: JsonField = JsonMissing.of() + private var width: JsonField = JsonMissing.of() + private var x: JsonField = JsonMissing.of() + private var xCenter: JsonField = JsonMissing.of() + private var y: JsonField = JsonMissing.of() + private var yCenter: JsonField = JsonMissing.of() + private var zoom: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(transformation: Transformation) = apply { + aiChangeBackground = transformation.aiChangeBackground + aiDropShadow = transformation.aiDropShadow + aiEdit = transformation.aiEdit + aiRemoveBackground = transformation.aiRemoveBackground + aiRemoveBackgroundExternal = transformation.aiRemoveBackgroundExternal + aiRetouch = transformation.aiRetouch + aiUpscale = transformation.aiUpscale + aiVariation = transformation.aiVariation + aspectRatio = transformation.aspectRatio + audioCodec = transformation.audioCodec + background = transformation.background + blur = transformation.blur + border = transformation.border + colorProfile = transformation.colorProfile + contrastStretch = transformation.contrastStretch + crop = transformation.crop + cropMode = transformation.cropMode + defaultImage = transformation.defaultImage + dpr = transformation.dpr + duration = transformation.duration + endOffset = transformation.endOffset + flip = transformation.flip + focus = transformation.focus + format = transformation.format + gradient = transformation.gradient + grayscale = transformation.grayscale + height = transformation.height + lossless = transformation.lossless + metadata = transformation.metadata + named = transformation.named + opacity = transformation.opacity + original = transformation.original + overlay = transformation.overlay + page = transformation.page + progressive = transformation.progressive + quality = transformation.quality + radius = transformation.radius + raw = transformation.raw + rotation = transformation.rotation + shadow = transformation.shadow + sharpen = transformation.sharpen + startOffset = transformation.startOffset + streamingResolutions = transformation.streamingResolutions.map { it.toMutableList() } + trim = transformation.trim + unsharpMask = transformation.unsharpMask + videoCodec = transformation.videoCodec + width = transformation.width + x = transformation.x + xCenter = transformation.xCenter + y = transformation.y + yCenter = transformation.yCenter + zoom = transformation.zoom + additionalProperties = transformation.additionalProperties.toMutableMap() + } + + /** + * Uses AI to change the background. Provide a text prompt or a base64-encoded prompt, e.g., + * `prompt-snow road` or `prompte-[urlencoded_base64_encoded_text]`. Not supported inside + * overlay. See + * [AI Change Background](https://imagekit.io/docs/ai-transformations#change-background-e-changebg). + */ + fun aiChangeBackground(aiChangeBackground: String) = + aiChangeBackground(JsonField.of(aiChangeBackground)) + + /** + * Sets [Builder.aiChangeBackground] to an arbitrary JSON value. + * + * You should usually call [Builder.aiChangeBackground] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun aiChangeBackground(aiChangeBackground: JsonField) = apply { + this.aiChangeBackground = aiChangeBackground + } + + /** + * Adds an AI-based drop shadow around a foreground object on a transparent or removed + * background. Optionally, control the direction, elevation, and saturation of the light + * source (e.g., `az-45` to change light direction). Pass `true` for the default drop + * shadow, or provide a string for a custom drop shadow. Supported inside overlay. See + * [AI Drop Shadow](https://imagekit.io/docs/ai-transformations#ai-drop-shadow-e-dropshadow). + */ + fun aiDropShadow(aiDropShadow: AiDropShadow) = aiDropShadow(JsonField.of(aiDropShadow)) + + /** + * Sets [Builder.aiDropShadow] to an arbitrary JSON value. + * + * You should usually call [Builder.aiDropShadow] with a well-typed [AiDropShadow] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun aiDropShadow(aiDropShadow: JsonField) = apply { + this.aiDropShadow = aiDropShadow + } + + /** Alias for calling [aiDropShadow] with `AiDropShadow.ofTrue()`. */ + fun aiDropShadowTrue() = aiDropShadow(AiDropShadow.ofTrue()) + + /** Alias for calling [aiDropShadow] with `AiDropShadow.ofString(string)`. */ + fun aiDropShadow(string: String) = aiDropShadow(AiDropShadow.ofString(string)) + + /** + * Uses AI to edit images based on a text prompt. Provide a text prompt or a base64-encoded + * prompt, e.g., `prompt-snow road` or `prompte-[urlencoded_base64_encoded_text]`. Not + * supported inside overlay. See + * [AI Edit](https://imagekit.io/docs/ai-transformations#edit-image-e-edit). + */ + fun aiEdit(aiEdit: String) = aiEdit(JsonField.of(aiEdit)) + + /** + * Sets [Builder.aiEdit] to an arbitrary JSON value. + * + * You should usually call [Builder.aiEdit] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun aiEdit(aiEdit: JsonField) = apply { this.aiEdit = aiEdit } + + /** + * Applies ImageKit's in-house background removal. Supported inside overlay. See + * [AI Background Removal](https://imagekit.io/docs/ai-transformations#imagekit-background-removal-e-bgremove). + */ + fun aiRemoveBackground(aiRemoveBackground: AiRemoveBackground) = + aiRemoveBackground(JsonField.of(aiRemoveBackground)) + + /** + * Sets [Builder.aiRemoveBackground] to an arbitrary JSON value. + * + * You should usually call [Builder.aiRemoveBackground] with a well-typed + * [AiRemoveBackground] value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun aiRemoveBackground(aiRemoveBackground: JsonField) = apply { + this.aiRemoveBackground = aiRemoveBackground + } + + /** + * Uses third-party background removal. Note: It is recommended to use aiRemoveBackground, + * ImageKit's in-house solution, which is more cost-effective. Supported inside overlay. See + * [External Background Removal](https://imagekit.io/docs/ai-transformations#background-removal-e-removedotbg). + */ + fun aiRemoveBackgroundExternal(aiRemoveBackgroundExternal: AiRemoveBackgroundExternal) = + aiRemoveBackgroundExternal(JsonField.of(aiRemoveBackgroundExternal)) + + /** + * Sets [Builder.aiRemoveBackgroundExternal] to an arbitrary JSON value. + * + * You should usually call [Builder.aiRemoveBackgroundExternal] with a well-typed + * [AiRemoveBackgroundExternal] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ + fun aiRemoveBackgroundExternal( + aiRemoveBackgroundExternal: JsonField + ) = apply { this.aiRemoveBackgroundExternal = aiRemoveBackgroundExternal } + + /** + * Performs AI-based retouching to improve faces or product shots. Not supported inside + * overlay. See [AI Retouch](https://imagekit.io/docs/ai-transformations#retouch-e-retouch). + */ + fun aiRetouch(aiRetouch: AiRetouch) = aiRetouch(JsonField.of(aiRetouch)) + + /** + * Sets [Builder.aiRetouch] to an arbitrary JSON value. + * + * You should usually call [Builder.aiRetouch] with a well-typed [AiRetouch] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun aiRetouch(aiRetouch: JsonField) = apply { this.aiRetouch = aiRetouch } + + /** + * Upscales images beyond their original dimensions using AI. Not supported inside overlay. + * See [AI Upscale](https://imagekit.io/docs/ai-transformations#upscale-e-upscale). + */ + fun aiUpscale(aiUpscale: AiUpscale) = aiUpscale(JsonField.of(aiUpscale)) + + /** + * Sets [Builder.aiUpscale] to an arbitrary JSON value. + * + * You should usually call [Builder.aiUpscale] with a well-typed [AiUpscale] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun aiUpscale(aiUpscale: JsonField) = apply { this.aiUpscale = aiUpscale } + + /** + * Generates a variation of an image using AI. This produces a new image with slight + * variations from the original, such as changes in color, texture, and other visual + * elements, while preserving the structure and essence of the original image. Not supported + * inside overlay. See + * [AI Generate Variations](https://imagekit.io/docs/ai-transformations#generate-variations-of-an-image-e-genvar). + */ + fun aiVariation(aiVariation: AiVariation) = aiVariation(JsonField.of(aiVariation)) + + /** + * Sets [Builder.aiVariation] to an arbitrary JSON value. + * + * You should usually call [Builder.aiVariation] with a well-typed [AiVariation] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun aiVariation(aiVariation: JsonField) = apply { + this.aiVariation = aiVariation + } + + /** + * Specifies the aspect ratio for the output, e.g., "ar-4-3". Typically used with either + * width or height (but not both). For example: aspectRatio = `4:3`, `4_3`, or an expression + * like `iar_div_2`. See + * [Image resize and crop – Aspect ratio](https://imagekit.io/docs/image-resize-and-crop#aspect-ratio---ar). + */ + fun aspectRatio(aspectRatio: AspectRatio) = aspectRatio(JsonField.of(aspectRatio)) + + /** + * Sets [Builder.aspectRatio] to an arbitrary JSON value. + * + * You should usually call [Builder.aspectRatio] with a well-typed [AspectRatio] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun aspectRatio(aspectRatio: JsonField) = apply { + this.aspectRatio = aspectRatio + } + + /** Alias for calling [aspectRatio] with `AspectRatio.ofNumber(number)`. */ + fun aspectRatio(number: Double) = aspectRatio(AspectRatio.ofNumber(number)) + + /** Alias for calling [aspectRatio] with `AspectRatio.ofString(string)`. */ + fun aspectRatio(string: String) = aspectRatio(AspectRatio.ofString(string)) + + /** + * Specifies the audio codec, e.g., `aac`, `opus`, or `none`. See + * [Audio codec](https://imagekit.io/docs/video-optimization#audio-codec---ac). + */ + fun audioCodec(audioCodec: AudioCodec) = audioCodec(JsonField.of(audioCodec)) + + /** + * Sets [Builder.audioCodec] to an arbitrary JSON value. + * + * You should usually call [Builder.audioCodec] with a well-typed [AudioCodec] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun audioCodec(audioCodec: JsonField) = apply { this.audioCodec = audioCodec } + + /** + * Specifies the background to be used in conjunction with certain cropping strategies when + * resizing an image. + * - A solid color: e.g., `red`, `F3F3F3`, `AAFF0010`. See + * [Solid color background](https://imagekit.io/docs/effects-and-enhancements#solid-color-background). + * - A blurred background: e.g., `blurred`, `blurred_25_N15`, etc. See + * [Blurred background](https://imagekit.io/docs/effects-and-enhancements#blurred-background). + * - Expand the image boundaries using generative fill: `genfill`. Not supported inside + * overlay. Optionally, control the background scene by passing a text prompt: + * `genfill[:-prompt-${text}]` or `genfill[:-prompte-${urlencoded_base64_encoded_text}]`. + * See + * [Generative fill background](https://imagekit.io/docs/ai-transformations#generative-fill-bg-genfill). + */ + fun background(background: String) = background(JsonField.of(background)) + + /** + * Sets [Builder.background] to an arbitrary JSON value. + * + * You should usually call [Builder.background] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun background(background: JsonField) = apply { this.background = background } + + /** + * Specifies the Gaussian blur level. Accepts an integer value between 1 and 100, or an + * expression like `bl-10`. See + * [Blur](https://imagekit.io/docs/effects-and-enhancements#blur---bl). + */ + fun blur(blur: Double) = blur(JsonField.of(blur)) + + /** + * Sets [Builder.blur] to an arbitrary JSON value. + * + * You should usually call [Builder.blur] with a well-typed [Double] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun blur(blur: JsonField) = apply { this.blur = blur } + + /** + * Adds a border to the output media. Accepts a string in the format + * `_` (e.g., `5_FFF000` for a 5px yellow border), or an expression + * like `ih_div_20_FF00FF`. See + * [Border](https://imagekit.io/docs/effects-and-enhancements#border---b). + */ + fun border(border: String) = border(JsonField.of(border)) + + /** + * Sets [Builder.border] to an arbitrary JSON value. + * + * You should usually call [Builder.border] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun border(border: JsonField) = apply { this.border = border } + + /** + * Indicates whether the output image should retain the original color profile. See + * [Color profile](https://imagekit.io/docs/image-optimization#color-profile---cp). + */ + fun colorProfile(colorProfile: Boolean) = colorProfile(JsonField.of(colorProfile)) + + /** + * Sets [Builder.colorProfile] to an arbitrary JSON value. + * + * You should usually call [Builder.colorProfile] with a well-typed [Boolean] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun colorProfile(colorProfile: JsonField) = apply { + this.colorProfile = colorProfile + } + + /** + * Automatically enhances the contrast of an image (contrast stretch). See + * [Contrast Stretch](https://imagekit.io/docs/effects-and-enhancements#contrast-stretch---e-contrast). + */ + fun contrastStretch(contrastStretch: ContrastStretch) = + contrastStretch(JsonField.of(contrastStretch)) + + /** + * Sets [Builder.contrastStretch] to an arbitrary JSON value. + * + * You should usually call [Builder.contrastStretch] with a well-typed [ContrastStretch] + * value instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun contrastStretch(contrastStretch: JsonField) = apply { + this.contrastStretch = contrastStretch + } + + /** + * Crop modes for image resizing. See + * [Crop modes & focus](https://imagekit.io/docs/image-resize-and-crop#crop-crop-modes--focus). + */ + fun crop(crop: Crop) = crop(JsonField.of(crop)) + + /** + * Sets [Builder.crop] to an arbitrary JSON value. + * + * You should usually call [Builder.crop] with a well-typed [Crop] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun crop(crop: JsonField) = apply { this.crop = crop } + + /** + * Additional crop modes for image resizing. See + * [Crop modes & focus](https://imagekit.io/docs/image-resize-and-crop#crop-crop-modes--focus). + */ + fun cropMode(cropMode: CropMode) = cropMode(JsonField.of(cropMode)) + + /** + * Sets [Builder.cropMode] to an arbitrary JSON value. + * + * You should usually call [Builder.cropMode] with a well-typed [CropMode] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun cropMode(cropMode: JsonField) = apply { this.cropMode = cropMode } + + /** + * Specifies a fallback image if the resource is not found, e.g., a URL or file path. See + * [Default image](https://imagekit.io/docs/image-transformation#default-image---di). + */ + fun defaultImage(defaultImage: String) = defaultImage(JsonField.of(defaultImage)) + + /** + * Sets [Builder.defaultImage] to an arbitrary JSON value. + * + * You should usually call [Builder.defaultImage] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun defaultImage(defaultImage: JsonField) = apply { + this.defaultImage = defaultImage + } + + /** + * Accepts values between 0.1 and 5, or `auto` for automatic device pixel ratio (DPR) + * calculation. See [DPR](https://imagekit.io/docs/image-resize-and-crop#dpr---dpr). + */ + fun dpr(dpr: Double) = dpr(JsonField.of(dpr)) + + /** + * Sets [Builder.dpr] to an arbitrary JSON value. + * + * You should usually call [Builder.dpr] with a well-typed [Double] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun dpr(dpr: JsonField) = apply { this.dpr = dpr } + + /** + * Specifies the duration (in seconds) for trimming videos, e.g., `5` or `10.5`. Typically + * used with startOffset to indicate the length from the start offset. Arithmetic + * expressions are supported. See + * [Trim videos – Duration](https://imagekit.io/docs/trim-videos#duration---du). + */ + fun duration(duration: Duration) = duration(JsonField.of(duration)) + + /** + * Sets [Builder.duration] to an arbitrary JSON value. + * + * You should usually call [Builder.duration] with a well-typed [Duration] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun duration(duration: JsonField) = apply { this.duration = duration } + + /** Alias for calling [duration] with `Duration.ofNumber(number)`. */ + fun duration(number: Double) = duration(Duration.ofNumber(number)) + + /** Alias for calling [duration] with `Duration.ofString(string)`. */ + fun duration(string: String) = duration(Duration.ofString(string)) + + /** + * Specifies the end offset (in seconds) for trimming videos, e.g., `5` or `10.5`. Typically + * used with startOffset to define a time window. Arithmetic expressions are supported. See + * [Trim videos – End offset](https://imagekit.io/docs/trim-videos#end-offset---eo). + */ + fun endOffset(endOffset: EndOffset) = endOffset(JsonField.of(endOffset)) + + /** + * Sets [Builder.endOffset] to an arbitrary JSON value. + * + * You should usually call [Builder.endOffset] with a well-typed [EndOffset] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun endOffset(endOffset: JsonField) = apply { this.endOffset = endOffset } + + /** Alias for calling [endOffset] with `EndOffset.ofNumber(number)`. */ + fun endOffset(number: Double) = endOffset(EndOffset.ofNumber(number)) + + /** Alias for calling [endOffset] with `EndOffset.ofString(string)`. */ + fun endOffset(string: String) = endOffset(EndOffset.ofString(string)) + + /** + * Flips or mirrors an image either horizontally, vertically, or both. Acceptable values: + * `h` (horizontal), `v` (vertical), `h_v` (horizontal and vertical), or `v_h`. See + * [Flip](https://imagekit.io/docs/effects-and-enhancements#flip---fl). + */ + fun flip(flip: Flip) = flip(JsonField.of(flip)) + + /** + * Sets [Builder.flip] to an arbitrary JSON value. + * + * You should usually call [Builder.flip] with a well-typed [Flip] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun flip(flip: JsonField) = apply { this.flip = flip } + + /** + * Refines padding and cropping behavior for pad resize, maintain ratio, and extract crop + * modes. Supports manual positions and coordinate-based focus. With AI-based cropping, you + * can automatically keep key subjects in frame—such as faces or detected objects (e.g., + * `fo-face`, `fo-person`, `fo-car`)— while resizing. + * - See [Focus](https://imagekit.io/docs/image-resize-and-crop#focus---fo). + * - [Object aware + * cropping](https://imagekit.io/docs/image-resize-and-crop#object-aware-cropping---fo-object-name) + */ + fun focus(focus: String) = focus(JsonField.of(focus)) + + /** + * Sets [Builder.focus] to an arbitrary JSON value. + * + * You should usually call [Builder.focus] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun focus(focus: JsonField) = apply { this.focus = focus } + + /** + * Specifies the output format for images or videos, e.g., `jpg`, `png`, `webp`, `mp4`, or + * `auto`. You can also pass `orig` for images to return the original format. ImageKit + * automatically delivers images and videos in the optimal format based on device support + * unless overridden by the dashboard settings or the format parameter. See + * [Image format](https://imagekit.io/docs/image-optimization#format---f) and + * [Video format](https://imagekit.io/docs/video-optimization#format---f). + */ + fun format(format: Format) = format(JsonField.of(format)) + + /** + * Sets [Builder.format] to an arbitrary JSON value. + * + * You should usually call [Builder.format] with a well-typed [Format] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun format(format: JsonField) = apply { this.format = format } + + /** + * Creates a linear gradient with two colors. Pass `true` for a default gradient, or provide + * a string for a custom gradient. See + * [Gradient](https://imagekit.io/docs/effects-and-enhancements#gradient---e-gradient). + */ + fun gradient(gradient: Gradient) = gradient(JsonField.of(gradient)) + + /** + * Sets [Builder.gradient] to an arbitrary JSON value. + * + * You should usually call [Builder.gradient] with a well-typed [Gradient] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun gradient(gradient: JsonField) = apply { this.gradient = gradient } + + /** Alias for calling [gradient] with `Gradient.ofTrue()`. */ + fun gradientTrue() = gradient(Gradient.ofTrue()) + + /** Alias for calling [gradient] with `Gradient.ofString(string)`. */ + fun gradient(string: String) = gradient(Gradient.ofString(string)) + + /** + * Enables a grayscale effect for images. See + * [Grayscale](https://imagekit.io/docs/effects-and-enhancements#grayscale---e-grayscale). + */ + fun grayscale(grayscale: Grayscale) = grayscale(JsonField.of(grayscale)) + + /** + * Sets [Builder.grayscale] to an arbitrary JSON value. + * + * You should usually call [Builder.grayscale] with a well-typed [Grayscale] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun grayscale(grayscale: JsonField) = apply { this.grayscale = grayscale } + + /** + * Specifies the height of the output. If a value between 0 and 1 is provided, it is treated + * as a percentage (e.g., `0.5` represents 50% of the original height). You can also supply + * arithmetic expressions (e.g., `ih_mul_0.5`). Height transformation – + * [Images](https://imagekit.io/docs/image-resize-and-crop#height---h) · + * [Videos](https://imagekit.io/docs/video-resize-and-crop#height---h) + */ + fun height(height: Height) = height(JsonField.of(height)) + + /** + * Sets [Builder.height] to an arbitrary JSON value. + * + * You should usually call [Builder.height] with a well-typed [Height] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun height(height: JsonField) = apply { this.height = height } + + /** Alias for calling [height] with `Height.ofNumber(number)`. */ + fun height(number: Double) = height(Height.ofNumber(number)) + + /** Alias for calling [height] with `Height.ofString(string)`. */ + fun height(string: String) = height(Height.ofString(string)) + + /** + * Specifies whether the output image (in JPEG or PNG) should be compressed losslessly. See + * [Lossless compression](https://imagekit.io/docs/image-optimization#lossless-webp-and-png---lo). + */ + fun lossless(lossless: Boolean) = lossless(JsonField.of(lossless)) + + /** + * Sets [Builder.lossless] to an arbitrary JSON value. + * + * You should usually call [Builder.lossless] with a well-typed [Boolean] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun lossless(lossless: JsonField) = apply { this.lossless = lossless } + + /** + * By default, ImageKit removes all metadata during automatic image compression. Set this to + * true to preserve metadata. See + * [Image metadata](https://imagekit.io/docs/image-optimization#image-metadata---md). + */ + fun metadata(metadata: Boolean) = metadata(JsonField.of(metadata)) + + /** + * Sets [Builder.metadata] to an arbitrary JSON value. + * + * You should usually call [Builder.metadata] with a well-typed [Boolean] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun metadata(metadata: JsonField) = apply { this.metadata = metadata } + + /** + * Named transformation reference. See + * [Named transformations](https://imagekit.io/docs/transformations#named-transformations). + */ + fun named(named: String) = named(JsonField.of(named)) + + /** + * Sets [Builder.named] to an arbitrary JSON value. + * + * You should usually call [Builder.named] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun named(named: JsonField) = apply { this.named = named } + + /** + * Specifies the opacity level of the output image. See + * [Opacity](https://imagekit.io/docs/effects-and-enhancements#opacity---o). + */ + fun opacity(opacity: Double) = opacity(JsonField.of(opacity)) + + /** + * Sets [Builder.opacity] to an arbitrary JSON value. + * + * You should usually call [Builder.opacity] with a well-typed [Double] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun opacity(opacity: JsonField) = apply { this.opacity = opacity } + + /** + * If set to true, serves the original file without applying any transformations. See + * [Deliver original file as-is](https://imagekit.io/docs/core-delivery-features#deliver-original-file-as-is---orig-true). + */ + fun original(original: Boolean) = original(JsonField.of(original)) + + /** + * Sets [Builder.original] to an arbitrary JSON value. + * + * You should usually call [Builder.original] with a well-typed [Boolean] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun original(original: JsonField) = apply { this.original = original } + + /** + * Specifies an overlay to be applied on the parent image or video. ImageKit supports + * overlays including images, text, videos, subtitles, and solid colors. See + * [Overlay using layers](https://imagekit.io/docs/transformations#overlay-using-layers). + */ + fun overlay(overlay: Overlay) = overlay(JsonField.of(overlay)) + + /** + * Sets [Builder.overlay] to an arbitrary JSON value. + * + * You should usually call [Builder.overlay] with a well-typed [Overlay] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun overlay(overlay: JsonField) = apply { this.overlay = overlay } + + /** Alias for calling [overlay] with `Overlay.ofText(text)`. */ + fun overlay(text: TextOverlay) = overlay(Overlay.ofText(text)) + + /** + * Alias for calling [overlay] with the following: + * ```java + * TextOverlay.builder() + * .text(text) + * .build() + * ``` + */ + fun textOverlay(text: String) = overlay(TextOverlay.builder().text(text).build()) + + /** Alias for calling [overlay] with `Overlay.ofImage(image)`. */ + fun overlay(image: ImageOverlay) = overlay(Overlay.ofImage(image)) + + /** + * Alias for calling [overlay] with the following: + * ```java + * ImageOverlay.builder() + * .input(input) + * .build() + * ``` + */ + fun imageOverlay(input: String) = overlay(ImageOverlay.builder().input(input).build()) + + /** Alias for calling [overlay] with `Overlay.ofVideo(video)`. */ + fun overlay(video: VideoOverlay) = overlay(Overlay.ofVideo(video)) + + /** + * Alias for calling [overlay] with the following: + * ```java + * VideoOverlay.builder() + * .input(input) + * .build() + * ``` + */ + fun videoOverlay(input: String) = overlay(VideoOverlay.builder().input(input).build()) + + /** Alias for calling [overlay] with `Overlay.ofSubtitle(subtitle)`. */ + fun overlay(subtitle: SubtitleOverlay) = overlay(Overlay.ofSubtitle(subtitle)) + + /** + * Alias for calling [overlay] with the following: + * ```java + * SubtitleOverlay.builder() + * .input(input) + * .build() + * ``` + */ + fun subtitleOverlay(input: String) = overlay(SubtitleOverlay.builder().input(input).build()) + + /** Alias for calling [overlay] with `Overlay.ofSolidColor(solidColor)`. */ + fun overlay(solidColor: SolidColorOverlay) = overlay(Overlay.ofSolidColor(solidColor)) + + /** + * Alias for calling [overlay] with the following: + * ```java + * SolidColorOverlay.builder() + * .color(color) + * .build() + * ``` + */ + fun solidColorOverlay(color: String) = + overlay(SolidColorOverlay.builder().color(color).build()) + + /** + * Extracts a specific page or frame from multi-page or layered files (PDF, PSD, AI). For + * example, specify by number (e.g., `2`), a range (e.g., `3-4` for the 2nd and 3rd layers), + * or by name (e.g., `name-layer-4` for a PSD layer). See + * [Thumbnail extraction](https://imagekit.io/docs/vector-and-animated-images#get-thumbnail-from-psd-pdf-ai-eps-and-animated-files). + */ + fun page(page: Page) = page(JsonField.of(page)) + + /** + * Sets [Builder.page] to an arbitrary JSON value. + * + * You should usually call [Builder.page] with a well-typed [Page] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun page(page: JsonField) = apply { this.page = page } + + /** Alias for calling [page] with `Page.ofNumber(number)`. */ + fun page(number: Double) = page(Page.ofNumber(number)) + + /** Alias for calling [page] with `Page.ofString(string)`. */ + fun page(string: String) = page(Page.ofString(string)) + + /** + * Specifies whether the output JPEG image should be rendered progressively. Progressive + * loading begins with a low-quality, pixelated version of the full image, which gradually + * improves to provide a faster perceived load time. See + * [Progressive images](https://imagekit.io/docs/image-optimization#progressive-image---pr). + */ + fun progressive(progressive: Boolean) = progressive(JsonField.of(progressive)) + + /** + * Sets [Builder.progressive] to an arbitrary JSON value. + * + * You should usually call [Builder.progressive] with a well-typed [Boolean] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun progressive(progressive: JsonField) = apply { this.progressive = progressive } + + /** + * Specifies the quality of the output image for lossy formats such as JPEG, WebP, and AVIF. + * A higher quality value results in a larger file size with better quality, while a lower + * value produces a smaller file size with reduced quality. See + * [Quality](https://imagekit.io/docs/image-optimization#quality---q). + */ + fun quality(quality: Double) = quality(JsonField.of(quality)) + + /** + * Sets [Builder.quality] to an arbitrary JSON value. + * + * You should usually call [Builder.quality] with a well-typed [Double] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun quality(quality: JsonField) = apply { this.quality = quality } + + /** + * Specifies the corner radius for rounded corners (e.g., 20) or `max` for circular or oval + * shape. See [Radius](https://imagekit.io/docs/effects-and-enhancements#radius---r). + */ + fun radius(radius: Radius) = radius(JsonField.of(radius)) + + /** + * Sets [Builder.radius] to an arbitrary JSON value. + * + * You should usually call [Builder.radius] with a well-typed [Radius] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun radius(radius: JsonField) = apply { this.radius = radius } + + /** Alias for calling [radius] with `Radius.ofNumber(number)`. */ + fun radius(number: Double) = radius(Radius.ofNumber(number)) + + /** Alias for calling [radius] with `Radius.ofMax()`. */ + fun radiusMax() = radius(Radius.ofMax()) + + /** + * Pass any transformation not directly supported by the SDK. This transformation string is + * appended to the URL as provided. + */ + fun raw(raw: String) = raw(JsonField.of(raw)) + + /** + * Sets [Builder.raw] to an arbitrary JSON value. + * + * You should usually call [Builder.raw] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun raw(raw: JsonField) = apply { this.raw = raw } + + /** + * Specifies the rotation angle in degrees. Positive values rotate the image clockwise; you + * can also use, for example, `N40` for counterclockwise rotation or `auto` to use the + * orientation specified in the image's EXIF data. For videos, only the following values are + * supported: 0, 90, 180, 270, or 360. See + * [Rotate](https://imagekit.io/docs/effects-and-enhancements#rotate---rt). + */ + fun rotation(rotation: Rotation) = rotation(JsonField.of(rotation)) + + /** + * Sets [Builder.rotation] to an arbitrary JSON value. + * + * You should usually call [Builder.rotation] with a well-typed [Rotation] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun rotation(rotation: JsonField) = apply { this.rotation = rotation } + + /** Alias for calling [rotation] with `Rotation.ofNumber(number)`. */ + fun rotation(number: Double) = rotation(Rotation.ofNumber(number)) + + /** Alias for calling [rotation] with `Rotation.ofString(string)`. */ + fun rotation(string: String) = rotation(Rotation.ofString(string)) + + /** + * Adds a shadow beneath solid objects in an image with a transparent background. For + * AI-based drop shadows, refer to aiDropShadow. Pass `true` for a default shadow, or + * provide a string for a custom shadow. See + * [Shadow](https://imagekit.io/docs/effects-and-enhancements#shadow---e-shadow). + */ + fun shadow(shadow: Shadow) = shadow(JsonField.of(shadow)) + + /** + * Sets [Builder.shadow] to an arbitrary JSON value. + * + * You should usually call [Builder.shadow] with a well-typed [Shadow] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun shadow(shadow: JsonField) = apply { this.shadow = shadow } + + /** Alias for calling [shadow] with `Shadow.ofTrue()`. */ + fun shadowTrue() = shadow(Shadow.ofTrue()) + + /** Alias for calling [shadow] with `Shadow.ofString(string)`. */ + fun shadow(string: String) = shadow(Shadow.ofString(string)) + + /** + * Sharpens the input image, highlighting edges and finer details. Pass `true` for default + * sharpening, or provide a numeric value for custom sharpening. See + * [Sharpen](https://imagekit.io/docs/effects-and-enhancements#sharpen---e-sharpen). + */ + fun sharpen(sharpen: Sharpen) = sharpen(JsonField.of(sharpen)) + + /** + * Sets [Builder.sharpen] to an arbitrary JSON value. + * + * You should usually call [Builder.sharpen] with a well-typed [Sharpen] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun sharpen(sharpen: JsonField) = apply { this.sharpen = sharpen } + + /** Alias for calling [sharpen] with `Sharpen.ofTrue()`. */ + fun sharpenTrue() = sharpen(Sharpen.ofTrue()) + + /** Alias for calling [sharpen] with `Sharpen.ofNumber(number)`. */ + fun sharpen(number: Double) = sharpen(Sharpen.ofNumber(number)) + + /** + * Specifies the start offset (in seconds) for trimming videos, e.g., `5` or `10.5`. + * Arithmetic expressions are also supported. See + * [Trim videos – Start offset](https://imagekit.io/docs/trim-videos#start-offset---so). + */ + fun startOffset(startOffset: StartOffset) = startOffset(JsonField.of(startOffset)) + + /** + * Sets [Builder.startOffset] to an arbitrary JSON value. + * + * You should usually call [Builder.startOffset] with a well-typed [StartOffset] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun startOffset(startOffset: JsonField) = apply { + this.startOffset = startOffset + } + + /** Alias for calling [startOffset] with `StartOffset.ofNumber(number)`. */ + fun startOffset(number: Double) = startOffset(StartOffset.ofNumber(number)) + + /** Alias for calling [startOffset] with `StartOffset.ofString(string)`. */ + fun startOffset(string: String) = startOffset(StartOffset.ofString(string)) + + /** + * An array of resolutions for adaptive bitrate streaming, e.g., + * [`240`, `360`, `480`, `720`, `1080`]. See + * [Adaptive Bitrate Streaming](https://imagekit.io/docs/adaptive-bitrate-streaming). + */ + fun streamingResolutions(streamingResolutions: List) = + streamingResolutions(JsonField.of(streamingResolutions)) + + /** + * Sets [Builder.streamingResolutions] to an arbitrary JSON value. + * + * You should usually call [Builder.streamingResolutions] with a well-typed + * `List` value instead. This method is primarily for setting the field + * to an undocumented or not yet supported value. + */ + fun streamingResolutions(streamingResolutions: JsonField>) = + apply { + this.streamingResolutions = streamingResolutions.map { it.toMutableList() } + } + + /** + * Adds a single [StreamingResolution] to [streamingResolutions]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addStreamingResolution(streamingResolution: StreamingResolution) = apply { + streamingResolutions = + (streamingResolutions ?: JsonField.of(mutableListOf())).also { + checkKnown("streamingResolutions", it).add(streamingResolution) + } + } + + /** + * Useful for images with a solid or nearly solid background and a central object. This + * parameter trims the background, leaving only the central object in the output image. See + * [Trim edges](https://imagekit.io/docs/effects-and-enhancements#trim-edges---t). + */ + fun trim(trim: Trim) = trim(JsonField.of(trim)) + + /** + * Sets [Builder.trim] to an arbitrary JSON value. + * + * You should usually call [Builder.trim] with a well-typed [Trim] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun trim(trim: JsonField) = apply { this.trim = trim } + + /** Alias for calling [trim] with `Trim.ofTrue()`. */ + fun trimTrue() = trim(Trim.ofTrue()) + + /** Alias for calling [trim] with `Trim.ofNumber(number)`. */ + fun trim(number: Double) = trim(Trim.ofNumber(number)) + + /** + * Applies Unsharp Masking (USM), an image sharpening technique. Pass `true` for a default + * unsharp mask, or provide a string for a custom unsharp mask. See + * [Unsharp Mask](https://imagekit.io/docs/effects-and-enhancements#unsharp-mask---e-usm). + */ + fun unsharpMask(unsharpMask: UnsharpMask) = unsharpMask(JsonField.of(unsharpMask)) + + /** + * Sets [Builder.unsharpMask] to an arbitrary JSON value. + * + * You should usually call [Builder.unsharpMask] with a well-typed [UnsharpMask] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun unsharpMask(unsharpMask: JsonField) = apply { + this.unsharpMask = unsharpMask + } + + /** Alias for calling [unsharpMask] with `UnsharpMask.ofTrue()`. */ + fun unsharpMaskTrue() = unsharpMask(UnsharpMask.ofTrue()) + + /** Alias for calling [unsharpMask] with `UnsharpMask.ofString(string)`. */ + fun unsharpMask(string: String) = unsharpMask(UnsharpMask.ofString(string)) + + /** + * Specifies the video codec, e.g., `h264`, `vp9`, `av1`, or `none`. See + * [Video codec](https://imagekit.io/docs/video-optimization#video-codec---vc). + */ + fun videoCodec(videoCodec: VideoCodec) = videoCodec(JsonField.of(videoCodec)) + + /** + * Sets [Builder.videoCodec] to an arbitrary JSON value. + * + * You should usually call [Builder.videoCodec] with a well-typed [VideoCodec] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun videoCodec(videoCodec: JsonField) = apply { this.videoCodec = videoCodec } + + /** + * Specifies the width of the output. If a value between 0 and 1 is provided, it is treated + * as a percentage (e.g., `0.4` represents 40% of the original width). You can also supply + * arithmetic expressions (e.g., `iw_div_2`). Width transformation – + * [Images](https://imagekit.io/docs/image-resize-and-crop#width---w) · + * [Videos](https://imagekit.io/docs/video-resize-and-crop#width---w) + */ + fun width(width: Width) = width(JsonField.of(width)) + + /** + * Sets [Builder.width] to an arbitrary JSON value. + * + * You should usually call [Builder.width] with a well-typed [Width] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun width(width: JsonField) = apply { this.width = width } + + /** Alias for calling [width] with `Width.ofNumber(number)`. */ + fun width(number: Double) = width(Width.ofNumber(number)) + + /** Alias for calling [width] with `Width.ofString(string)`. */ + fun width(string: String) = width(Width.ofString(string)) + + /** + * Focus using cropped image coordinates - X coordinate. See + * [Focus using cropped coordinates](https://imagekit.io/docs/image-resize-and-crop#example---focus-using-cropped-image-coordinates). + */ + fun x(x: X) = x(JsonField.of(x)) + + /** + * Sets [Builder.x] to an arbitrary JSON value. + * + * You should usually call [Builder.x] with a well-typed [X] value instead. This method is + * primarily for setting the field to an undocumented or not yet supported value. + */ + fun x(x: JsonField) = apply { this.x = x } + + /** Alias for calling [x] with `X.ofNumber(number)`. */ + fun x(number: Double) = x(X.ofNumber(number)) + + /** Alias for calling [x] with `X.ofString(string)`. */ + fun x(string: String) = x(X.ofString(string)) + + /** + * Focus using cropped image coordinates - X center coordinate. See + * [Focus using cropped coordinates](https://imagekit.io/docs/image-resize-and-crop#example---focus-using-cropped-image-coordinates). + */ + fun xCenter(xCenter: XCenter) = xCenter(JsonField.of(xCenter)) + + /** + * Sets [Builder.xCenter] to an arbitrary JSON value. + * + * You should usually call [Builder.xCenter] with a well-typed [XCenter] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun xCenter(xCenter: JsonField) = apply { this.xCenter = xCenter } + + /** Alias for calling [xCenter] with `XCenter.ofNumber(number)`. */ + fun xCenter(number: Double) = xCenter(XCenter.ofNumber(number)) + + /** Alias for calling [xCenter] with `XCenter.ofString(string)`. */ + fun xCenter(string: String) = xCenter(XCenter.ofString(string)) + + /** + * Focus using cropped image coordinates - Y coordinate. See + * [Focus using cropped coordinates](https://imagekit.io/docs/image-resize-and-crop#example---focus-using-cropped-image-coordinates). + */ + fun y(y: Y) = y(JsonField.of(y)) + + /** + * Sets [Builder.y] to an arbitrary JSON value. + * + * You should usually call [Builder.y] with a well-typed [Y] value instead. This method is + * primarily for setting the field to an undocumented or not yet supported value. + */ + fun y(y: JsonField) = apply { this.y = y } + + /** Alias for calling [y] with `Y.ofNumber(number)`. */ + fun y(number: Double) = y(Y.ofNumber(number)) + + /** Alias for calling [y] with `Y.ofString(string)`. */ + fun y(string: String) = y(Y.ofString(string)) + + /** + * Focus using cropped image coordinates - Y center coordinate. See + * [Focus using cropped coordinates](https://imagekit.io/docs/image-resize-and-crop#example---focus-using-cropped-image-coordinates). + */ + fun yCenter(yCenter: YCenter) = yCenter(JsonField.of(yCenter)) + + /** + * Sets [Builder.yCenter] to an arbitrary JSON value. + * + * You should usually call [Builder.yCenter] with a well-typed [YCenter] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun yCenter(yCenter: JsonField) = apply { this.yCenter = yCenter } + + /** Alias for calling [yCenter] with `YCenter.ofNumber(number)`. */ + fun yCenter(number: Double) = yCenter(YCenter.ofNumber(number)) + + /** Alias for calling [yCenter] with `YCenter.ofString(string)`. */ + fun yCenter(string: String) = yCenter(YCenter.ofString(string)) + + /** + * Accepts a numeric value that determines how much to zoom in or out of the cropped area. + * It should be used in conjunction with fo-face or fo-. See + * [Zoom](https://imagekit.io/docs/image-resize-and-crop#zoom---z). + */ + fun zoom(zoom: Double) = zoom(JsonField.of(zoom)) + + /** + * Sets [Builder.zoom] to an arbitrary JSON value. + * + * You should usually call [Builder.zoom] with a well-typed [Double] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun zoom(zoom: JsonField) = apply { this.zoom = zoom } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Transformation]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Transformation = + Transformation( + aiChangeBackground, + aiDropShadow, + aiEdit, + aiRemoveBackground, + aiRemoveBackgroundExternal, + aiRetouch, + aiUpscale, + aiVariation, + aspectRatio, + audioCodec, + background, + blur, + border, + colorProfile, + contrastStretch, + crop, + cropMode, + defaultImage, + dpr, + duration, + endOffset, + flip, + focus, + format, + gradient, + grayscale, + height, + lossless, + metadata, + named, + opacity, + original, + overlay, + page, + progressive, + quality, + radius, + raw, + rotation, + shadow, + sharpen, + startOffset, + (streamingResolutions ?: JsonMissing.of()).map { it.toImmutable() }, + trim, + unsharpMask, + videoCodec, + width, + x, + xCenter, + y, + yCenter, + zoom, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Transformation = apply { + if (validated) { + return@apply + } + + aiChangeBackground() + aiDropShadow().ifPresent { it.validate() } + aiEdit() + aiRemoveBackground().ifPresent { it.validate() } + aiRemoveBackgroundExternal().ifPresent { it.validate() } + aiRetouch().ifPresent { it.validate() } + aiUpscale().ifPresent { it.validate() } + aiVariation().ifPresent { it.validate() } + aspectRatio().ifPresent { it.validate() } + audioCodec().ifPresent { it.validate() } + background() + blur() + border() + colorProfile() + contrastStretch().ifPresent { it.validate() } + crop().ifPresent { it.validate() } + cropMode().ifPresent { it.validate() } + defaultImage() + dpr() + duration().ifPresent { it.validate() } + endOffset().ifPresent { it.validate() } + flip().ifPresent { it.validate() } + focus() + format().ifPresent { it.validate() } + gradient().ifPresent { it.validate() } + grayscale().ifPresent { it.validate() } + height().ifPresent { it.validate() } + lossless() + metadata() + named() + opacity() + original() + overlay().ifPresent { it.validate() } + page().ifPresent { it.validate() } + progressive() + quality() + radius().ifPresent { it.validate() } + raw() + rotation().ifPresent { it.validate() } + shadow().ifPresent { it.validate() } + sharpen().ifPresent { it.validate() } + startOffset().ifPresent { it.validate() } + streamingResolutions().ifPresent { it.forEach { it.validate() } } + trim().ifPresent { it.validate() } + unsharpMask().ifPresent { it.validate() } + videoCodec().ifPresent { it.validate() } + width().ifPresent { it.validate() } + x().ifPresent { it.validate() } + xCenter().ifPresent { it.validate() } + y().ifPresent { it.validate() } + yCenter().ifPresent { it.validate() } + zoom() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (aiChangeBackground.asKnown().isPresent) 1 else 0) + + (aiDropShadow.asKnown().getOrNull()?.validity() ?: 0) + + (if (aiEdit.asKnown().isPresent) 1 else 0) + + (aiRemoveBackground.asKnown().getOrNull()?.validity() ?: 0) + + (aiRemoveBackgroundExternal.asKnown().getOrNull()?.validity() ?: 0) + + (aiRetouch.asKnown().getOrNull()?.validity() ?: 0) + + (aiUpscale.asKnown().getOrNull()?.validity() ?: 0) + + (aiVariation.asKnown().getOrNull()?.validity() ?: 0) + + (aspectRatio.asKnown().getOrNull()?.validity() ?: 0) + + (audioCodec.asKnown().getOrNull()?.validity() ?: 0) + + (if (background.asKnown().isPresent) 1 else 0) + + (if (blur.asKnown().isPresent) 1 else 0) + + (if (border.asKnown().isPresent) 1 else 0) + + (if (colorProfile.asKnown().isPresent) 1 else 0) + + (contrastStretch.asKnown().getOrNull()?.validity() ?: 0) + + (crop.asKnown().getOrNull()?.validity() ?: 0) + + (cropMode.asKnown().getOrNull()?.validity() ?: 0) + + (if (defaultImage.asKnown().isPresent) 1 else 0) + + (if (dpr.asKnown().isPresent) 1 else 0) + + (duration.asKnown().getOrNull()?.validity() ?: 0) + + (endOffset.asKnown().getOrNull()?.validity() ?: 0) + + (flip.asKnown().getOrNull()?.validity() ?: 0) + + (if (focus.asKnown().isPresent) 1 else 0) + + (format.asKnown().getOrNull()?.validity() ?: 0) + + (gradient.asKnown().getOrNull()?.validity() ?: 0) + + (grayscale.asKnown().getOrNull()?.validity() ?: 0) + + (height.asKnown().getOrNull()?.validity() ?: 0) + + (if (lossless.asKnown().isPresent) 1 else 0) + + (if (metadata.asKnown().isPresent) 1 else 0) + + (if (named.asKnown().isPresent) 1 else 0) + + (if (opacity.asKnown().isPresent) 1 else 0) + + (if (original.asKnown().isPresent) 1 else 0) + + (overlay.asKnown().getOrNull()?.validity() ?: 0) + + (page.asKnown().getOrNull()?.validity() ?: 0) + + (if (progressive.asKnown().isPresent) 1 else 0) + + (if (quality.asKnown().isPresent) 1 else 0) + + (radius.asKnown().getOrNull()?.validity() ?: 0) + + (if (raw.asKnown().isPresent) 1 else 0) + + (rotation.asKnown().getOrNull()?.validity() ?: 0) + + (shadow.asKnown().getOrNull()?.validity() ?: 0) + + (sharpen.asKnown().getOrNull()?.validity() ?: 0) + + (startOffset.asKnown().getOrNull()?.validity() ?: 0) + + (streamingResolutions.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + (trim.asKnown().getOrNull()?.validity() ?: 0) + + (unsharpMask.asKnown().getOrNull()?.validity() ?: 0) + + (videoCodec.asKnown().getOrNull()?.validity() ?: 0) + + (width.asKnown().getOrNull()?.validity() ?: 0) + + (x.asKnown().getOrNull()?.validity() ?: 0) + + (xCenter.asKnown().getOrNull()?.validity() ?: 0) + + (y.asKnown().getOrNull()?.validity() ?: 0) + + (yCenter.asKnown().getOrNull()?.validity() ?: 0) + + (if (zoom.asKnown().isPresent) 1 else 0) + + /** + * Adds an AI-based drop shadow around a foreground object on a transparent or removed + * background. Optionally, control the direction, elevation, and saturation of the light source + * (e.g., `az-45` to change light direction). Pass `true` for the default drop shadow, or + * provide a string for a custom drop shadow. Supported inside overlay. See + * [AI Drop Shadow](https://imagekit.io/docs/ai-transformations#ai-drop-shadow-e-dropshadow). + */ + @JsonDeserialize(using = AiDropShadow.Deserializer::class) + @JsonSerialize(using = AiDropShadow.Serializer::class) + class AiDropShadow + private constructor( + private val true_: JsonValue? = null, + private val string: String? = null, + private val _json: JsonValue? = null, + ) { + + fun true_(): Optional = Optional.ofNullable(true_) + + fun string(): Optional = Optional.ofNullable(string) + + fun isTrue(): Boolean = true_ != null + + fun isString(): Boolean = string != null + + fun asTrue(): JsonValue = true_.getOrThrow("true_") + + fun asString(): String = string.getOrThrow("string") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + true_ != null -> visitor.visitTrue(true_) + string != null -> visitor.visitString(string) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): AiDropShadow = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitTrue(true_: JsonValue) { + true_.let { + if (it != JsonValue.from(true)) { + throw ImageKitInvalidDataException( + "'true_' is invalid, received $it" + ) + } + } + } + + override fun visitString(string: String) {} + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitTrue(true_: JsonValue) = + true_.let { if (it == JsonValue.from(true)) 1 else 0 } + + override fun visitString(string: String) = 1 + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is AiDropShadow && true_ == other.true_ && string == other.string + } + + override fun hashCode(): Int = Objects.hash(true_, string) + + override fun toString(): String = + when { + true_ != null -> "AiDropShadow{true_=$true_}" + string != null -> "AiDropShadow{string=$string}" + _json != null -> "AiDropShadow{_unknown=$_json}" + else -> throw IllegalStateException("Invalid AiDropShadow") + } + + companion object { + + @JvmStatic fun ofTrue() = AiDropShadow(true_ = JsonValue.from(true)) + + @JvmStatic fun ofString(string: String) = AiDropShadow(string = string) + } + + /** + * An interface that defines how to map each variant of [AiDropShadow] to a value of type + * [T]. + */ + interface Visitor { + + fun visitTrue(true_: JsonValue): T + + fun visitString(string: String): T + + /** + * Maps an unknown variant of [AiDropShadow] to a value of type [T]. + * + * An instance of [AiDropShadow] can contain an unknown variant if it was deserialized + * from data that doesn't match any known variant. For example, if the SDK is on an + * older version than the API, then the API may respond with new variants that the SDK + * is unaware of. + * + * @throws ImageKitInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw ImageKitInvalidDataException("Unknown AiDropShadow: $json") + } + } + + internal class Deserializer : BaseDeserializer(AiDropShadow::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): AiDropShadow { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef()) + ?.let { AiDropShadow(true_ = it, _json = json) } + ?.takeIf { it.isValid() }, + tryDeserialize(node, jacksonTypeRef())?.let { + AiDropShadow(string = it, _json = json) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely incompatible with + // all the possible variants (e.g. deserializing from object). + 0 -> AiDropShadow(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then use the first + // completely valid match, or simply the first match if none are completely + // valid. + else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() + } + } + } + + internal class Serializer : BaseSerializer(AiDropShadow::class) { + + override fun serialize( + value: AiDropShadow, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.true_ != null -> generator.writeObject(value.true_) + value.string != null -> generator.writeObject(value.string) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid AiDropShadow") + } + } + } + } + + /** + * Applies ImageKit's in-house background removal. Supported inside overlay. See + * [AI Background Removal](https://imagekit.io/docs/ai-transformations#imagekit-background-removal-e-bgremove). + */ + class AiRemoveBackground + @JsonCreator + private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is on an + * older version than the API, then the API may respond with new members that the SDK is + * unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val TRUE = of(true) + + @JvmStatic fun of(value: Boolean) = AiRemoveBackground(JsonField.of(value)) + } + + /** An enum containing [AiRemoveBackground]'s known values. */ + enum class Known { + TRUE + } + + /** + * An enum containing [AiRemoveBackground]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [AiRemoveBackground] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if the + * SDK is on an older version than the API, then the API may respond with new members that + * the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + TRUE, + /** + * An enum member indicating that [AiRemoveBackground] was instantiated with an unknown + * value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] + * if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you want + * to throw for the unknown case. + */ + fun value(): Value = + when (this) { + TRUE -> Value.TRUE + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and don't + * want to throw for the unknown case. + * + * @throws ImageKitInvalidDataException if this class instance's value is a not a known + * member. + */ + fun known(): Known = + when (this) { + TRUE -> Known.TRUE + else -> throw ImageKitInvalidDataException("Unknown AiRemoveBackground: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * @throws ImageKitInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asBoolean(): Boolean = + _value().asBoolean().orElseThrow { + ImageKitInvalidDataException("Value is not a Boolean") + } + + private var validated: Boolean = false + + fun validate(): AiRemoveBackground = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is AiRemoveBackground && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + /** + * Uses third-party background removal. Note: It is recommended to use aiRemoveBackground, + * ImageKit's in-house solution, which is more cost-effective. Supported inside overlay. See + * [External Background Removal](https://imagekit.io/docs/ai-transformations#background-removal-e-removedotbg). + */ + class AiRemoveBackgroundExternal + @JsonCreator + private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is on an + * older version than the API, then the API may respond with new members that the SDK is + * unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val TRUE = of(true) + + @JvmStatic fun of(value: Boolean) = AiRemoveBackgroundExternal(JsonField.of(value)) + } + + /** An enum containing [AiRemoveBackgroundExternal]'s known values. */ + enum class Known { + TRUE + } + + /** + * An enum containing [AiRemoveBackgroundExternal]'s known values, as well as an [_UNKNOWN] + * member. + * + * An instance of [AiRemoveBackgroundExternal] can contain an unknown value in a couple of + * cases: + * - It was deserialized from data that doesn't match any known member. For example, if the + * SDK is on an older version than the API, then the API may respond with new members that + * the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + TRUE, + /** + * An enum member indicating that [AiRemoveBackgroundExternal] was instantiated with an + * unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] + * if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you want + * to throw for the unknown case. + */ + fun value(): Value = + when (this) { + TRUE -> Value.TRUE + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and don't + * want to throw for the unknown case. + * + * @throws ImageKitInvalidDataException if this class instance's value is a not a known + * member. + */ + fun known(): Known = + when (this) { + TRUE -> Known.TRUE + else -> + throw ImageKitInvalidDataException("Unknown AiRemoveBackgroundExternal: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * @throws ImageKitInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asBoolean(): Boolean = + _value().asBoolean().orElseThrow { + ImageKitInvalidDataException("Value is not a Boolean") + } + + private var validated: Boolean = false + + fun validate(): AiRemoveBackgroundExternal = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is AiRemoveBackgroundExternal && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + /** + * Performs AI-based retouching to improve faces or product shots. Not supported inside overlay. + * See [AI Retouch](https://imagekit.io/docs/ai-transformations#retouch-e-retouch). + */ + class AiRetouch @JsonCreator private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is on an + * older version than the API, then the API may respond with new members that the SDK is + * unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val TRUE = of(true) + + @JvmStatic fun of(value: Boolean) = AiRetouch(JsonField.of(value)) + } + + /** An enum containing [AiRetouch]'s known values. */ + enum class Known { + TRUE + } + + /** + * An enum containing [AiRetouch]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [AiRetouch] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if the + * SDK is on an older version than the API, then the API may respond with new members that + * the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + TRUE, + /** + * An enum member indicating that [AiRetouch] was instantiated with an unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] + * if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you want + * to throw for the unknown case. + */ + fun value(): Value = + when (this) { + TRUE -> Value.TRUE + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and don't + * want to throw for the unknown case. + * + * @throws ImageKitInvalidDataException if this class instance's value is a not a known + * member. + */ + fun known(): Known = + when (this) { + TRUE -> Known.TRUE + else -> throw ImageKitInvalidDataException("Unknown AiRetouch: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * @throws ImageKitInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asBoolean(): Boolean = + _value().asBoolean().orElseThrow { + ImageKitInvalidDataException("Value is not a Boolean") + } + + private var validated: Boolean = false + + fun validate(): AiRetouch = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is AiRetouch && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + /** + * Upscales images beyond their original dimensions using AI. Not supported inside overlay. See + * [AI Upscale](https://imagekit.io/docs/ai-transformations#upscale-e-upscale). + */ + class AiUpscale @JsonCreator private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is on an + * older version than the API, then the API may respond with new members that the SDK is + * unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val TRUE = of(true) + + @JvmStatic fun of(value: Boolean) = AiUpscale(JsonField.of(value)) + } + + /** An enum containing [AiUpscale]'s known values. */ + enum class Known { + TRUE + } + + /** + * An enum containing [AiUpscale]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [AiUpscale] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if the + * SDK is on an older version than the API, then the API may respond with new members that + * the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + TRUE, + /** + * An enum member indicating that [AiUpscale] was instantiated with an unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] + * if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you want + * to throw for the unknown case. + */ + fun value(): Value = + when (this) { + TRUE -> Value.TRUE + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and don't + * want to throw for the unknown case. + * + * @throws ImageKitInvalidDataException if this class instance's value is a not a known + * member. + */ + fun known(): Known = + when (this) { + TRUE -> Known.TRUE + else -> throw ImageKitInvalidDataException("Unknown AiUpscale: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * @throws ImageKitInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asBoolean(): Boolean = + _value().asBoolean().orElseThrow { + ImageKitInvalidDataException("Value is not a Boolean") + } + + private var validated: Boolean = false + + fun validate(): AiUpscale = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is AiUpscale && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + /** + * Generates a variation of an image using AI. This produces a new image with slight variations + * from the original, such as changes in color, texture, and other visual elements, while + * preserving the structure and essence of the original image. Not supported inside overlay. See + * [AI Generate Variations](https://imagekit.io/docs/ai-transformations#generate-variations-of-an-image-e-genvar). + */ + class AiVariation @JsonCreator private constructor(private val value: JsonField) : + Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is on an + * older version than the API, then the API may respond with new members that the SDK is + * unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val TRUE = of(true) + + @JvmStatic fun of(value: Boolean) = AiVariation(JsonField.of(value)) + } + + /** An enum containing [AiVariation]'s known values. */ + enum class Known { + TRUE + } + + /** + * An enum containing [AiVariation]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [AiVariation] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if the + * SDK is on an older version than the API, then the API may respond with new members that + * the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + TRUE, + /** + * An enum member indicating that [AiVariation] was instantiated with an unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] + * if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you want + * to throw for the unknown case. + */ + fun value(): Value = + when (this) { + TRUE -> Value.TRUE + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and don't + * want to throw for the unknown case. + * + * @throws ImageKitInvalidDataException if this class instance's value is a not a known + * member. + */ + fun known(): Known = + when (this) { + TRUE -> Known.TRUE + else -> throw ImageKitInvalidDataException("Unknown AiVariation: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * @throws ImageKitInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asBoolean(): Boolean = + _value().asBoolean().orElseThrow { + ImageKitInvalidDataException("Value is not a Boolean") + } + + private var validated: Boolean = false + + fun validate(): AiVariation = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is AiVariation && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + /** + * Specifies the aspect ratio for the output, e.g., "ar-4-3". Typically used with either width + * or height (but not both). For example: aspectRatio = `4:3`, `4_3`, or an expression like + * `iar_div_2`. See + * [Image resize and crop – Aspect ratio](https://imagekit.io/docs/image-resize-and-crop#aspect-ratio---ar). + */ + @JsonDeserialize(using = AspectRatio.Deserializer::class) + @JsonSerialize(using = AspectRatio.Serializer::class) + class AspectRatio + private constructor( + private val number: Double? = null, + private val string: String? = null, + private val _json: JsonValue? = null, + ) { + + fun number(): Optional = Optional.ofNullable(number) + + fun string(): Optional = Optional.ofNullable(string) + + fun isNumber(): Boolean = number != null + + fun isString(): Boolean = string != null + + fun asNumber(): Double = number.getOrThrow("number") + + fun asString(): String = string.getOrThrow("string") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + number != null -> visitor.visitNumber(number) + string != null -> visitor.visitString(string) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): AspectRatio = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitNumber(number: Double) {} + + override fun visitString(string: String) {} + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitNumber(number: Double) = 1 + + override fun visitString(string: String) = 1 + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is AspectRatio && number == other.number && string == other.string + } + + override fun hashCode(): Int = Objects.hash(number, string) + + override fun toString(): String = + when { + number != null -> "AspectRatio{number=$number}" + string != null -> "AspectRatio{string=$string}" + _json != null -> "AspectRatio{_unknown=$_json}" + else -> throw IllegalStateException("Invalid AspectRatio") + } + + companion object { + + @JvmStatic fun ofNumber(number: Double) = AspectRatio(number = number) + + @JvmStatic fun ofString(string: String) = AspectRatio(string = string) + } + + /** + * An interface that defines how to map each variant of [AspectRatio] to a value of type + * [T]. + */ + interface Visitor { + + fun visitNumber(number: Double): T + + fun visitString(string: String): T + + /** + * Maps an unknown variant of [AspectRatio] to a value of type [T]. + * + * An instance of [AspectRatio] can contain an unknown variant if it was deserialized + * from data that doesn't match any known variant. For example, if the SDK is on an + * older version than the API, then the API may respond with new variants that the SDK + * is unaware of. + * + * @throws ImageKitInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw ImageKitInvalidDataException("Unknown AspectRatio: $json") + } + } + + internal class Deserializer : BaseDeserializer(AspectRatio::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): AspectRatio { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + AspectRatio(number = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + AspectRatio(string = it, _json = json) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely incompatible with + // all the possible variants (e.g. deserializing from object). + 0 -> AspectRatio(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then use the first + // completely valid match, or simply the first match if none are completely + // valid. + else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() + } + } + } + + internal class Serializer : BaseSerializer(AspectRatio::class) { + + override fun serialize( + value: AspectRatio, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.number != null -> generator.writeObject(value.number) + value.string != null -> generator.writeObject(value.string) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid AspectRatio") + } + } + } + } + + /** + * Specifies the audio codec, e.g., `aac`, `opus`, or `none`. See + * [Audio codec](https://imagekit.io/docs/video-optimization#audio-codec---ac). + */ + class AudioCodec @JsonCreator private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is on an + * older version than the API, then the API may respond with new members that the SDK is + * unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val AAC = of("aac") + + @JvmField val OPUS = of("opus") + + @JvmField val NONE = of("none") + + @JvmStatic fun of(value: String) = AudioCodec(JsonField.of(value)) + } + + /** An enum containing [AudioCodec]'s known values. */ + enum class Known { + AAC, + OPUS, + NONE, + } + + /** + * An enum containing [AudioCodec]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [AudioCodec] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if the + * SDK is on an older version than the API, then the API may respond with new members that + * the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + AAC, + OPUS, + NONE, + /** + * An enum member indicating that [AudioCodec] was instantiated with an unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] + * if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you want + * to throw for the unknown case. + */ + fun value(): Value = + when (this) { + AAC -> Value.AAC + OPUS -> Value.OPUS + NONE -> Value.NONE + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and don't + * want to throw for the unknown case. + * + * @throws ImageKitInvalidDataException if this class instance's value is a not a known + * member. + */ + fun known(): Known = + when (this) { + AAC -> Known.AAC + OPUS -> Known.OPUS + NONE -> Known.NONE + else -> throw ImageKitInvalidDataException("Unknown AudioCodec: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for debugging + * and generally doesn't throw. + * + * @throws ImageKitInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + ImageKitInvalidDataException("Value is not a String") + } + + private var validated: Boolean = false + + fun validate(): AudioCodec = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is AudioCodec && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + /** + * Automatically enhances the contrast of an image (contrast stretch). See + * [Contrast Stretch](https://imagekit.io/docs/effects-and-enhancements#contrast-stretch---e-contrast). + */ + class ContrastStretch @JsonCreator private constructor(private val value: JsonField) : + Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is on an + * older version than the API, then the API may respond with new members that the SDK is + * unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val TRUE = of(true) + + @JvmStatic fun of(value: Boolean) = ContrastStretch(JsonField.of(value)) + } + + /** An enum containing [ContrastStretch]'s known values. */ + enum class Known { + TRUE + } + + /** + * An enum containing [ContrastStretch]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [ContrastStretch] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if the + * SDK is on an older version than the API, then the API may respond with new members that + * the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + TRUE, + /** + * An enum member indicating that [ContrastStretch] was instantiated with an unknown + * value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] + * if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you want + * to throw for the unknown case. + */ + fun value(): Value = + when (this) { + TRUE -> Value.TRUE + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and don't + * want to throw for the unknown case. + * + * @throws ImageKitInvalidDataException if this class instance's value is a not a known + * member. + */ + fun known(): Known = + when (this) { + TRUE -> Known.TRUE + else -> throw ImageKitInvalidDataException("Unknown ContrastStretch: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * @throws ImageKitInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asBoolean(): Boolean = + _value().asBoolean().orElseThrow { + ImageKitInvalidDataException("Value is not a Boolean") + } + + private var validated: Boolean = false + + fun validate(): ContrastStretch = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ContrastStretch && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + /** + * Crop modes for image resizing. See + * [Crop modes & focus](https://imagekit.io/docs/image-resize-and-crop#crop-crop-modes--focus). + */ + class Crop @JsonCreator private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is on an + * older version than the API, then the API may respond with new members that the SDK is + * unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val FORCE = of("force") + + @JvmField val AT_MAX = of("at_max") + + @JvmField val AT_MAX_ENLARGE = of("at_max_enlarge") + + @JvmField val AT_LEAST = of("at_least") + + @JvmField val MAINTAIN_RATIO = of("maintain_ratio") + + @JvmStatic fun of(value: String) = Crop(JsonField.of(value)) + } + + /** An enum containing [Crop]'s known values. */ + enum class Known { + FORCE, + AT_MAX, + AT_MAX_ENLARGE, + AT_LEAST, + MAINTAIN_RATIO, + } + + /** + * An enum containing [Crop]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [Crop] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if the + * SDK is on an older version than the API, then the API may respond with new members that + * the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + FORCE, + AT_MAX, + AT_MAX_ENLARGE, + AT_LEAST, + MAINTAIN_RATIO, + /** An enum member indicating that [Crop] was instantiated with an unknown value. */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] + * if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you want + * to throw for the unknown case. + */ + fun value(): Value = + when (this) { + FORCE -> Value.FORCE + AT_MAX -> Value.AT_MAX + AT_MAX_ENLARGE -> Value.AT_MAX_ENLARGE + AT_LEAST -> Value.AT_LEAST + MAINTAIN_RATIO -> Value.MAINTAIN_RATIO + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and don't + * want to throw for the unknown case. + * + * @throws ImageKitInvalidDataException if this class instance's value is a not a known + * member. + */ + fun known(): Known = + when (this) { + FORCE -> Known.FORCE + AT_MAX -> Known.AT_MAX + AT_MAX_ENLARGE -> Known.AT_MAX_ENLARGE + AT_LEAST -> Known.AT_LEAST + MAINTAIN_RATIO -> Known.MAINTAIN_RATIO + else -> throw ImageKitInvalidDataException("Unknown Crop: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for debugging + * and generally doesn't throw. + * + * @throws ImageKitInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + ImageKitInvalidDataException("Value is not a String") + } + + private var validated: Boolean = false + + fun validate(): Crop = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Crop && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + /** + * Additional crop modes for image resizing. See + * [Crop modes & focus](https://imagekit.io/docs/image-resize-and-crop#crop-crop-modes--focus). + */ + class CropMode @JsonCreator private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is on an + * older version than the API, then the API may respond with new members that the SDK is + * unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val PAD_RESIZE = of("pad_resize") + + @JvmField val EXTRACT = of("extract") + + @JvmField val PAD_EXTRACT = of("pad_extract") + + @JvmStatic fun of(value: String) = CropMode(JsonField.of(value)) + } + + /** An enum containing [CropMode]'s known values. */ + enum class Known { + PAD_RESIZE, + EXTRACT, + PAD_EXTRACT, + } + + /** + * An enum containing [CropMode]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [CropMode] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if the + * SDK is on an older version than the API, then the API may respond with new members that + * the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + PAD_RESIZE, + EXTRACT, + PAD_EXTRACT, + /** An enum member indicating that [CropMode] was instantiated with an unknown value. */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] + * if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you want + * to throw for the unknown case. + */ + fun value(): Value = + when (this) { + PAD_RESIZE -> Value.PAD_RESIZE + EXTRACT -> Value.EXTRACT + PAD_EXTRACT -> Value.PAD_EXTRACT + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and don't + * want to throw for the unknown case. + * + * @throws ImageKitInvalidDataException if this class instance's value is a not a known + * member. + */ + fun known(): Known = + when (this) { + PAD_RESIZE -> Known.PAD_RESIZE + EXTRACT -> Known.EXTRACT + PAD_EXTRACT -> Known.PAD_EXTRACT + else -> throw ImageKitInvalidDataException("Unknown CropMode: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for debugging + * and generally doesn't throw. + * + * @throws ImageKitInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + ImageKitInvalidDataException("Value is not a String") + } + + private var validated: Boolean = false + + fun validate(): CropMode = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is CropMode && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + /** + * Specifies the duration (in seconds) for trimming videos, e.g., `5` or `10.5`. Typically used + * with startOffset to indicate the length from the start offset. Arithmetic expressions are + * supported. See [Trim videos – Duration](https://imagekit.io/docs/trim-videos#duration---du). + */ + @JsonDeserialize(using = Duration.Deserializer::class) + @JsonSerialize(using = Duration.Serializer::class) + class Duration + private constructor( + private val number: Double? = null, + private val string: String? = null, + private val _json: JsonValue? = null, + ) { + + fun number(): Optional = Optional.ofNullable(number) + + fun string(): Optional = Optional.ofNullable(string) + + fun isNumber(): Boolean = number != null + + fun isString(): Boolean = string != null + + fun asNumber(): Double = number.getOrThrow("number") + + fun asString(): String = string.getOrThrow("string") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + number != null -> visitor.visitNumber(number) + string != null -> visitor.visitString(string) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): Duration = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitNumber(number: Double) {} + + override fun visitString(string: String) {} + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitNumber(number: Double) = 1 + + override fun visitString(string: String) = 1 + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Duration && number == other.number && string == other.string + } + + override fun hashCode(): Int = Objects.hash(number, string) + + override fun toString(): String = + when { + number != null -> "Duration{number=$number}" + string != null -> "Duration{string=$string}" + _json != null -> "Duration{_unknown=$_json}" + else -> throw IllegalStateException("Invalid Duration") + } + + companion object { + + @JvmStatic fun ofNumber(number: Double) = Duration(number = number) + + @JvmStatic fun ofString(string: String) = Duration(string = string) + } + + /** + * An interface that defines how to map each variant of [Duration] to a value of type [T]. + */ + interface Visitor { + + fun visitNumber(number: Double): T + + fun visitString(string: String): T + + /** + * Maps an unknown variant of [Duration] to a value of type [T]. + * + * An instance of [Duration] can contain an unknown variant if it was deserialized from + * data that doesn't match any known variant. For example, if the SDK is on an older + * version than the API, then the API may respond with new variants that the SDK is + * unaware of. + * + * @throws ImageKitInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw ImageKitInvalidDataException("Unknown Duration: $json") + } + } + + internal class Deserializer : BaseDeserializer(Duration::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): Duration { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + Duration(number = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + Duration(string = it, _json = json) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely incompatible with + // all the possible variants (e.g. deserializing from object). + 0 -> Duration(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then use the first + // completely valid match, or simply the first match if none are completely + // valid. + else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() + } + } + } + + internal class Serializer : BaseSerializer(Duration::class) { + + override fun serialize( + value: Duration, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.number != null -> generator.writeObject(value.number) + value.string != null -> generator.writeObject(value.string) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid Duration") + } + } + } + } + + /** + * Specifies the end offset (in seconds) for trimming videos, e.g., `5` or `10.5`. Typically + * used with startOffset to define a time window. Arithmetic expressions are supported. See + * [Trim videos – End offset](https://imagekit.io/docs/trim-videos#end-offset---eo). + */ + @JsonDeserialize(using = EndOffset.Deserializer::class) + @JsonSerialize(using = EndOffset.Serializer::class) + class EndOffset + private constructor( + private val number: Double? = null, + private val string: String? = null, + private val _json: JsonValue? = null, + ) { + + fun number(): Optional = Optional.ofNullable(number) + + fun string(): Optional = Optional.ofNullable(string) + + fun isNumber(): Boolean = number != null + + fun isString(): Boolean = string != null + + fun asNumber(): Double = number.getOrThrow("number") + + fun asString(): String = string.getOrThrow("string") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + number != null -> visitor.visitNumber(number) + string != null -> visitor.visitString(string) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): EndOffset = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitNumber(number: Double) {} + + override fun visitString(string: String) {} + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitNumber(number: Double) = 1 + + override fun visitString(string: String) = 1 + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is EndOffset && number == other.number && string == other.string + } + + override fun hashCode(): Int = Objects.hash(number, string) + + override fun toString(): String = + when { + number != null -> "EndOffset{number=$number}" + string != null -> "EndOffset{string=$string}" + _json != null -> "EndOffset{_unknown=$_json}" + else -> throw IllegalStateException("Invalid EndOffset") + } + + companion object { + + @JvmStatic fun ofNumber(number: Double) = EndOffset(number = number) + + @JvmStatic fun ofString(string: String) = EndOffset(string = string) + } + + /** + * An interface that defines how to map each variant of [EndOffset] to a value of type [T]. + */ + interface Visitor { + + fun visitNumber(number: Double): T + + fun visitString(string: String): T + + /** + * Maps an unknown variant of [EndOffset] to a value of type [T]. + * + * An instance of [EndOffset] can contain an unknown variant if it was deserialized from + * data that doesn't match any known variant. For example, if the SDK is on an older + * version than the API, then the API may respond with new variants that the SDK is + * unaware of. + * + * @throws ImageKitInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw ImageKitInvalidDataException("Unknown EndOffset: $json") + } + } + + internal class Deserializer : BaseDeserializer(EndOffset::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): EndOffset { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + EndOffset(number = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + EndOffset(string = it, _json = json) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely incompatible with + // all the possible variants (e.g. deserializing from object). + 0 -> EndOffset(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then use the first + // completely valid match, or simply the first match if none are completely + // valid. + else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() + } + } + } + + internal class Serializer : BaseSerializer(EndOffset::class) { + + override fun serialize( + value: EndOffset, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.number != null -> generator.writeObject(value.number) + value.string != null -> generator.writeObject(value.string) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid EndOffset") + } + } + } + } + + /** + * Flips or mirrors an image either horizontally, vertically, or both. Acceptable values: `h` + * (horizontal), `v` (vertical), `h_v` (horizontal and vertical), or `v_h`. See + * [Flip](https://imagekit.io/docs/effects-and-enhancements#flip---fl). + */ + class Flip @JsonCreator private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is on an + * older version than the API, then the API may respond with new members that the SDK is + * unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val H = of("h") + + @JvmField val V = of("v") + + @JvmField val H_V = of("h_v") + + @JvmField val V_H = of("v_h") + + @JvmStatic fun of(value: String) = Flip(JsonField.of(value)) + } + + /** An enum containing [Flip]'s known values. */ + enum class Known { + H, + V, + H_V, + V_H, + } + + /** + * An enum containing [Flip]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [Flip] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if the + * SDK is on an older version than the API, then the API may respond with new members that + * the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + H, + V, + H_V, + V_H, + /** An enum member indicating that [Flip] was instantiated with an unknown value. */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] + * if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you want + * to throw for the unknown case. + */ + fun value(): Value = + when (this) { + H -> Value.H + V -> Value.V + H_V -> Value.H_V + V_H -> Value.V_H + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and don't + * want to throw for the unknown case. + * + * @throws ImageKitInvalidDataException if this class instance's value is a not a known + * member. + */ + fun known(): Known = + when (this) { + H -> Known.H + V -> Known.V + H_V -> Known.H_V + V_H -> Known.V_H + else -> throw ImageKitInvalidDataException("Unknown Flip: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for debugging + * and generally doesn't throw. + * + * @throws ImageKitInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + ImageKitInvalidDataException("Value is not a String") + } + + private var validated: Boolean = false + + fun validate(): Flip = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Flip && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + /** + * Specifies the output format for images or videos, e.g., `jpg`, `png`, `webp`, `mp4`, or + * `auto`. You can also pass `orig` for images to return the original format. ImageKit + * automatically delivers images and videos in the optimal format based on device support unless + * overridden by the dashboard settings or the format parameter. See + * [Image format](https://imagekit.io/docs/image-optimization#format---f) and + * [Video format](https://imagekit.io/docs/video-optimization#format---f). + */ + class Format @JsonCreator private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is on an + * older version than the API, then the API may respond with new members that the SDK is + * unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val AUTO = of("auto") + + @JvmField val WEBP = of("webp") + + @JvmField val JPG = of("jpg") + + @JvmField val JPEG = of("jpeg") + + @JvmField val PNG = of("png") + + @JvmField val GIF = of("gif") + + @JvmField val SVG = of("svg") + + @JvmField val MP4 = of("mp4") + + @JvmField val WEBM = of("webm") + + @JvmField val AVIF = of("avif") + + @JvmField val ORIG = of("orig") + + @JvmStatic fun of(value: String) = Format(JsonField.of(value)) + } + + /** An enum containing [Format]'s known values. */ + enum class Known { + AUTO, + WEBP, + JPG, + JPEG, + PNG, + GIF, + SVG, + MP4, + WEBM, + AVIF, + ORIG, + } + + /** + * An enum containing [Format]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [Format] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if the + * SDK is on an older version than the API, then the API may respond with new members that + * the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + AUTO, + WEBP, + JPG, + JPEG, + PNG, + GIF, + SVG, + MP4, + WEBM, + AVIF, + ORIG, + /** An enum member indicating that [Format] was instantiated with an unknown value. */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] + * if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you want + * to throw for the unknown case. + */ + fun value(): Value = + when (this) { + AUTO -> Value.AUTO + WEBP -> Value.WEBP + JPG -> Value.JPG + JPEG -> Value.JPEG + PNG -> Value.PNG + GIF -> Value.GIF + SVG -> Value.SVG + MP4 -> Value.MP4 + WEBM -> Value.WEBM + AVIF -> Value.AVIF + ORIG -> Value.ORIG + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and don't + * want to throw for the unknown case. + * + * @throws ImageKitInvalidDataException if this class instance's value is a not a known + * member. + */ + fun known(): Known = + when (this) { + AUTO -> Known.AUTO + WEBP -> Known.WEBP + JPG -> Known.JPG + JPEG -> Known.JPEG + PNG -> Known.PNG + GIF -> Known.GIF + SVG -> Known.SVG + MP4 -> Known.MP4 + WEBM -> Known.WEBM + AVIF -> Known.AVIF + ORIG -> Known.ORIG + else -> throw ImageKitInvalidDataException("Unknown Format: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for debugging + * and generally doesn't throw. + * + * @throws ImageKitInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + ImageKitInvalidDataException("Value is not a String") + } + + private var validated: Boolean = false + + fun validate(): Format = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Format && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + /** + * Creates a linear gradient with two colors. Pass `true` for a default gradient, or provide a + * string for a custom gradient. See + * [Gradient](https://imagekit.io/docs/effects-and-enhancements#gradient---e-gradient). + */ + @JsonDeserialize(using = Gradient.Deserializer::class) + @JsonSerialize(using = Gradient.Serializer::class) + class Gradient + private constructor( + private val true_: JsonValue? = null, + private val string: String? = null, + private val _json: JsonValue? = null, + ) { + + fun true_(): Optional = Optional.ofNullable(true_) + + fun string(): Optional = Optional.ofNullable(string) + + fun isTrue(): Boolean = true_ != null + + fun isString(): Boolean = string != null + + fun asTrue(): JsonValue = true_.getOrThrow("true_") + + fun asString(): String = string.getOrThrow("string") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + true_ != null -> visitor.visitTrue(true_) + string != null -> visitor.visitString(string) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): Gradient = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitTrue(true_: JsonValue) { + true_.let { + if (it != JsonValue.from(true)) { + throw ImageKitInvalidDataException( + "'true_' is invalid, received $it" + ) + } + } + } + + override fun visitString(string: String) {} + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitTrue(true_: JsonValue) = + true_.let { if (it == JsonValue.from(true)) 1 else 0 } + + override fun visitString(string: String) = 1 + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Gradient && true_ == other.true_ && string == other.string + } + + override fun hashCode(): Int = Objects.hash(true_, string) + + override fun toString(): String = + when { + true_ != null -> "Gradient{true_=$true_}" + string != null -> "Gradient{string=$string}" + _json != null -> "Gradient{_unknown=$_json}" + else -> throw IllegalStateException("Invalid Gradient") + } + + companion object { + + @JvmStatic fun ofTrue() = Gradient(true_ = JsonValue.from(true)) + + @JvmStatic fun ofString(string: String) = Gradient(string = string) + } + + /** + * An interface that defines how to map each variant of [Gradient] to a value of type [T]. + */ + interface Visitor { + + fun visitTrue(true_: JsonValue): T + + fun visitString(string: String): T + + /** + * Maps an unknown variant of [Gradient] to a value of type [T]. + * + * An instance of [Gradient] can contain an unknown variant if it was deserialized from + * data that doesn't match any known variant. For example, if the SDK is on an older + * version than the API, then the API may respond with new variants that the SDK is + * unaware of. + * + * @throws ImageKitInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw ImageKitInvalidDataException("Unknown Gradient: $json") + } + } + + internal class Deserializer : BaseDeserializer(Gradient::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): Gradient { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef()) + ?.let { Gradient(true_ = it, _json = json) } + ?.takeIf { it.isValid() }, + tryDeserialize(node, jacksonTypeRef())?.let { + Gradient(string = it, _json = json) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely incompatible with + // all the possible variants (e.g. deserializing from object). + 0 -> Gradient(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then use the first + // completely valid match, or simply the first match if none are completely + // valid. + else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() + } + } + } + + internal class Serializer : BaseSerializer(Gradient::class) { + + override fun serialize( + value: Gradient, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.true_ != null -> generator.writeObject(value.true_) + value.string != null -> generator.writeObject(value.string) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid Gradient") + } + } + } + } + + /** + * Enables a grayscale effect for images. See + * [Grayscale](https://imagekit.io/docs/effects-and-enhancements#grayscale---e-grayscale). + */ + class Grayscale @JsonCreator private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is on an + * older version than the API, then the API may respond with new members that the SDK is + * unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val TRUE = of(true) + + @JvmStatic fun of(value: Boolean) = Grayscale(JsonField.of(value)) + } + + /** An enum containing [Grayscale]'s known values. */ + enum class Known { + TRUE + } + + /** + * An enum containing [Grayscale]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [Grayscale] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if the + * SDK is on an older version than the API, then the API may respond with new members that + * the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + TRUE, + /** + * An enum member indicating that [Grayscale] was instantiated with an unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] + * if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you want + * to throw for the unknown case. + */ + fun value(): Value = + when (this) { + TRUE -> Value.TRUE + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and don't + * want to throw for the unknown case. + * + * @throws ImageKitInvalidDataException if this class instance's value is a not a known + * member. + */ + fun known(): Known = + when (this) { + TRUE -> Known.TRUE + else -> throw ImageKitInvalidDataException("Unknown Grayscale: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * @throws ImageKitInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asBoolean(): Boolean = + _value().asBoolean().orElseThrow { + ImageKitInvalidDataException("Value is not a Boolean") + } + + private var validated: Boolean = false + + fun validate(): Grayscale = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Grayscale && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + /** + * Specifies the height of the output. If a value between 0 and 1 is provided, it is treated as + * a percentage (e.g., `0.5` represents 50% of the original height). You can also supply + * arithmetic expressions (e.g., `ih_mul_0.5`). Height transformation – + * [Images](https://imagekit.io/docs/image-resize-and-crop#height---h) · + * [Videos](https://imagekit.io/docs/video-resize-and-crop#height---h) + */ + @JsonDeserialize(using = Height.Deserializer::class) + @JsonSerialize(using = Height.Serializer::class) + class Height + private constructor( + private val number: Double? = null, + private val string: String? = null, + private val _json: JsonValue? = null, + ) { + + fun number(): Optional = Optional.ofNullable(number) + + fun string(): Optional = Optional.ofNullable(string) + + fun isNumber(): Boolean = number != null + + fun isString(): Boolean = string != null + + fun asNumber(): Double = number.getOrThrow("number") + + fun asString(): String = string.getOrThrow("string") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + number != null -> visitor.visitNumber(number) + string != null -> visitor.visitString(string) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): Height = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitNumber(number: Double) {} + + override fun visitString(string: String) {} + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitNumber(number: Double) = 1 + + override fun visitString(string: String) = 1 + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Height && number == other.number && string == other.string + } + + override fun hashCode(): Int = Objects.hash(number, string) + + override fun toString(): String = + when { + number != null -> "Height{number=$number}" + string != null -> "Height{string=$string}" + _json != null -> "Height{_unknown=$_json}" + else -> throw IllegalStateException("Invalid Height") + } + + companion object { + + @JvmStatic fun ofNumber(number: Double) = Height(number = number) + + @JvmStatic fun ofString(string: String) = Height(string = string) + } + + /** An interface that defines how to map each variant of [Height] to a value of type [T]. */ + interface Visitor { + + fun visitNumber(number: Double): T + + fun visitString(string: String): T + + /** + * Maps an unknown variant of [Height] to a value of type [T]. + * + * An instance of [Height] can contain an unknown variant if it was deserialized from + * data that doesn't match any known variant. For example, if the SDK is on an older + * version than the API, then the API may respond with new variants that the SDK is + * unaware of. + * + * @throws ImageKitInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw ImageKitInvalidDataException("Unknown Height: $json") + } + } + + internal class Deserializer : BaseDeserializer(Height::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): Height { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + Height(number = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + Height(string = it, _json = json) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely incompatible with + // all the possible variants (e.g. deserializing from object). + 0 -> Height(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then use the first + // completely valid match, or simply the first match if none are completely + // valid. + else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() + } + } + } + + internal class Serializer : BaseSerializer(Height::class) { + + override fun serialize( + value: Height, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.number != null -> generator.writeObject(value.number) + value.string != null -> generator.writeObject(value.string) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid Height") + } + } + } + } + + /** + * Extracts a specific page or frame from multi-page or layered files (PDF, PSD, AI). For + * example, specify by number (e.g., `2`), a range (e.g., `3-4` for the 2nd and 3rd layers), or + * by name (e.g., `name-layer-4` for a PSD layer). See + * [Thumbnail extraction](https://imagekit.io/docs/vector-and-animated-images#get-thumbnail-from-psd-pdf-ai-eps-and-animated-files). + */ + @JsonDeserialize(using = Page.Deserializer::class) + @JsonSerialize(using = Page.Serializer::class) + class Page + private constructor( + private val number: Double? = null, + private val string: String? = null, + private val _json: JsonValue? = null, + ) { + + fun number(): Optional = Optional.ofNullable(number) + + fun string(): Optional = Optional.ofNullable(string) + + fun isNumber(): Boolean = number != null + + fun isString(): Boolean = string != null + + fun asNumber(): Double = number.getOrThrow("number") + + fun asString(): String = string.getOrThrow("string") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + number != null -> visitor.visitNumber(number) + string != null -> visitor.visitString(string) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): Page = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitNumber(number: Double) {} + + override fun visitString(string: String) {} + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitNumber(number: Double) = 1 + + override fun visitString(string: String) = 1 + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Page && number == other.number && string == other.string + } + + override fun hashCode(): Int = Objects.hash(number, string) + + override fun toString(): String = + when { + number != null -> "Page{number=$number}" + string != null -> "Page{string=$string}" + _json != null -> "Page{_unknown=$_json}" + else -> throw IllegalStateException("Invalid Page") + } + + companion object { + + @JvmStatic fun ofNumber(number: Double) = Page(number = number) + + @JvmStatic fun ofString(string: String) = Page(string = string) + } + + /** An interface that defines how to map each variant of [Page] to a value of type [T]. */ + interface Visitor { + + fun visitNumber(number: Double): T + + fun visitString(string: String): T + + /** + * Maps an unknown variant of [Page] to a value of type [T]. + * + * An instance of [Page] can contain an unknown variant if it was deserialized from data + * that doesn't match any known variant. For example, if the SDK is on an older version + * than the API, then the API may respond with new variants that the SDK is unaware of. + * + * @throws ImageKitInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw ImageKitInvalidDataException("Unknown Page: $json") + } + } + + internal class Deserializer : BaseDeserializer(Page::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): Page { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + Page(number = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + Page(string = it, _json = json) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely incompatible with + // all the possible variants (e.g. deserializing from object). + 0 -> Page(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then use the first + // completely valid match, or simply the first match if none are completely + // valid. + else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() + } + } + } + + internal class Serializer : BaseSerializer(Page::class) { + + override fun serialize( + value: Page, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.number != null -> generator.writeObject(value.number) + value.string != null -> generator.writeObject(value.string) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid Page") + } + } + } + } + + /** + * Specifies the corner radius for rounded corners (e.g., 20) or `max` for circular or oval + * shape. See [Radius](https://imagekit.io/docs/effects-and-enhancements#radius---r). + */ + @JsonDeserialize(using = Radius.Deserializer::class) + @JsonSerialize(using = Radius.Serializer::class) + class Radius + private constructor( + private val number: Double? = null, + private val max: JsonValue? = null, + private val _json: JsonValue? = null, + ) { + + fun number(): Optional = Optional.ofNullable(number) + + fun max(): Optional = Optional.ofNullable(max) + + fun isNumber(): Boolean = number != null + + fun isMax(): Boolean = max != null + + fun asNumber(): Double = number.getOrThrow("number") + + fun asMax(): JsonValue = max.getOrThrow("max") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + number != null -> visitor.visitNumber(number) + max != null -> visitor.visitMax(max) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): Radius = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitNumber(number: Double) {} + + override fun visitMax(max: JsonValue) { + max.let { + if (it != JsonValue.from("max")) { + throw ImageKitInvalidDataException("'max' is invalid, received $it") + } + } + } + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitNumber(number: Double) = 1 + + override fun visitMax(max: JsonValue) = + max.let { if (it == JsonValue.from("max")) 1 else 0 } + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Radius && number == other.number && max == other.max + } + + override fun hashCode(): Int = Objects.hash(number, max) + + override fun toString(): String = + when { + number != null -> "Radius{number=$number}" + max != null -> "Radius{max=$max}" + _json != null -> "Radius{_unknown=$_json}" + else -> throw IllegalStateException("Invalid Radius") + } + + companion object { + + @JvmStatic fun ofNumber(number: Double) = Radius(number = number) + + @JvmStatic fun ofMax() = Radius(max = JsonValue.from("max")) + } + + /** An interface that defines how to map each variant of [Radius] to a value of type [T]. */ + interface Visitor { + + fun visitNumber(number: Double): T + + fun visitMax(max: JsonValue): T + + /** + * Maps an unknown variant of [Radius] to a value of type [T]. + * + * An instance of [Radius] can contain an unknown variant if it was deserialized from + * data that doesn't match any known variant. For example, if the SDK is on an older + * version than the API, then the API may respond with new variants that the SDK is + * unaware of. + * + * @throws ImageKitInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw ImageKitInvalidDataException("Unknown Radius: $json") + } + } + + internal class Deserializer : BaseDeserializer(Radius::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): Radius { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef()) + ?.let { Radius(max = it, _json = json) } + ?.takeIf { it.isValid() }, + tryDeserialize(node, jacksonTypeRef())?.let { + Radius(number = it, _json = json) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely incompatible with + // all the possible variants (e.g. deserializing from object). + 0 -> Radius(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then use the first + // completely valid match, or simply the first match if none are completely + // valid. + else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() + } + } + } + + internal class Serializer : BaseSerializer(Radius::class) { + + override fun serialize( + value: Radius, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.number != null -> generator.writeObject(value.number) + value.max != null -> generator.writeObject(value.max) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid Radius") + } + } + } + } + + /** + * Specifies the rotation angle in degrees. Positive values rotate the image clockwise; you can + * also use, for example, `N40` for counterclockwise rotation or `auto` to use the orientation + * specified in the image's EXIF data. For videos, only the following values are supported: 0, + * 90, 180, 270, or 360. See + * [Rotate](https://imagekit.io/docs/effects-and-enhancements#rotate---rt). + */ + @JsonDeserialize(using = Rotation.Deserializer::class) + @JsonSerialize(using = Rotation.Serializer::class) + class Rotation + private constructor( + private val number: Double? = null, + private val string: String? = null, + private val _json: JsonValue? = null, + ) { + + fun number(): Optional = Optional.ofNullable(number) + + fun string(): Optional = Optional.ofNullable(string) + + fun isNumber(): Boolean = number != null + + fun isString(): Boolean = string != null + + fun asNumber(): Double = number.getOrThrow("number") + + fun asString(): String = string.getOrThrow("string") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + number != null -> visitor.visitNumber(number) + string != null -> visitor.visitString(string) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): Rotation = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitNumber(number: Double) {} + + override fun visitString(string: String) {} + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitNumber(number: Double) = 1 + + override fun visitString(string: String) = 1 + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Rotation && number == other.number && string == other.string + } + + override fun hashCode(): Int = Objects.hash(number, string) + + override fun toString(): String = + when { + number != null -> "Rotation{number=$number}" + string != null -> "Rotation{string=$string}" + _json != null -> "Rotation{_unknown=$_json}" + else -> throw IllegalStateException("Invalid Rotation") + } + + companion object { + + @JvmStatic fun ofNumber(number: Double) = Rotation(number = number) + + @JvmStatic fun ofString(string: String) = Rotation(string = string) + } + + /** + * An interface that defines how to map each variant of [Rotation] to a value of type [T]. + */ + interface Visitor { + + fun visitNumber(number: Double): T + + fun visitString(string: String): T + + /** + * Maps an unknown variant of [Rotation] to a value of type [T]. + * + * An instance of [Rotation] can contain an unknown variant if it was deserialized from + * data that doesn't match any known variant. For example, if the SDK is on an older + * version than the API, then the API may respond with new variants that the SDK is + * unaware of. + * + * @throws ImageKitInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw ImageKitInvalidDataException("Unknown Rotation: $json") + } + } + + internal class Deserializer : BaseDeserializer(Rotation::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): Rotation { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + Rotation(number = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + Rotation(string = it, _json = json) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely incompatible with + // all the possible variants (e.g. deserializing from object). + 0 -> Rotation(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then use the first + // completely valid match, or simply the first match if none are completely + // valid. + else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() + } + } + } + + internal class Serializer : BaseSerializer(Rotation::class) { + + override fun serialize( + value: Rotation, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.number != null -> generator.writeObject(value.number) + value.string != null -> generator.writeObject(value.string) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid Rotation") + } + } + } + } + + /** + * Adds a shadow beneath solid objects in an image with a transparent background. For AI-based + * drop shadows, refer to aiDropShadow. Pass `true` for a default shadow, or provide a string + * for a custom shadow. See + * [Shadow](https://imagekit.io/docs/effects-and-enhancements#shadow---e-shadow). + */ + @JsonDeserialize(using = Shadow.Deserializer::class) + @JsonSerialize(using = Shadow.Serializer::class) + class Shadow + private constructor( + private val true_: JsonValue? = null, + private val string: String? = null, + private val _json: JsonValue? = null, + ) { + + fun true_(): Optional = Optional.ofNullable(true_) + + fun string(): Optional = Optional.ofNullable(string) + + fun isTrue(): Boolean = true_ != null + + fun isString(): Boolean = string != null + + fun asTrue(): JsonValue = true_.getOrThrow("true_") + + fun asString(): String = string.getOrThrow("string") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + true_ != null -> visitor.visitTrue(true_) + string != null -> visitor.visitString(string) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): Shadow = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitTrue(true_: JsonValue) { + true_.let { + if (it != JsonValue.from(true)) { + throw ImageKitInvalidDataException( + "'true_' is invalid, received $it" + ) + } + } + } + + override fun visitString(string: String) {} + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitTrue(true_: JsonValue) = + true_.let { if (it == JsonValue.from(true)) 1 else 0 } + + override fun visitString(string: String) = 1 + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Shadow && true_ == other.true_ && string == other.string + } + + override fun hashCode(): Int = Objects.hash(true_, string) + + override fun toString(): String = + when { + true_ != null -> "Shadow{true_=$true_}" + string != null -> "Shadow{string=$string}" + _json != null -> "Shadow{_unknown=$_json}" + else -> throw IllegalStateException("Invalid Shadow") + } + + companion object { + + @JvmStatic fun ofTrue() = Shadow(true_ = JsonValue.from(true)) + + @JvmStatic fun ofString(string: String) = Shadow(string = string) + } + + /** An interface that defines how to map each variant of [Shadow] to a value of type [T]. */ + interface Visitor { + + fun visitTrue(true_: JsonValue): T + + fun visitString(string: String): T + + /** + * Maps an unknown variant of [Shadow] to a value of type [T]. + * + * An instance of [Shadow] can contain an unknown variant if it was deserialized from + * data that doesn't match any known variant. For example, if the SDK is on an older + * version than the API, then the API may respond with new variants that the SDK is + * unaware of. + * + * @throws ImageKitInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw ImageKitInvalidDataException("Unknown Shadow: $json") + } + } + + internal class Deserializer : BaseDeserializer(Shadow::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): Shadow { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef()) + ?.let { Shadow(true_ = it, _json = json) } + ?.takeIf { it.isValid() }, + tryDeserialize(node, jacksonTypeRef())?.let { + Shadow(string = it, _json = json) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely incompatible with + // all the possible variants (e.g. deserializing from object). + 0 -> Shadow(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then use the first + // completely valid match, or simply the first match if none are completely + // valid. + else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() + } + } + } + + internal class Serializer : BaseSerializer(Shadow::class) { + + override fun serialize( + value: Shadow, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.true_ != null -> generator.writeObject(value.true_) + value.string != null -> generator.writeObject(value.string) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid Shadow") + } + } + } + } + + /** + * Sharpens the input image, highlighting edges and finer details. Pass `true` for default + * sharpening, or provide a numeric value for custom sharpening. See + * [Sharpen](https://imagekit.io/docs/effects-and-enhancements#sharpen---e-sharpen). + */ + @JsonDeserialize(using = Sharpen.Deserializer::class) + @JsonSerialize(using = Sharpen.Serializer::class) + class Sharpen + private constructor( + private val true_: JsonValue? = null, + private val number: Double? = null, + private val _json: JsonValue? = null, + ) { + + fun true_(): Optional = Optional.ofNullable(true_) + + fun number(): Optional = Optional.ofNullable(number) + + fun isTrue(): Boolean = true_ != null + + fun isNumber(): Boolean = number != null + + fun asTrue(): JsonValue = true_.getOrThrow("true_") + + fun asNumber(): Double = number.getOrThrow("number") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + true_ != null -> visitor.visitTrue(true_) + number != null -> visitor.visitNumber(number) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): Sharpen = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitTrue(true_: JsonValue) { + true_.let { + if (it != JsonValue.from(true)) { + throw ImageKitInvalidDataException( + "'true_' is invalid, received $it" + ) + } + } + } + + override fun visitNumber(number: Double) {} + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitTrue(true_: JsonValue) = + true_.let { if (it == JsonValue.from(true)) 1 else 0 } + + override fun visitNumber(number: Double) = 1 + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Sharpen && true_ == other.true_ && number == other.number + } + + override fun hashCode(): Int = Objects.hash(true_, number) + + override fun toString(): String = + when { + true_ != null -> "Sharpen{true_=$true_}" + number != null -> "Sharpen{number=$number}" + _json != null -> "Sharpen{_unknown=$_json}" + else -> throw IllegalStateException("Invalid Sharpen") + } + + companion object { + + @JvmStatic fun ofTrue() = Sharpen(true_ = JsonValue.from(true)) + + @JvmStatic fun ofNumber(number: Double) = Sharpen(number = number) + } + + /** + * An interface that defines how to map each variant of [Sharpen] to a value of type [T]. + */ + interface Visitor { + + fun visitTrue(true_: JsonValue): T + + fun visitNumber(number: Double): T + + /** + * Maps an unknown variant of [Sharpen] to a value of type [T]. + * + * An instance of [Sharpen] can contain an unknown variant if it was deserialized from + * data that doesn't match any known variant. For example, if the SDK is on an older + * version than the API, then the API may respond with new variants that the SDK is + * unaware of. + * + * @throws ImageKitInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw ImageKitInvalidDataException("Unknown Sharpen: $json") + } + } + + internal class Deserializer : BaseDeserializer(Sharpen::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): Sharpen { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef()) + ?.let { Sharpen(true_ = it, _json = json) } + ?.takeIf { it.isValid() }, + tryDeserialize(node, jacksonTypeRef())?.let { + Sharpen(number = it, _json = json) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely incompatible with + // all the possible variants (e.g. deserializing from string). + 0 -> Sharpen(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then use the first + // completely valid match, or simply the first match if none are completely + // valid. + else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() + } + } + } + + internal class Serializer : BaseSerializer(Sharpen::class) { + + override fun serialize( + value: Sharpen, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.true_ != null -> generator.writeObject(value.true_) + value.number != null -> generator.writeObject(value.number) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid Sharpen") + } + } + } + } + + /** + * Specifies the start offset (in seconds) for trimming videos, e.g., `5` or `10.5`. Arithmetic + * expressions are also supported. See + * [Trim videos – Start offset](https://imagekit.io/docs/trim-videos#start-offset---so). + */ + @JsonDeserialize(using = StartOffset.Deserializer::class) + @JsonSerialize(using = StartOffset.Serializer::class) + class StartOffset + private constructor( + private val number: Double? = null, + private val string: String? = null, + private val _json: JsonValue? = null, + ) { + + fun number(): Optional = Optional.ofNullable(number) + + fun string(): Optional = Optional.ofNullable(string) + + fun isNumber(): Boolean = number != null + + fun isString(): Boolean = string != null + + fun asNumber(): Double = number.getOrThrow("number") + + fun asString(): String = string.getOrThrow("string") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + number != null -> visitor.visitNumber(number) + string != null -> visitor.visitString(string) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): StartOffset = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitNumber(number: Double) {} + + override fun visitString(string: String) {} + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitNumber(number: Double) = 1 + + override fun visitString(string: String) = 1 + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is StartOffset && number == other.number && string == other.string + } + + override fun hashCode(): Int = Objects.hash(number, string) + + override fun toString(): String = + when { + number != null -> "StartOffset{number=$number}" + string != null -> "StartOffset{string=$string}" + _json != null -> "StartOffset{_unknown=$_json}" + else -> throw IllegalStateException("Invalid StartOffset") + } + + companion object { + + @JvmStatic fun ofNumber(number: Double) = StartOffset(number = number) + + @JvmStatic fun ofString(string: String) = StartOffset(string = string) + } + + /** + * An interface that defines how to map each variant of [StartOffset] to a value of type + * [T]. + */ + interface Visitor { + + fun visitNumber(number: Double): T + + fun visitString(string: String): T + + /** + * Maps an unknown variant of [StartOffset] to a value of type [T]. + * + * An instance of [StartOffset] can contain an unknown variant if it was deserialized + * from data that doesn't match any known variant. For example, if the SDK is on an + * older version than the API, then the API may respond with new variants that the SDK + * is unaware of. + * + * @throws ImageKitInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw ImageKitInvalidDataException("Unknown StartOffset: $json") + } + } + + internal class Deserializer : BaseDeserializer(StartOffset::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): StartOffset { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + StartOffset(number = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + StartOffset(string = it, _json = json) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely incompatible with + // all the possible variants (e.g. deserializing from object). + 0 -> StartOffset(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then use the first + // completely valid match, or simply the first match if none are completely + // valid. + else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() + } + } + } + + internal class Serializer : BaseSerializer(StartOffset::class) { + + override fun serialize( + value: StartOffset, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.number != null -> generator.writeObject(value.number) + value.string != null -> generator.writeObject(value.string) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid StartOffset") + } + } + } + } + + /** + * Useful for images with a solid or nearly solid background and a central object. This + * parameter trims the background, leaving only the central object in the output image. See + * [Trim edges](https://imagekit.io/docs/effects-and-enhancements#trim-edges---t). + */ + @JsonDeserialize(using = Trim.Deserializer::class) + @JsonSerialize(using = Trim.Serializer::class) + class Trim + private constructor( + private val true_: JsonValue? = null, + private val number: Double? = null, + private val _json: JsonValue? = null, + ) { + + fun true_(): Optional = Optional.ofNullable(true_) + + fun number(): Optional = Optional.ofNullable(number) + + fun isTrue(): Boolean = true_ != null + + fun isNumber(): Boolean = number != null + + fun asTrue(): JsonValue = true_.getOrThrow("true_") + + fun asNumber(): Double = number.getOrThrow("number") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + true_ != null -> visitor.visitTrue(true_) + number != null -> visitor.visitNumber(number) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): Trim = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitTrue(true_: JsonValue) { + true_.let { + if (it != JsonValue.from(true)) { + throw ImageKitInvalidDataException( + "'true_' is invalid, received $it" + ) + } + } + } + + override fun visitNumber(number: Double) {} + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitTrue(true_: JsonValue) = + true_.let { if (it == JsonValue.from(true)) 1 else 0 } + + override fun visitNumber(number: Double) = 1 + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Trim && true_ == other.true_ && number == other.number + } + + override fun hashCode(): Int = Objects.hash(true_, number) + + override fun toString(): String = + when { + true_ != null -> "Trim{true_=$true_}" + number != null -> "Trim{number=$number}" + _json != null -> "Trim{_unknown=$_json}" + else -> throw IllegalStateException("Invalid Trim") + } + + companion object { + + @JvmStatic fun ofTrue() = Trim(true_ = JsonValue.from(true)) + + @JvmStatic fun ofNumber(number: Double) = Trim(number = number) + } + + /** An interface that defines how to map each variant of [Trim] to a value of type [T]. */ + interface Visitor { + + fun visitTrue(true_: JsonValue): T + + fun visitNumber(number: Double): T + + /** + * Maps an unknown variant of [Trim] to a value of type [T]. + * + * An instance of [Trim] can contain an unknown variant if it was deserialized from data + * that doesn't match any known variant. For example, if the SDK is on an older version + * than the API, then the API may respond with new variants that the SDK is unaware of. + * + * @throws ImageKitInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw ImageKitInvalidDataException("Unknown Trim: $json") + } + } + + internal class Deserializer : BaseDeserializer(Trim::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): Trim { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef()) + ?.let { Trim(true_ = it, _json = json) } + ?.takeIf { it.isValid() }, + tryDeserialize(node, jacksonTypeRef())?.let { + Trim(number = it, _json = json) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely incompatible with + // all the possible variants (e.g. deserializing from string). + 0 -> Trim(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then use the first + // completely valid match, or simply the first match if none are completely + // valid. + else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() + } + } + } + + internal class Serializer : BaseSerializer(Trim::class) { + + override fun serialize( + value: Trim, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.true_ != null -> generator.writeObject(value.true_) + value.number != null -> generator.writeObject(value.number) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid Trim") + } + } + } + } + + /** + * Applies Unsharp Masking (USM), an image sharpening technique. Pass `true` for a default + * unsharp mask, or provide a string for a custom unsharp mask. See + * [Unsharp Mask](https://imagekit.io/docs/effects-and-enhancements#unsharp-mask---e-usm). + */ + @JsonDeserialize(using = UnsharpMask.Deserializer::class) + @JsonSerialize(using = UnsharpMask.Serializer::class) + class UnsharpMask + private constructor( + private val true_: JsonValue? = null, + private val string: String? = null, + private val _json: JsonValue? = null, + ) { + + fun true_(): Optional = Optional.ofNullable(true_) + + fun string(): Optional = Optional.ofNullable(string) + + fun isTrue(): Boolean = true_ != null + + fun isString(): Boolean = string != null + + fun asTrue(): JsonValue = true_.getOrThrow("true_") + + fun asString(): String = string.getOrThrow("string") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + true_ != null -> visitor.visitTrue(true_) + string != null -> visitor.visitString(string) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): UnsharpMask = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitTrue(true_: JsonValue) { + true_.let { + if (it != JsonValue.from(true)) { + throw ImageKitInvalidDataException( + "'true_' is invalid, received $it" + ) + } + } + } + + override fun visitString(string: String) {} + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitTrue(true_: JsonValue) = + true_.let { if (it == JsonValue.from(true)) 1 else 0 } + + override fun visitString(string: String) = 1 + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is UnsharpMask && true_ == other.true_ && string == other.string + } + + override fun hashCode(): Int = Objects.hash(true_, string) + + override fun toString(): String = + when { + true_ != null -> "UnsharpMask{true_=$true_}" + string != null -> "UnsharpMask{string=$string}" + _json != null -> "UnsharpMask{_unknown=$_json}" + else -> throw IllegalStateException("Invalid UnsharpMask") + } + + companion object { + + @JvmStatic fun ofTrue() = UnsharpMask(true_ = JsonValue.from(true)) + + @JvmStatic fun ofString(string: String) = UnsharpMask(string = string) + } + + /** + * An interface that defines how to map each variant of [UnsharpMask] to a value of type + * [T]. + */ + interface Visitor { + + fun visitTrue(true_: JsonValue): T + + fun visitString(string: String): T + + /** + * Maps an unknown variant of [UnsharpMask] to a value of type [T]. + * + * An instance of [UnsharpMask] can contain an unknown variant if it was deserialized + * from data that doesn't match any known variant. For example, if the SDK is on an + * older version than the API, then the API may respond with new variants that the SDK + * is unaware of. + * + * @throws ImageKitInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw ImageKitInvalidDataException("Unknown UnsharpMask: $json") + } + } + + internal class Deserializer : BaseDeserializer(UnsharpMask::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): UnsharpMask { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef()) + ?.let { UnsharpMask(true_ = it, _json = json) } + ?.takeIf { it.isValid() }, + tryDeserialize(node, jacksonTypeRef())?.let { + UnsharpMask(string = it, _json = json) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely incompatible with + // all the possible variants (e.g. deserializing from object). + 0 -> UnsharpMask(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then use the first + // completely valid match, or simply the first match if none are completely + // valid. + else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() + } + } + } + + internal class Serializer : BaseSerializer(UnsharpMask::class) { + + override fun serialize( + value: UnsharpMask, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.true_ != null -> generator.writeObject(value.true_) + value.string != null -> generator.writeObject(value.string) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid UnsharpMask") + } + } + } + } + + /** + * Specifies the video codec, e.g., `h264`, `vp9`, `av1`, or `none`. See + * [Video codec](https://imagekit.io/docs/video-optimization#video-codec---vc). + */ + class VideoCodec @JsonCreator private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is on an + * older version than the API, then the API may respond with new members that the SDK is + * unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val H264 = of("h264") + + @JvmField val VP9 = of("vp9") + + @JvmField val AV1 = of("av1") + + @JvmField val NONE = of("none") + + @JvmStatic fun of(value: String) = VideoCodec(JsonField.of(value)) + } + + /** An enum containing [VideoCodec]'s known values. */ + enum class Known { + H264, + VP9, + AV1, + NONE, + } + + /** + * An enum containing [VideoCodec]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [VideoCodec] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if the + * SDK is on an older version than the API, then the API may respond with new members that + * the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + H264, + VP9, + AV1, + NONE, + /** + * An enum member indicating that [VideoCodec] was instantiated with an unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] + * if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you want + * to throw for the unknown case. + */ + fun value(): Value = + when (this) { + H264 -> Value.H264 + VP9 -> Value.VP9 + AV1 -> Value.AV1 + NONE -> Value.NONE + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and don't + * want to throw for the unknown case. + * + * @throws ImageKitInvalidDataException if this class instance's value is a not a known + * member. + */ + fun known(): Known = + when (this) { + H264 -> Known.H264 + VP9 -> Known.VP9 + AV1 -> Known.AV1 + NONE -> Known.NONE + else -> throw ImageKitInvalidDataException("Unknown VideoCodec: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for debugging + * and generally doesn't throw. + * + * @throws ImageKitInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + ImageKitInvalidDataException("Value is not a String") + } + + private var validated: Boolean = false + + fun validate(): VideoCodec = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is VideoCodec && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + /** + * Specifies the width of the output. If a value between 0 and 1 is provided, it is treated as a + * percentage (e.g., `0.4` represents 40% of the original width). You can also supply arithmetic + * expressions (e.g., `iw_div_2`). Width transformation – + * [Images](https://imagekit.io/docs/image-resize-and-crop#width---w) · + * [Videos](https://imagekit.io/docs/video-resize-and-crop#width---w) + */ + @JsonDeserialize(using = Width.Deserializer::class) + @JsonSerialize(using = Width.Serializer::class) + class Width + private constructor( + private val number: Double? = null, + private val string: String? = null, + private val _json: JsonValue? = null, + ) { + + fun number(): Optional = Optional.ofNullable(number) + + fun string(): Optional = Optional.ofNullable(string) + + fun isNumber(): Boolean = number != null + + fun isString(): Boolean = string != null + + fun asNumber(): Double = number.getOrThrow("number") + + fun asString(): String = string.getOrThrow("string") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + number != null -> visitor.visitNumber(number) + string != null -> visitor.visitString(string) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): Width = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitNumber(number: Double) {} + + override fun visitString(string: String) {} + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitNumber(number: Double) = 1 + + override fun visitString(string: String) = 1 + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Width && number == other.number && string == other.string + } + + override fun hashCode(): Int = Objects.hash(number, string) + + override fun toString(): String = + when { + number != null -> "Width{number=$number}" + string != null -> "Width{string=$string}" + _json != null -> "Width{_unknown=$_json}" + else -> throw IllegalStateException("Invalid Width") + } + + companion object { + + @JvmStatic fun ofNumber(number: Double) = Width(number = number) + + @JvmStatic fun ofString(string: String) = Width(string = string) + } + + /** An interface that defines how to map each variant of [Width] to a value of type [T]. */ + interface Visitor { + + fun visitNumber(number: Double): T + + fun visitString(string: String): T + + /** + * Maps an unknown variant of [Width] to a value of type [T]. + * + * An instance of [Width] can contain an unknown variant if it was deserialized from + * data that doesn't match any known variant. For example, if the SDK is on an older + * version than the API, then the API may respond with new variants that the SDK is + * unaware of. + * + * @throws ImageKitInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw ImageKitInvalidDataException("Unknown Width: $json") + } + } + + internal class Deserializer : BaseDeserializer(Width::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): Width { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + Width(number = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + Width(string = it, _json = json) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely incompatible with + // all the possible variants (e.g. deserializing from object). + 0 -> Width(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then use the first + // completely valid match, or simply the first match if none are completely + // valid. + else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() + } + } + } + + internal class Serializer : BaseSerializer(Width::class) { + + override fun serialize( + value: Width, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.number != null -> generator.writeObject(value.number) + value.string != null -> generator.writeObject(value.string) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid Width") + } + } + } + } + + /** + * Focus using cropped image coordinates - X coordinate. See + * [Focus using cropped coordinates](https://imagekit.io/docs/image-resize-and-crop#example---focus-using-cropped-image-coordinates). + */ + @JsonDeserialize(using = X.Deserializer::class) + @JsonSerialize(using = X.Serializer::class) + class X + private constructor( + private val number: Double? = null, + private val string: String? = null, + private val _json: JsonValue? = null, + ) { + + fun number(): Optional = Optional.ofNullable(number) + + fun string(): Optional = Optional.ofNullable(string) + + fun isNumber(): Boolean = number != null + + fun isString(): Boolean = string != null + + fun asNumber(): Double = number.getOrThrow("number") + + fun asString(): String = string.getOrThrow("string") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + number != null -> visitor.visitNumber(number) + string != null -> visitor.visitString(string) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): X = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitNumber(number: Double) {} + + override fun visitString(string: String) {} + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitNumber(number: Double) = 1 + + override fun visitString(string: String) = 1 + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is X && number == other.number && string == other.string + } + + override fun hashCode(): Int = Objects.hash(number, string) + + override fun toString(): String = + when { + number != null -> "X{number=$number}" + string != null -> "X{string=$string}" + _json != null -> "X{_unknown=$_json}" + else -> throw IllegalStateException("Invalid X") + } + + companion object { + + @JvmStatic fun ofNumber(number: Double) = X(number = number) + + @JvmStatic fun ofString(string: String) = X(string = string) + } + + /** An interface that defines how to map each variant of [X] to a value of type [T]. */ + interface Visitor { + + fun visitNumber(number: Double): T + + fun visitString(string: String): T + + /** + * Maps an unknown variant of [X] to a value of type [T]. + * + * An instance of [X] can contain an unknown variant if it was deserialized from data + * that doesn't match any known variant. For example, if the SDK is on an older version + * than the API, then the API may respond with new variants that the SDK is unaware of. + * + * @throws ImageKitInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw ImageKitInvalidDataException("Unknown X: $json") + } + } + + internal class Deserializer : BaseDeserializer(X::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): X { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + X(number = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + X(string = it, _json = json) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely incompatible with + // all the possible variants (e.g. deserializing from object). + 0 -> X(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then use the first + // completely valid match, or simply the first match if none are completely + // valid. + else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() + } + } + } + + internal class Serializer : BaseSerializer(X::class) { + + override fun serialize( + value: X, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.number != null -> generator.writeObject(value.number) + value.string != null -> generator.writeObject(value.string) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid X") + } + } + } + } + + /** + * Focus using cropped image coordinates - X center coordinate. See + * [Focus using cropped coordinates](https://imagekit.io/docs/image-resize-and-crop#example---focus-using-cropped-image-coordinates). + */ + @JsonDeserialize(using = XCenter.Deserializer::class) + @JsonSerialize(using = XCenter.Serializer::class) + class XCenter + private constructor( + private val number: Double? = null, + private val string: String? = null, + private val _json: JsonValue? = null, + ) { + + fun number(): Optional = Optional.ofNullable(number) + + fun string(): Optional = Optional.ofNullable(string) + + fun isNumber(): Boolean = number != null + + fun isString(): Boolean = string != null + + fun asNumber(): Double = number.getOrThrow("number") + + fun asString(): String = string.getOrThrow("string") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + number != null -> visitor.visitNumber(number) + string != null -> visitor.visitString(string) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): XCenter = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitNumber(number: Double) {} + + override fun visitString(string: String) {} + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitNumber(number: Double) = 1 + + override fun visitString(string: String) = 1 + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is XCenter && number == other.number && string == other.string + } + + override fun hashCode(): Int = Objects.hash(number, string) + + override fun toString(): String = + when { + number != null -> "XCenter{number=$number}" + string != null -> "XCenter{string=$string}" + _json != null -> "XCenter{_unknown=$_json}" + else -> throw IllegalStateException("Invalid XCenter") + } + + companion object { + + @JvmStatic fun ofNumber(number: Double) = XCenter(number = number) + + @JvmStatic fun ofString(string: String) = XCenter(string = string) + } + + /** + * An interface that defines how to map each variant of [XCenter] to a value of type [T]. + */ + interface Visitor { + + fun visitNumber(number: Double): T + + fun visitString(string: String): T + + /** + * Maps an unknown variant of [XCenter] to a value of type [T]. + * + * An instance of [XCenter] can contain an unknown variant if it was deserialized from + * data that doesn't match any known variant. For example, if the SDK is on an older + * version than the API, then the API may respond with new variants that the SDK is + * unaware of. + * + * @throws ImageKitInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw ImageKitInvalidDataException("Unknown XCenter: $json") + } + } + + internal class Deserializer : BaseDeserializer(XCenter::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): XCenter { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + XCenter(number = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + XCenter(string = it, _json = json) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely incompatible with + // all the possible variants (e.g. deserializing from object). + 0 -> XCenter(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then use the first + // completely valid match, or simply the first match if none are completely + // valid. + else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() + } + } + } + + internal class Serializer : BaseSerializer(XCenter::class) { + + override fun serialize( + value: XCenter, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.number != null -> generator.writeObject(value.number) + value.string != null -> generator.writeObject(value.string) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid XCenter") + } + } + } + } + + /** + * Focus using cropped image coordinates - Y coordinate. See + * [Focus using cropped coordinates](https://imagekit.io/docs/image-resize-and-crop#example---focus-using-cropped-image-coordinates). + */ + @JsonDeserialize(using = Y.Deserializer::class) + @JsonSerialize(using = Y.Serializer::class) + class Y + private constructor( + private val number: Double? = null, + private val string: String? = null, + private val _json: JsonValue? = null, + ) { + + fun number(): Optional = Optional.ofNullable(number) + + fun string(): Optional = Optional.ofNullable(string) + + fun isNumber(): Boolean = number != null + + fun isString(): Boolean = string != null + + fun asNumber(): Double = number.getOrThrow("number") + + fun asString(): String = string.getOrThrow("string") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + number != null -> visitor.visitNumber(number) + string != null -> visitor.visitString(string) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): Y = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitNumber(number: Double) {} + + override fun visitString(string: String) {} + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitNumber(number: Double) = 1 + + override fun visitString(string: String) = 1 + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Y && number == other.number && string == other.string + } + + override fun hashCode(): Int = Objects.hash(number, string) + + override fun toString(): String = + when { + number != null -> "Y{number=$number}" + string != null -> "Y{string=$string}" + _json != null -> "Y{_unknown=$_json}" + else -> throw IllegalStateException("Invalid Y") + } + + companion object { + + @JvmStatic fun ofNumber(number: Double) = Y(number = number) + + @JvmStatic fun ofString(string: String) = Y(string = string) + } + + /** An interface that defines how to map each variant of [Y] to a value of type [T]. */ + interface Visitor { + + fun visitNumber(number: Double): T + + fun visitString(string: String): T + + /** + * Maps an unknown variant of [Y] to a value of type [T]. + * + * An instance of [Y] can contain an unknown variant if it was deserialized from data + * that doesn't match any known variant. For example, if the SDK is on an older version + * than the API, then the API may respond with new variants that the SDK is unaware of. + * + * @throws ImageKitInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw ImageKitInvalidDataException("Unknown Y: $json") + } + } + + internal class Deserializer : BaseDeserializer(Y::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): Y { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + Y(number = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + Y(string = it, _json = json) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely incompatible with + // all the possible variants (e.g. deserializing from object). + 0 -> Y(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then use the first + // completely valid match, or simply the first match if none are completely + // valid. + else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() + } + } + } + + internal class Serializer : BaseSerializer(Y::class) { + + override fun serialize( + value: Y, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.number != null -> generator.writeObject(value.number) + value.string != null -> generator.writeObject(value.string) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid Y") + } + } + } + } + + /** + * Focus using cropped image coordinates - Y center coordinate. See + * [Focus using cropped coordinates](https://imagekit.io/docs/image-resize-and-crop#example---focus-using-cropped-image-coordinates). + */ + @JsonDeserialize(using = YCenter.Deserializer::class) + @JsonSerialize(using = YCenter.Serializer::class) + class YCenter + private constructor( + private val number: Double? = null, + private val string: String? = null, + private val _json: JsonValue? = null, + ) { + + fun number(): Optional = Optional.ofNullable(number) + + fun string(): Optional = Optional.ofNullable(string) + + fun isNumber(): Boolean = number != null + + fun isString(): Boolean = string != null + + fun asNumber(): Double = number.getOrThrow("number") + + fun asString(): String = string.getOrThrow("string") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + number != null -> visitor.visitNumber(number) + string != null -> visitor.visitString(string) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): YCenter = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitNumber(number: Double) {} + + override fun visitString(string: String) {} + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitNumber(number: Double) = 1 + + override fun visitString(string: String) = 1 + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is YCenter && number == other.number && string == other.string + } + + override fun hashCode(): Int = Objects.hash(number, string) + + override fun toString(): String = + when { + number != null -> "YCenter{number=$number}" + string != null -> "YCenter{string=$string}" + _json != null -> "YCenter{_unknown=$_json}" + else -> throw IllegalStateException("Invalid YCenter") + } + + companion object { + + @JvmStatic fun ofNumber(number: Double) = YCenter(number = number) + + @JvmStatic fun ofString(string: String) = YCenter(string = string) + } + + /** + * An interface that defines how to map each variant of [YCenter] to a value of type [T]. + */ + interface Visitor { + + fun visitNumber(number: Double): T + + fun visitString(string: String): T + + /** + * Maps an unknown variant of [YCenter] to a value of type [T]. + * + * An instance of [YCenter] can contain an unknown variant if it was deserialized from + * data that doesn't match any known variant. For example, if the SDK is on an older + * version than the API, then the API may respond with new variants that the SDK is + * unaware of. + * + * @throws ImageKitInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw ImageKitInvalidDataException("Unknown YCenter: $json") + } + } + + internal class Deserializer : BaseDeserializer(YCenter::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): YCenter { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + YCenter(number = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + YCenter(string = it, _json = json) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely incompatible with + // all the possible variants (e.g. deserializing from object). + 0 -> YCenter(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then use the first + // completely valid match, or simply the first match if none are completely + // valid. + else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() + } + } + } + + internal class Serializer : BaseSerializer(YCenter::class) { + + override fun serialize( + value: YCenter, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.number != null -> generator.writeObject(value.number) + value.string != null -> generator.writeObject(value.string) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid YCenter") + } + } + } + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Transformation && + aiChangeBackground == other.aiChangeBackground && + aiDropShadow == other.aiDropShadow && + aiEdit == other.aiEdit && + aiRemoveBackground == other.aiRemoveBackground && + aiRemoveBackgroundExternal == other.aiRemoveBackgroundExternal && + aiRetouch == other.aiRetouch && + aiUpscale == other.aiUpscale && + aiVariation == other.aiVariation && + aspectRatio == other.aspectRatio && + audioCodec == other.audioCodec && + background == other.background && + blur == other.blur && + border == other.border && + colorProfile == other.colorProfile && + contrastStretch == other.contrastStretch && + crop == other.crop && + cropMode == other.cropMode && + defaultImage == other.defaultImage && + dpr == other.dpr && + duration == other.duration && + endOffset == other.endOffset && + flip == other.flip && + focus == other.focus && + format == other.format && + gradient == other.gradient && + grayscale == other.grayscale && + height == other.height && + lossless == other.lossless && + metadata == other.metadata && + named == other.named && + opacity == other.opacity && + original == other.original && + overlay == other.overlay && + page == other.page && + progressive == other.progressive && + quality == other.quality && + radius == other.radius && + raw == other.raw && + rotation == other.rotation && + shadow == other.shadow && + sharpen == other.sharpen && + startOffset == other.startOffset && + streamingResolutions == other.streamingResolutions && + trim == other.trim && + unsharpMask == other.unsharpMask && + videoCodec == other.videoCodec && + width == other.width && + x == other.x && + xCenter == other.xCenter && + y == other.y && + yCenter == other.yCenter && + zoom == other.zoom && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + aiChangeBackground, + aiDropShadow, + aiEdit, + aiRemoveBackground, + aiRemoveBackgroundExternal, + aiRetouch, + aiUpscale, + aiVariation, + aspectRatio, + audioCodec, + background, + blur, + border, + colorProfile, + contrastStretch, + crop, + cropMode, + defaultImage, + dpr, + duration, + endOffset, + flip, + focus, + format, + gradient, + grayscale, + height, + lossless, + metadata, + named, + opacity, + original, + overlay, + page, + progressive, + quality, + radius, + raw, + rotation, + shadow, + sharpen, + startOffset, + streamingResolutions, + trim, + unsharpMask, + videoCodec, + width, + x, + xCenter, + y, + yCenter, + zoom, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Transformation{aiChangeBackground=$aiChangeBackground, aiDropShadow=$aiDropShadow, aiEdit=$aiEdit, aiRemoveBackground=$aiRemoveBackground, aiRemoveBackgroundExternal=$aiRemoveBackgroundExternal, aiRetouch=$aiRetouch, aiUpscale=$aiUpscale, aiVariation=$aiVariation, aspectRatio=$aspectRatio, audioCodec=$audioCodec, background=$background, blur=$blur, border=$border, colorProfile=$colorProfile, contrastStretch=$contrastStretch, crop=$crop, cropMode=$cropMode, defaultImage=$defaultImage, dpr=$dpr, duration=$duration, endOffset=$endOffset, flip=$flip, focus=$focus, format=$format, gradient=$gradient, grayscale=$grayscale, height=$height, lossless=$lossless, metadata=$metadata, named=$named, opacity=$opacity, original=$original, overlay=$overlay, page=$page, progressive=$progressive, quality=$quality, radius=$radius, raw=$raw, rotation=$rotation, shadow=$shadow, sharpen=$sharpen, startOffset=$startOffset, streamingResolutions=$streamingResolutions, trim=$trim, unsharpMask=$unsharpMask, videoCodec=$videoCodec, width=$width, x=$x, xCenter=$xCenter, y=$y, yCenter=$yCenter, zoom=$zoom, additionalProperties=$additionalProperties}" +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/TransformationPosition.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/TransformationPosition.kt new file mode 100644 index 0000000..5a62532 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/TransformationPosition.kt @@ -0,0 +1,140 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models + +import com.fasterxml.jackson.annotation.JsonCreator +import com.imagekit.api.core.Enum +import com.imagekit.api.core.JsonField +import com.imagekit.api.errors.ImageKitInvalidDataException + +/** + * By default, the transformation string is added as a query parameter in the URL, e.g., + * `?tr=w-100,h-100`. If you want to add the transformation string in the path of the URL, set this + * to `path`. Learn more in the [Transformations guide](https://imagekit.io/docs/transformations). + */ +class TransformationPosition +@JsonCreator +private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't match + * any known member, and you want to know that value. For example, if the SDK is on an older + * version than the API, then the API may respond with new members that the SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val PATH = of("path") + + @JvmField val QUERY = of("query") + + @JvmStatic fun of(value: String) = TransformationPosition(JsonField.of(value)) + } + + /** An enum containing [TransformationPosition]'s known values. */ + enum class Known { + PATH, + QUERY, + } + + /** + * An enum containing [TransformationPosition]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [TransformationPosition] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if the SDK + * is on an older version than the API, then the API may respond with new members that the SDK + * is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + PATH, + QUERY, + /** + * An enum member indicating that [TransformationPosition] was instantiated with an unknown + * value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] if + * the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you want to + * throw for the unknown case. + */ + fun value(): Value = + when (this) { + PATH -> Value.PATH + QUERY -> Value.QUERY + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and don't want + * to throw for the unknown case. + * + * @throws ImageKitInvalidDataException if this class instance's value is a not a known member. + */ + fun known(): Known = + when (this) { + PATH -> Known.PATH + QUERY -> Known.QUERY + else -> throw ImageKitInvalidDataException("Unknown TransformationPosition: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for debugging and + * generally doesn't throw. + * + * @throws ImageKitInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { ImageKitInvalidDataException("Value is not a String") } + + private var validated: Boolean = false + + fun validate(): TransformationPosition = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is TransformationPosition && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/VideoOverlay.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/VideoOverlay.kt new file mode 100644 index 0000000..2ca94d2 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/VideoOverlay.kt @@ -0,0 +1,530 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.imagekit.api.core.Enum +import com.imagekit.api.core.ExcludeMissing +import com.imagekit.api.core.JsonField +import com.imagekit.api.core.JsonMissing +import com.imagekit.api.core.JsonValue +import com.imagekit.api.core.checkKnown +import com.imagekit.api.core.checkRequired +import com.imagekit.api.core.toImmutable +import com.imagekit.api.errors.ImageKitInvalidDataException +import java.util.Collections +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +class VideoOverlay +private constructor( + private val position: JsonField, + private val timing: JsonField, + private val input: JsonField, + private val type: JsonValue, + private val encoding: JsonField, + private val transformation: JsonField>, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("position") + @ExcludeMissing + position: JsonField = JsonMissing.of(), + @JsonProperty("timing") @ExcludeMissing timing: JsonField = JsonMissing.of(), + @JsonProperty("input") @ExcludeMissing input: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(), + @JsonProperty("encoding") @ExcludeMissing encoding: JsonField = JsonMissing.of(), + @JsonProperty("transformation") + @ExcludeMissing + transformation: JsonField> = JsonMissing.of(), + ) : this(position, timing, input, type, encoding, transformation, mutableMapOf()) + + fun toBaseOverlay(): BaseOverlay = + BaseOverlay.builder().position(position).timing(timing).build() + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun position(): Optional = position.getOptional("position") + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun timing(): Optional = timing.getOptional("timing") + + /** + * Specifies the relative path to the video used as an overlay. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun input(): String = input.getRequired("input") + + /** + * Expected to always return the following: + * ```java + * JsonValue.from("video") + * ``` + * + * However, this method can be useful for debugging and logging (e.g. if the server responded + * with an unexpected value). + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type + + /** + * The input path can be included in the layer as either `i-{input}` or + * `ie-{base64_encoded_input}`. By default, the SDK determines the appropriate format + * automatically. To always use base64 encoding (`ie-{base64}`), set this parameter to `base64`. + * To always use plain text (`i-{input}`), set it to `plain`. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun encoding(): Optional = encoding.getOptional("encoding") + + /** + * Array of transformation to be applied to the overlay video. Except `streamingResolutions`, + * all other video transformations are supported. See + * [Video transformations](https://imagekit.io/docs/video-transformation). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun transformation(): Optional> = + transformation.getOptional("transformation") + + /** + * Returns the raw JSON value of [position]. + * + * Unlike [position], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("position") @ExcludeMissing fun _position(): JsonField = position + + /** + * Returns the raw JSON value of [timing]. + * + * Unlike [timing], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("timing") @ExcludeMissing fun _timing(): JsonField = timing + + /** + * Returns the raw JSON value of [input]. + * + * Unlike [input], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("input") @ExcludeMissing fun _input(): JsonField = input + + /** + * Returns the raw JSON value of [encoding]. + * + * Unlike [encoding], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("encoding") @ExcludeMissing fun _encoding(): JsonField = encoding + + /** + * Returns the raw JSON value of [transformation]. + * + * Unlike [transformation], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("transformation") + @ExcludeMissing + fun _transformation(): JsonField> = transformation + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [VideoOverlay]. + * + * The following fields are required: + * ```java + * .input() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [VideoOverlay]. */ + class Builder internal constructor() { + + private var position: JsonField = JsonMissing.of() + private var timing: JsonField = JsonMissing.of() + private var input: JsonField? = null + private var type: JsonValue = JsonValue.from("video") + private var encoding: JsonField = JsonMissing.of() + private var transformation: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(videoOverlay: VideoOverlay) = apply { + position = videoOverlay.position + timing = videoOverlay.timing + input = videoOverlay.input + type = videoOverlay.type + encoding = videoOverlay.encoding + transformation = videoOverlay.transformation.map { it.toMutableList() } + additionalProperties = videoOverlay.additionalProperties.toMutableMap() + } + + fun position(position: OverlayPosition) = position(JsonField.of(position)) + + /** + * Sets [Builder.position] to an arbitrary JSON value. + * + * You should usually call [Builder.position] with a well-typed [OverlayPosition] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun position(position: JsonField) = apply { this.position = position } + + fun timing(timing: OverlayTiming) = timing(JsonField.of(timing)) + + /** + * Sets [Builder.timing] to an arbitrary JSON value. + * + * You should usually call [Builder.timing] with a well-typed [OverlayTiming] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun timing(timing: JsonField) = apply { this.timing = timing } + + /** Specifies the relative path to the video used as an overlay. */ + fun input(input: String) = input(JsonField.of(input)) + + /** + * Sets [Builder.input] to an arbitrary JSON value. + * + * You should usually call [Builder.input] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun input(input: JsonField) = apply { this.input = input } + + /** + * Sets the field to an arbitrary JSON value. + * + * It is usually unnecessary to call this method because the field defaults to the + * following: + * ```java + * JsonValue.from("video") + * ``` + * + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun type(type: JsonValue) = apply { this.type = type } + + /** + * The input path can be included in the layer as either `i-{input}` or + * `ie-{base64_encoded_input}`. By default, the SDK determines the appropriate format + * automatically. To always use base64 encoding (`ie-{base64}`), set this parameter to + * `base64`. To always use plain text (`i-{input}`), set it to `plain`. + */ + fun encoding(encoding: Encoding) = encoding(JsonField.of(encoding)) + + /** + * Sets [Builder.encoding] to an arbitrary JSON value. + * + * You should usually call [Builder.encoding] with a well-typed [Encoding] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun encoding(encoding: JsonField) = apply { this.encoding = encoding } + + /** + * Array of transformation to be applied to the overlay video. Except + * `streamingResolutions`, all other video transformations are supported. See + * [Video transformations](https://imagekit.io/docs/video-transformation). + */ + fun transformation(transformation: List) = + transformation(JsonField.of(transformation)) + + /** + * Sets [Builder.transformation] to an arbitrary JSON value. + * + * You should usually call [Builder.transformation] with a well-typed `List` + * value instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun transformation(transformation: JsonField>) = apply { + this.transformation = transformation.map { it.toMutableList() } + } + + /** + * Adds a single [Transformation] to [Builder.transformation]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addTransformation(transformation: Transformation) = apply { + this.transformation = + (this.transformation ?: JsonField.of(mutableListOf())).also { + checkKnown("transformation", it).add(transformation) + } + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [VideoOverlay]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .input() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): VideoOverlay = + VideoOverlay( + position, + timing, + checkRequired("input", input), + type, + encoding, + (transformation ?: JsonMissing.of()).map { it.toImmutable() }, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): VideoOverlay = apply { + if (validated) { + return@apply + } + + position().ifPresent { it.validate() } + timing().ifPresent { it.validate() } + input() + _type().let { + if (it != JsonValue.from("video")) { + throw ImageKitInvalidDataException("'type' is invalid, received $it") + } + } + encoding().ifPresent { it.validate() } + transformation().ifPresent { it.forEach { it.validate() } } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (position.asKnown().getOrNull()?.validity() ?: 0) + + (timing.asKnown().getOrNull()?.validity() ?: 0) + + (if (input.asKnown().isPresent) 1 else 0) + + type.let { if (it == JsonValue.from("video")) 1 else 0 } + + (encoding.asKnown().getOrNull()?.validity() ?: 0) + + (transformation.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + /** + * The input path can be included in the layer as either `i-{input}` or + * `ie-{base64_encoded_input}`. By default, the SDK determines the appropriate format + * automatically. To always use base64 encoding (`ie-{base64}`), set this parameter to `base64`. + * To always use plain text (`i-{input}`), set it to `plain`. + */ + class Encoding @JsonCreator private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is on an + * older version than the API, then the API may respond with new members that the SDK is + * unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val AUTO = of("auto") + + @JvmField val PLAIN = of("plain") + + @JvmField val BASE64 = of("base64") + + @JvmStatic fun of(value: String) = Encoding(JsonField.of(value)) + } + + /** An enum containing [Encoding]'s known values. */ + enum class Known { + AUTO, + PLAIN, + BASE64, + } + + /** + * An enum containing [Encoding]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [Encoding] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if the + * SDK is on an older version than the API, then the API may respond with new members that + * the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + AUTO, + PLAIN, + BASE64, + /** An enum member indicating that [Encoding] was instantiated with an unknown value. */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] + * if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you want + * to throw for the unknown case. + */ + fun value(): Value = + when (this) { + AUTO -> Value.AUTO + PLAIN -> Value.PLAIN + BASE64 -> Value.BASE64 + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and don't + * want to throw for the unknown case. + * + * @throws ImageKitInvalidDataException if this class instance's value is a not a known + * member. + */ + fun known(): Known = + when (this) { + AUTO -> Known.AUTO + PLAIN -> Known.PLAIN + BASE64 -> Known.BASE64 + else -> throw ImageKitInvalidDataException("Unknown Encoding: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for debugging + * and generally doesn't throw. + * + * @throws ImageKitInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + ImageKitInvalidDataException("Value is not a String") + } + + private var validated: Boolean = false + + fun validate(): Encoding = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Encoding && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is VideoOverlay && + position == other.position && + timing == other.timing && + input == other.input && + type == other.type && + encoding == other.encoding && + transformation == other.transformation && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(position, timing, input, type, encoding, transformation, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "VideoOverlay{position=$position, timing=$timing, input=$input, type=$type, encoding=$encoding, transformation=$transformation, additionalProperties=$additionalProperties}" +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/accounts/origins/OriginCreateParams.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/accounts/origins/OriginCreateParams.kt new file mode 100644 index 0000000..6ea3230 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/accounts/origins/OriginCreateParams.kt @@ -0,0 +1,246 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.accounts.origins + +import com.imagekit.api.core.Params +import com.imagekit.api.core.checkRequired +import com.imagekit.api.core.http.Headers +import com.imagekit.api.core.http.QueryParams +import java.util.Objects + +/** **Note:** This API is currently in beta. Creates a new origin and returns the origin object. */ +class OriginCreateParams +private constructor( + private val originRequest: OriginRequest, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** Schema for origin request resources. */ + fun originRequest(): OriginRequest = originRequest + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [OriginCreateParams]. + * + * The following fields are required: + * ```java + * .originRequest() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [OriginCreateParams]. */ + class Builder internal constructor() { + + private var originRequest: OriginRequest? = null + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + + @JvmSynthetic + internal fun from(originCreateParams: OriginCreateParams) = apply { + originRequest = originCreateParams.originRequest + additionalHeaders = originCreateParams.additionalHeaders.toBuilder() + additionalQueryParams = originCreateParams.additionalQueryParams.toBuilder() + } + + /** Schema for origin request resources. */ + fun originRequest(originRequest: OriginRequest) = apply { + this.originRequest = originRequest + } + + /** Alias for calling [originRequest] with `OriginRequest.ofS3(s3)`. */ + fun originRequest(s3: OriginRequest.S3) = originRequest(OriginRequest.ofS3(s3)) + + /** Alias for calling [originRequest] with `OriginRequest.ofS3Compatible(s3Compatible)`. */ + fun originRequest(s3Compatible: OriginRequest.S3Compatible) = + originRequest(OriginRequest.ofS3Compatible(s3Compatible)) + + /** + * Alias for calling [originRequest] with + * `OriginRequest.ofCloudinaryBackup(cloudinaryBackup)`. + */ + fun originRequest(cloudinaryBackup: OriginRequest.CloudinaryBackup) = + originRequest(OriginRequest.ofCloudinaryBackup(cloudinaryBackup)) + + /** Alias for calling [originRequest] with `OriginRequest.ofWebFolder(webFolder)`. */ + fun originRequest(webFolder: OriginRequest.WebFolder) = + originRequest(OriginRequest.ofWebFolder(webFolder)) + + /** Alias for calling [originRequest] with `OriginRequest.ofWebProxy(webProxy)`. */ + fun originRequest(webProxy: OriginRequest.WebProxy) = + originRequest(OriginRequest.ofWebProxy(webProxy)) + + /** + * Alias for calling [originRequest] with the following: + * ```java + * OriginRequest.WebProxy.builder() + * .name(name) + * .build() + * ``` + */ + fun webProxyOriginRequest(name: String) = + originRequest(OriginRequest.WebProxy.builder().name(name).build()) + + /** Alias for calling [originRequest] with `OriginRequest.ofGcs(gcs)`. */ + fun originRequest(gcs: OriginRequest.Gcs) = originRequest(OriginRequest.ofGcs(gcs)) + + /** Alias for calling [originRequest] with `OriginRequest.ofAzureBlob(azureBlob)`. */ + fun originRequest(azureBlob: OriginRequest.AzureBlob) = + originRequest(OriginRequest.ofAzureBlob(azureBlob)) + + /** Alias for calling [originRequest] with `OriginRequest.ofAkeneoPim(akeneoPim)`. */ + fun originRequest(akeneoPim: OriginRequest.AkeneoPim) = + originRequest(OriginRequest.ofAkeneoPim(akeneoPim)) + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + /** + * Returns an immutable instance of [OriginCreateParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .originRequest() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): OriginCreateParams = + OriginCreateParams( + checkRequired("originRequest", originRequest), + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } + + fun _body(): OriginRequest = originRequest + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is OriginCreateParams && + originRequest == other.originRequest && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = + Objects.hash(originRequest, additionalHeaders, additionalQueryParams) + + override fun toString() = + "OriginCreateParams{originRequest=$originRequest, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/accounts/origins/OriginDeleteParams.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/accounts/origins/OriginDeleteParams.kt new file mode 100644 index 0000000..f96b6b3 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/accounts/origins/OriginDeleteParams.kt @@ -0,0 +1,239 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.accounts.origins + +import com.imagekit.api.core.JsonValue +import com.imagekit.api.core.Params +import com.imagekit.api.core.http.Headers +import com.imagekit.api.core.http.QueryParams +import com.imagekit.api.core.toImmutable +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** + * **Note:** This API is currently in beta. Permanently removes the origin identified by `id`. If + * the origin is in use by any URL‑endpoints, the API will return an error. + */ +class OriginDeleteParams +private constructor( + private val id: String?, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, + private val additionalBodyProperties: Map, +) : Params { + + /** + * Unique identifier for the origin. This is generated by ImageKit when you create a new origin. + */ + fun id(): Optional = Optional.ofNullable(id) + + /** Additional body properties to send with the request. */ + fun _additionalBodyProperties(): Map = additionalBodyProperties + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun none(): OriginDeleteParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [OriginDeleteParams]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [OriginDeleteParams]. */ + class Builder internal constructor() { + + private var id: String? = null + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + private var additionalBodyProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(originDeleteParams: OriginDeleteParams) = apply { + id = originDeleteParams.id + additionalHeaders = originDeleteParams.additionalHeaders.toBuilder() + additionalQueryParams = originDeleteParams.additionalQueryParams.toBuilder() + additionalBodyProperties = originDeleteParams.additionalBodyProperties.toMutableMap() + } + + /** + * Unique identifier for the origin. This is generated by ImageKit when you create a new + * origin. + */ + fun id(id: String?) = apply { this.id = id } + + /** Alias for calling [Builder.id] with `id.orElse(null)`. */ + fun id(id: Optional) = id(id.getOrNull()) + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + this.additionalBodyProperties.clear() + putAllAdditionalBodyProperties(additionalBodyProperties) + } + + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + additionalBodyProperties.put(key, value) + } + + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + this.additionalBodyProperties.putAll(additionalBodyProperties) + } + + fun removeAdditionalBodyProperty(key: String) = apply { + additionalBodyProperties.remove(key) + } + + fun removeAllAdditionalBodyProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalBodyProperty) + } + + /** + * Returns an immutable instance of [OriginDeleteParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): OriginDeleteParams = + OriginDeleteParams( + id, + additionalHeaders.build(), + additionalQueryParams.build(), + additionalBodyProperties.toImmutable(), + ) + } + + fun _body(): Optional> = + Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) + + fun _pathParam(index: Int): String = + when (index) { + 0 -> id ?: "" + else -> "" + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is OriginDeleteParams && + id == other.id && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams && + additionalBodyProperties == other.additionalBodyProperties + } + + override fun hashCode(): Int = + Objects.hash(id, additionalHeaders, additionalQueryParams, additionalBodyProperties) + + override fun toString() = + "OriginDeleteParams{id=$id, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams, additionalBodyProperties=$additionalBodyProperties}" +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/accounts/origins/OriginGetParams.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/accounts/origins/OriginGetParams.kt new file mode 100644 index 0000000..b4b2f30 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/accounts/origins/OriginGetParams.kt @@ -0,0 +1,196 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.accounts.origins + +import com.imagekit.api.core.Params +import com.imagekit.api.core.http.Headers +import com.imagekit.api.core.http.QueryParams +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** **Note:** This API is currently in beta. Retrieves the origin identified by `id`. */ +class OriginGetParams +private constructor( + private val id: String?, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** + * Unique identifier for the origin. This is generated by ImageKit when you create a new origin. + */ + fun id(): Optional = Optional.ofNullable(id) + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun none(): OriginGetParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [OriginGetParams]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [OriginGetParams]. */ + class Builder internal constructor() { + + private var id: String? = null + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + + @JvmSynthetic + internal fun from(originGetParams: OriginGetParams) = apply { + id = originGetParams.id + additionalHeaders = originGetParams.additionalHeaders.toBuilder() + additionalQueryParams = originGetParams.additionalQueryParams.toBuilder() + } + + /** + * Unique identifier for the origin. This is generated by ImageKit when you create a new + * origin. + */ + fun id(id: String?) = apply { this.id = id } + + /** Alias for calling [Builder.id] with `id.orElse(null)`. */ + fun id(id: Optional) = id(id.getOrNull()) + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + /** + * Returns an immutable instance of [OriginGetParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): OriginGetParams = + OriginGetParams(id, additionalHeaders.build(), additionalQueryParams.build()) + } + + fun _pathParam(index: Int): String = + when (index) { + 0 -> id ?: "" + else -> "" + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is OriginGetParams && + id == other.id && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = Objects.hash(id, additionalHeaders, additionalQueryParams) + + override fun toString() = + "OriginGetParams{id=$id, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/accounts/origins/OriginListParams.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/accounts/origins/OriginListParams.kt new file mode 100644 index 0000000..a1f0950 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/accounts/origins/OriginListParams.kt @@ -0,0 +1,173 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.accounts.origins + +import com.imagekit.api.core.Params +import com.imagekit.api.core.http.Headers +import com.imagekit.api.core.http.QueryParams +import java.util.Objects + +/** + * **Note:** This API is currently in beta. Returns an array of all configured origins for the + * current account. + */ +class OriginListParams +private constructor( + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun none(): OriginListParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [OriginListParams]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [OriginListParams]. */ + class Builder internal constructor() { + + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + + @JvmSynthetic + internal fun from(originListParams: OriginListParams) = apply { + additionalHeaders = originListParams.additionalHeaders.toBuilder() + additionalQueryParams = originListParams.additionalQueryParams.toBuilder() + } + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + /** + * Returns an immutable instance of [OriginListParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): OriginListParams = + OriginListParams(additionalHeaders.build(), additionalQueryParams.build()) + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is OriginListParams && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = Objects.hash(additionalHeaders, additionalQueryParams) + + override fun toString() = + "OriginListParams{additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/accounts/origins/OriginRequest.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/accounts/origins/OriginRequest.kt new file mode 100644 index 0000000..56eb794 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/accounts/origins/OriginRequest.kt @@ -0,0 +1,3908 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.accounts.origins + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.fasterxml.jackson.core.JsonGenerator +import com.fasterxml.jackson.core.ObjectCodec +import com.fasterxml.jackson.databind.JsonNode +import com.fasterxml.jackson.databind.SerializerProvider +import com.fasterxml.jackson.databind.annotation.JsonDeserialize +import com.fasterxml.jackson.databind.annotation.JsonSerialize +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.imagekit.api.core.BaseDeserializer +import com.imagekit.api.core.BaseSerializer +import com.imagekit.api.core.ExcludeMissing +import com.imagekit.api.core.JsonField +import com.imagekit.api.core.JsonMissing +import com.imagekit.api.core.JsonValue +import com.imagekit.api.core.checkRequired +import com.imagekit.api.core.getOrThrow +import com.imagekit.api.errors.ImageKitInvalidDataException +import java.util.Collections +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** Schema for origin request resources. */ +@JsonDeserialize(using = OriginRequest.Deserializer::class) +@JsonSerialize(using = OriginRequest.Serializer::class) +class OriginRequest +private constructor( + private val s3: S3? = null, + private val s3Compatible: S3Compatible? = null, + private val cloudinaryBackup: CloudinaryBackup? = null, + private val webFolder: WebFolder? = null, + private val webProxy: WebProxy? = null, + private val gcs: Gcs? = null, + private val azureBlob: AzureBlob? = null, + private val akeneoPim: AkeneoPim? = null, + private val _json: JsonValue? = null, +) { + + fun s3(): Optional = Optional.ofNullable(s3) + + fun s3Compatible(): Optional = Optional.ofNullable(s3Compatible) + + fun cloudinaryBackup(): Optional = Optional.ofNullable(cloudinaryBackup) + + fun webFolder(): Optional = Optional.ofNullable(webFolder) + + fun webProxy(): Optional = Optional.ofNullable(webProxy) + + fun gcs(): Optional = Optional.ofNullable(gcs) + + fun azureBlob(): Optional = Optional.ofNullable(azureBlob) + + fun akeneoPim(): Optional = Optional.ofNullable(akeneoPim) + + fun isS3(): Boolean = s3 != null + + fun isS3Compatible(): Boolean = s3Compatible != null + + fun isCloudinaryBackup(): Boolean = cloudinaryBackup != null + + fun isWebFolder(): Boolean = webFolder != null + + fun isWebProxy(): Boolean = webProxy != null + + fun isGcs(): Boolean = gcs != null + + fun isAzureBlob(): Boolean = azureBlob != null + + fun isAkeneoPim(): Boolean = akeneoPim != null + + fun asS3(): S3 = s3.getOrThrow("s3") + + fun asS3Compatible(): S3Compatible = s3Compatible.getOrThrow("s3Compatible") + + fun asCloudinaryBackup(): CloudinaryBackup = cloudinaryBackup.getOrThrow("cloudinaryBackup") + + fun asWebFolder(): WebFolder = webFolder.getOrThrow("webFolder") + + fun asWebProxy(): WebProxy = webProxy.getOrThrow("webProxy") + + fun asGcs(): Gcs = gcs.getOrThrow("gcs") + + fun asAzureBlob(): AzureBlob = azureBlob.getOrThrow("azureBlob") + + fun asAkeneoPim(): AkeneoPim = akeneoPim.getOrThrow("akeneoPim") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + s3 != null -> visitor.visitS3(s3) + s3Compatible != null -> visitor.visitS3Compatible(s3Compatible) + cloudinaryBackup != null -> visitor.visitCloudinaryBackup(cloudinaryBackup) + webFolder != null -> visitor.visitWebFolder(webFolder) + webProxy != null -> visitor.visitWebProxy(webProxy) + gcs != null -> visitor.visitGcs(gcs) + azureBlob != null -> visitor.visitAzureBlob(azureBlob) + akeneoPim != null -> visitor.visitAkeneoPim(akeneoPim) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): OriginRequest = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitS3(s3: S3) { + s3.validate() + } + + override fun visitS3Compatible(s3Compatible: S3Compatible) { + s3Compatible.validate() + } + + override fun visitCloudinaryBackup(cloudinaryBackup: CloudinaryBackup) { + cloudinaryBackup.validate() + } + + override fun visitWebFolder(webFolder: WebFolder) { + webFolder.validate() + } + + override fun visitWebProxy(webProxy: WebProxy) { + webProxy.validate() + } + + override fun visitGcs(gcs: Gcs) { + gcs.validate() + } + + override fun visitAzureBlob(azureBlob: AzureBlob) { + azureBlob.validate() + } + + override fun visitAkeneoPim(akeneoPim: AkeneoPim) { + akeneoPim.validate() + } + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitS3(s3: S3) = s3.validity() + + override fun visitS3Compatible(s3Compatible: S3Compatible) = s3Compatible.validity() + + override fun visitCloudinaryBackup(cloudinaryBackup: CloudinaryBackup) = + cloudinaryBackup.validity() + + override fun visitWebFolder(webFolder: WebFolder) = webFolder.validity() + + override fun visitWebProxy(webProxy: WebProxy) = webProxy.validity() + + override fun visitGcs(gcs: Gcs) = gcs.validity() + + override fun visitAzureBlob(azureBlob: AzureBlob) = azureBlob.validity() + + override fun visitAkeneoPim(akeneoPim: AkeneoPim) = akeneoPim.validity() + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is OriginRequest && + s3 == other.s3 && + s3Compatible == other.s3Compatible && + cloudinaryBackup == other.cloudinaryBackup && + webFolder == other.webFolder && + webProxy == other.webProxy && + gcs == other.gcs && + azureBlob == other.azureBlob && + akeneoPim == other.akeneoPim + } + + override fun hashCode(): Int = + Objects.hash( + s3, + s3Compatible, + cloudinaryBackup, + webFolder, + webProxy, + gcs, + azureBlob, + akeneoPim, + ) + + override fun toString(): String = + when { + s3 != null -> "OriginRequest{s3=$s3}" + s3Compatible != null -> "OriginRequest{s3Compatible=$s3Compatible}" + cloudinaryBackup != null -> "OriginRequest{cloudinaryBackup=$cloudinaryBackup}" + webFolder != null -> "OriginRequest{webFolder=$webFolder}" + webProxy != null -> "OriginRequest{webProxy=$webProxy}" + gcs != null -> "OriginRequest{gcs=$gcs}" + azureBlob != null -> "OriginRequest{azureBlob=$azureBlob}" + akeneoPim != null -> "OriginRequest{akeneoPim=$akeneoPim}" + _json != null -> "OriginRequest{_unknown=$_json}" + else -> throw IllegalStateException("Invalid OriginRequest") + } + + companion object { + + @JvmStatic fun ofS3(s3: S3) = OriginRequest(s3 = s3) + + @JvmStatic + fun ofS3Compatible(s3Compatible: S3Compatible) = OriginRequest(s3Compatible = s3Compatible) + + @JvmStatic + fun ofCloudinaryBackup(cloudinaryBackup: CloudinaryBackup) = + OriginRequest(cloudinaryBackup = cloudinaryBackup) + + @JvmStatic fun ofWebFolder(webFolder: WebFolder) = OriginRequest(webFolder = webFolder) + + @JvmStatic fun ofWebProxy(webProxy: WebProxy) = OriginRequest(webProxy = webProxy) + + @JvmStatic fun ofGcs(gcs: Gcs) = OriginRequest(gcs = gcs) + + @JvmStatic fun ofAzureBlob(azureBlob: AzureBlob) = OriginRequest(azureBlob = azureBlob) + + @JvmStatic fun ofAkeneoPim(akeneoPim: AkeneoPim) = OriginRequest(akeneoPim = akeneoPim) + } + + /** + * An interface that defines how to map each variant of [OriginRequest] to a value of type [T]. + */ + interface Visitor { + + fun visitS3(s3: S3): T + + fun visitS3Compatible(s3Compatible: S3Compatible): T + + fun visitCloudinaryBackup(cloudinaryBackup: CloudinaryBackup): T + + fun visitWebFolder(webFolder: WebFolder): T + + fun visitWebProxy(webProxy: WebProxy): T + + fun visitGcs(gcs: Gcs): T + + fun visitAzureBlob(azureBlob: AzureBlob): T + + fun visitAkeneoPim(akeneoPim: AkeneoPim): T + + /** + * Maps an unknown variant of [OriginRequest] to a value of type [T]. + * + * An instance of [OriginRequest] can contain an unknown variant if it was deserialized from + * data that doesn't match any known variant. For example, if the SDK is on an older version + * than the API, then the API may respond with new variants that the SDK is unaware of. + * + * @throws ImageKitInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw ImageKitInvalidDataException("Unknown OriginRequest: $json") + } + } + + internal class Deserializer : BaseDeserializer(OriginRequest::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): OriginRequest { + val json = JsonValue.fromJsonNode(node) + val type = json.asObject().getOrNull()?.get("type")?.asString()?.getOrNull() + + when (type) { + "S3" -> { + return tryDeserialize(node, jacksonTypeRef())?.let { + OriginRequest(s3 = it, _json = json) + } ?: OriginRequest(_json = json) + } + "S3_COMPATIBLE" -> { + return tryDeserialize(node, jacksonTypeRef())?.let { + OriginRequest(s3Compatible = it, _json = json) + } ?: OriginRequest(_json = json) + } + "CLOUDINARY_BACKUP" -> { + return tryDeserialize(node, jacksonTypeRef())?.let { + OriginRequest(cloudinaryBackup = it, _json = json) + } ?: OriginRequest(_json = json) + } + "WEB_FOLDER" -> { + return tryDeserialize(node, jacksonTypeRef())?.let { + OriginRequest(webFolder = it, _json = json) + } ?: OriginRequest(_json = json) + } + "WEB_PROXY" -> { + return tryDeserialize(node, jacksonTypeRef())?.let { + OriginRequest(webProxy = it, _json = json) + } ?: OriginRequest(_json = json) + } + "GCS" -> { + return tryDeserialize(node, jacksonTypeRef())?.let { + OriginRequest(gcs = it, _json = json) + } ?: OriginRequest(_json = json) + } + "AZURE_BLOB" -> { + return tryDeserialize(node, jacksonTypeRef())?.let { + OriginRequest(azureBlob = it, _json = json) + } ?: OriginRequest(_json = json) + } + "AKENEO_PIM" -> { + return tryDeserialize(node, jacksonTypeRef())?.let { + OriginRequest(akeneoPim = it, _json = json) + } ?: OriginRequest(_json = json) + } + } + + return OriginRequest(_json = json) + } + } + + internal class Serializer : BaseSerializer(OriginRequest::class) { + + override fun serialize( + value: OriginRequest, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.s3 != null -> generator.writeObject(value.s3) + value.s3Compatible != null -> generator.writeObject(value.s3Compatible) + value.cloudinaryBackup != null -> generator.writeObject(value.cloudinaryBackup) + value.webFolder != null -> generator.writeObject(value.webFolder) + value.webProxy != null -> generator.writeObject(value.webProxy) + value.gcs != null -> generator.writeObject(value.gcs) + value.azureBlob != null -> generator.writeObject(value.azureBlob) + value.akeneoPim != null -> generator.writeObject(value.akeneoPim) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid OriginRequest") + } + } + } + + class S3 + private constructor( + private val accessKey: JsonField, + private val bucket: JsonField, + private val name: JsonField, + private val secretKey: JsonField, + private val type: JsonValue, + private val baseUrlForCanonicalHeader: JsonField, + private val includeCanonicalHeader: JsonField, + private val prefix: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("accessKey") + @ExcludeMissing + accessKey: JsonField = JsonMissing.of(), + @JsonProperty("bucket") @ExcludeMissing bucket: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("secretKey") + @ExcludeMissing + secretKey: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(), + @JsonProperty("baseUrlForCanonicalHeader") + @ExcludeMissing + baseUrlForCanonicalHeader: JsonField = JsonMissing.of(), + @JsonProperty("includeCanonicalHeader") + @ExcludeMissing + includeCanonicalHeader: JsonField = JsonMissing.of(), + @JsonProperty("prefix") @ExcludeMissing prefix: JsonField = JsonMissing.of(), + ) : this( + accessKey, + bucket, + name, + secretKey, + type, + baseUrlForCanonicalHeader, + includeCanonicalHeader, + prefix, + mutableMapOf(), + ) + + /** + * Access key for the bucket. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun accessKey(): String = accessKey.getRequired("accessKey") + + /** + * S3 bucket name. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun bucket(): String = bucket.getRequired("bucket") + + /** + * Display name of the origin. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun name(): String = name.getRequired("name") + + /** + * Secret key for the bucket. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun secretKey(): String = secretKey.getRequired("secretKey") + + /** + * Expected to always return the following: + * ```java + * JsonValue.from("S3") + * ``` + * + * However, this method can be useful for debugging and logging (e.g. if the server + * responded with an unexpected value). + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type + + /** + * URL used in the Canonical header (if enabled). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun baseUrlForCanonicalHeader(): Optional = + baseUrlForCanonicalHeader.getOptional("baseUrlForCanonicalHeader") + + /** + * Whether to send a Canonical header. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun includeCanonicalHeader(): Optional = + includeCanonicalHeader.getOptional("includeCanonicalHeader") + + /** + * Path prefix inside the bucket. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun prefix(): Optional = prefix.getOptional("prefix") + + /** + * Returns the raw JSON value of [accessKey]. + * + * Unlike [accessKey], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("accessKey") @ExcludeMissing fun _accessKey(): JsonField = accessKey + + /** + * Returns the raw JSON value of [bucket]. + * + * Unlike [bucket], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("bucket") @ExcludeMissing fun _bucket(): JsonField = bucket + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + + /** + * Returns the raw JSON value of [secretKey]. + * + * Unlike [secretKey], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("secretKey") @ExcludeMissing fun _secretKey(): JsonField = secretKey + + /** + * Returns the raw JSON value of [baseUrlForCanonicalHeader]. + * + * Unlike [baseUrlForCanonicalHeader], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("baseUrlForCanonicalHeader") + @ExcludeMissing + fun _baseUrlForCanonicalHeader(): JsonField = baseUrlForCanonicalHeader + + /** + * Returns the raw JSON value of [includeCanonicalHeader]. + * + * Unlike [includeCanonicalHeader], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("includeCanonicalHeader") + @ExcludeMissing + fun _includeCanonicalHeader(): JsonField = includeCanonicalHeader + + /** + * Returns the raw JSON value of [prefix]. + * + * Unlike [prefix], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("prefix") @ExcludeMissing fun _prefix(): JsonField = prefix + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [S3]. + * + * The following fields are required: + * ```java + * .accessKey() + * .bucket() + * .name() + * .secretKey() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [S3]. */ + class Builder internal constructor() { + + private var accessKey: JsonField? = null + private var bucket: JsonField? = null + private var name: JsonField? = null + private var secretKey: JsonField? = null + private var type: JsonValue = JsonValue.from("S3") + private var baseUrlForCanonicalHeader: JsonField = JsonMissing.of() + private var includeCanonicalHeader: JsonField = JsonMissing.of() + private var prefix: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(s3: S3) = apply { + accessKey = s3.accessKey + bucket = s3.bucket + name = s3.name + secretKey = s3.secretKey + type = s3.type + baseUrlForCanonicalHeader = s3.baseUrlForCanonicalHeader + includeCanonicalHeader = s3.includeCanonicalHeader + prefix = s3.prefix + additionalProperties = s3.additionalProperties.toMutableMap() + } + + /** Access key for the bucket. */ + fun accessKey(accessKey: String) = accessKey(JsonField.of(accessKey)) + + /** + * Sets [Builder.accessKey] to an arbitrary JSON value. + * + * You should usually call [Builder.accessKey] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun accessKey(accessKey: JsonField) = apply { this.accessKey = accessKey } + + /** S3 bucket name. */ + fun bucket(bucket: String) = bucket(JsonField.of(bucket)) + + /** + * Sets [Builder.bucket] to an arbitrary JSON value. + * + * You should usually call [Builder.bucket] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun bucket(bucket: JsonField) = apply { this.bucket = bucket } + + /** Display name of the origin. */ + fun name(name: String) = name(JsonField.of(name)) + + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun name(name: JsonField) = apply { this.name = name } + + /** Secret key for the bucket. */ + fun secretKey(secretKey: String) = secretKey(JsonField.of(secretKey)) + + /** + * Sets [Builder.secretKey] to an arbitrary JSON value. + * + * You should usually call [Builder.secretKey] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun secretKey(secretKey: JsonField) = apply { this.secretKey = secretKey } + + /** + * Sets the field to an arbitrary JSON value. + * + * It is usually unnecessary to call this method because the field defaults to the + * following: + * ```java + * JsonValue.from("S3") + * ``` + * + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun type(type: JsonValue) = apply { this.type = type } + + /** URL used in the Canonical header (if enabled). */ + fun baseUrlForCanonicalHeader(baseUrlForCanonicalHeader: String) = + baseUrlForCanonicalHeader(JsonField.of(baseUrlForCanonicalHeader)) + + /** + * Sets [Builder.baseUrlForCanonicalHeader] to an arbitrary JSON value. + * + * You should usually call [Builder.baseUrlForCanonicalHeader] with a well-typed + * [String] value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun baseUrlForCanonicalHeader(baseUrlForCanonicalHeader: JsonField) = apply { + this.baseUrlForCanonicalHeader = baseUrlForCanonicalHeader + } + + /** Whether to send a Canonical header. */ + fun includeCanonicalHeader(includeCanonicalHeader: Boolean) = + includeCanonicalHeader(JsonField.of(includeCanonicalHeader)) + + /** + * Sets [Builder.includeCanonicalHeader] to an arbitrary JSON value. + * + * You should usually call [Builder.includeCanonicalHeader] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun includeCanonicalHeader(includeCanonicalHeader: JsonField) = apply { + this.includeCanonicalHeader = includeCanonicalHeader + } + + /** Path prefix inside the bucket. */ + fun prefix(prefix: String) = prefix(JsonField.of(prefix)) + + /** + * Sets [Builder.prefix] to an arbitrary JSON value. + * + * You should usually call [Builder.prefix] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun prefix(prefix: JsonField) = apply { this.prefix = prefix } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [S3]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .accessKey() + * .bucket() + * .name() + * .secretKey() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): S3 = + S3( + checkRequired("accessKey", accessKey), + checkRequired("bucket", bucket), + checkRequired("name", name), + checkRequired("secretKey", secretKey), + type, + baseUrlForCanonicalHeader, + includeCanonicalHeader, + prefix, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): S3 = apply { + if (validated) { + return@apply + } + + accessKey() + bucket() + name() + secretKey() + _type().let { + if (it != JsonValue.from("S3")) { + throw ImageKitInvalidDataException("'type' is invalid, received $it") + } + } + baseUrlForCanonicalHeader() + includeCanonicalHeader() + prefix() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (accessKey.asKnown().isPresent) 1 else 0) + + (if (bucket.asKnown().isPresent) 1 else 0) + + (if (name.asKnown().isPresent) 1 else 0) + + (if (secretKey.asKnown().isPresent) 1 else 0) + + type.let { if (it == JsonValue.from("S3")) 1 else 0 } + + (if (baseUrlForCanonicalHeader.asKnown().isPresent) 1 else 0) + + (if (includeCanonicalHeader.asKnown().isPresent) 1 else 0) + + (if (prefix.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is S3 && + accessKey == other.accessKey && + bucket == other.bucket && + name == other.name && + secretKey == other.secretKey && + type == other.type && + baseUrlForCanonicalHeader == other.baseUrlForCanonicalHeader && + includeCanonicalHeader == other.includeCanonicalHeader && + prefix == other.prefix && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + accessKey, + bucket, + name, + secretKey, + type, + baseUrlForCanonicalHeader, + includeCanonicalHeader, + prefix, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "S3{accessKey=$accessKey, bucket=$bucket, name=$name, secretKey=$secretKey, type=$type, baseUrlForCanonicalHeader=$baseUrlForCanonicalHeader, includeCanonicalHeader=$includeCanonicalHeader, prefix=$prefix, additionalProperties=$additionalProperties}" + } + + class S3Compatible + private constructor( + private val accessKey: JsonField, + private val bucket: JsonField, + private val endpoint: JsonField, + private val name: JsonField, + private val secretKey: JsonField, + private val type: JsonValue, + private val baseUrlForCanonicalHeader: JsonField, + private val includeCanonicalHeader: JsonField, + private val prefix: JsonField, + private val s3ForcePathStyle: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("accessKey") + @ExcludeMissing + accessKey: JsonField = JsonMissing.of(), + @JsonProperty("bucket") @ExcludeMissing bucket: JsonField = JsonMissing.of(), + @JsonProperty("endpoint") + @ExcludeMissing + endpoint: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("secretKey") + @ExcludeMissing + secretKey: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(), + @JsonProperty("baseUrlForCanonicalHeader") + @ExcludeMissing + baseUrlForCanonicalHeader: JsonField = JsonMissing.of(), + @JsonProperty("includeCanonicalHeader") + @ExcludeMissing + includeCanonicalHeader: JsonField = JsonMissing.of(), + @JsonProperty("prefix") @ExcludeMissing prefix: JsonField = JsonMissing.of(), + @JsonProperty("s3ForcePathStyle") + @ExcludeMissing + s3ForcePathStyle: JsonField = JsonMissing.of(), + ) : this( + accessKey, + bucket, + endpoint, + name, + secretKey, + type, + baseUrlForCanonicalHeader, + includeCanonicalHeader, + prefix, + s3ForcePathStyle, + mutableMapOf(), + ) + + /** + * Access key for the bucket. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun accessKey(): String = accessKey.getRequired("accessKey") + + /** + * S3 bucket name. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun bucket(): String = bucket.getRequired("bucket") + + /** + * Custom S3-compatible endpoint. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun endpoint(): String = endpoint.getRequired("endpoint") + + /** + * Display name of the origin. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun name(): String = name.getRequired("name") + + /** + * Secret key for the bucket. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun secretKey(): String = secretKey.getRequired("secretKey") + + /** + * Expected to always return the following: + * ```java + * JsonValue.from("S3_COMPATIBLE") + * ``` + * + * However, this method can be useful for debugging and logging (e.g. if the server + * responded with an unexpected value). + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type + + /** + * URL used in the Canonical header (if enabled). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun baseUrlForCanonicalHeader(): Optional = + baseUrlForCanonicalHeader.getOptional("baseUrlForCanonicalHeader") + + /** + * Whether to send a Canonical header. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun includeCanonicalHeader(): Optional = + includeCanonicalHeader.getOptional("includeCanonicalHeader") + + /** + * Path prefix inside the bucket. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun prefix(): Optional = prefix.getOptional("prefix") + + /** + * Use path-style S3 URLs? + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun s3ForcePathStyle(): Optional = s3ForcePathStyle.getOptional("s3ForcePathStyle") + + /** + * Returns the raw JSON value of [accessKey]. + * + * Unlike [accessKey], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("accessKey") @ExcludeMissing fun _accessKey(): JsonField = accessKey + + /** + * Returns the raw JSON value of [bucket]. + * + * Unlike [bucket], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("bucket") @ExcludeMissing fun _bucket(): JsonField = bucket + + /** + * Returns the raw JSON value of [endpoint]. + * + * Unlike [endpoint], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("endpoint") @ExcludeMissing fun _endpoint(): JsonField = endpoint + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + + /** + * Returns the raw JSON value of [secretKey]. + * + * Unlike [secretKey], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("secretKey") @ExcludeMissing fun _secretKey(): JsonField = secretKey + + /** + * Returns the raw JSON value of [baseUrlForCanonicalHeader]. + * + * Unlike [baseUrlForCanonicalHeader], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("baseUrlForCanonicalHeader") + @ExcludeMissing + fun _baseUrlForCanonicalHeader(): JsonField = baseUrlForCanonicalHeader + + /** + * Returns the raw JSON value of [includeCanonicalHeader]. + * + * Unlike [includeCanonicalHeader], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("includeCanonicalHeader") + @ExcludeMissing + fun _includeCanonicalHeader(): JsonField = includeCanonicalHeader + + /** + * Returns the raw JSON value of [prefix]. + * + * Unlike [prefix], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("prefix") @ExcludeMissing fun _prefix(): JsonField = prefix + + /** + * Returns the raw JSON value of [s3ForcePathStyle]. + * + * Unlike [s3ForcePathStyle], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("s3ForcePathStyle") + @ExcludeMissing + fun _s3ForcePathStyle(): JsonField = s3ForcePathStyle + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [S3Compatible]. + * + * The following fields are required: + * ```java + * .accessKey() + * .bucket() + * .endpoint() + * .name() + * .secretKey() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [S3Compatible]. */ + class Builder internal constructor() { + + private var accessKey: JsonField? = null + private var bucket: JsonField? = null + private var endpoint: JsonField? = null + private var name: JsonField? = null + private var secretKey: JsonField? = null + private var type: JsonValue = JsonValue.from("S3_COMPATIBLE") + private var baseUrlForCanonicalHeader: JsonField = JsonMissing.of() + private var includeCanonicalHeader: JsonField = JsonMissing.of() + private var prefix: JsonField = JsonMissing.of() + private var s3ForcePathStyle: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(s3Compatible: S3Compatible) = apply { + accessKey = s3Compatible.accessKey + bucket = s3Compatible.bucket + endpoint = s3Compatible.endpoint + name = s3Compatible.name + secretKey = s3Compatible.secretKey + type = s3Compatible.type + baseUrlForCanonicalHeader = s3Compatible.baseUrlForCanonicalHeader + includeCanonicalHeader = s3Compatible.includeCanonicalHeader + prefix = s3Compatible.prefix + s3ForcePathStyle = s3Compatible.s3ForcePathStyle + additionalProperties = s3Compatible.additionalProperties.toMutableMap() + } + + /** Access key for the bucket. */ + fun accessKey(accessKey: String) = accessKey(JsonField.of(accessKey)) + + /** + * Sets [Builder.accessKey] to an arbitrary JSON value. + * + * You should usually call [Builder.accessKey] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun accessKey(accessKey: JsonField) = apply { this.accessKey = accessKey } + + /** S3 bucket name. */ + fun bucket(bucket: String) = bucket(JsonField.of(bucket)) + + /** + * Sets [Builder.bucket] to an arbitrary JSON value. + * + * You should usually call [Builder.bucket] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun bucket(bucket: JsonField) = apply { this.bucket = bucket } + + /** Custom S3-compatible endpoint. */ + fun endpoint(endpoint: String) = endpoint(JsonField.of(endpoint)) + + /** + * Sets [Builder.endpoint] to an arbitrary JSON value. + * + * You should usually call [Builder.endpoint] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun endpoint(endpoint: JsonField) = apply { this.endpoint = endpoint } + + /** Display name of the origin. */ + fun name(name: String) = name(JsonField.of(name)) + + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun name(name: JsonField) = apply { this.name = name } + + /** Secret key for the bucket. */ + fun secretKey(secretKey: String) = secretKey(JsonField.of(secretKey)) + + /** + * Sets [Builder.secretKey] to an arbitrary JSON value. + * + * You should usually call [Builder.secretKey] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun secretKey(secretKey: JsonField) = apply { this.secretKey = secretKey } + + /** + * Sets the field to an arbitrary JSON value. + * + * It is usually unnecessary to call this method because the field defaults to the + * following: + * ```java + * JsonValue.from("S3_COMPATIBLE") + * ``` + * + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun type(type: JsonValue) = apply { this.type = type } + + /** URL used in the Canonical header (if enabled). */ + fun baseUrlForCanonicalHeader(baseUrlForCanonicalHeader: String) = + baseUrlForCanonicalHeader(JsonField.of(baseUrlForCanonicalHeader)) + + /** + * Sets [Builder.baseUrlForCanonicalHeader] to an arbitrary JSON value. + * + * You should usually call [Builder.baseUrlForCanonicalHeader] with a well-typed + * [String] value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun baseUrlForCanonicalHeader(baseUrlForCanonicalHeader: JsonField) = apply { + this.baseUrlForCanonicalHeader = baseUrlForCanonicalHeader + } + + /** Whether to send a Canonical header. */ + fun includeCanonicalHeader(includeCanonicalHeader: Boolean) = + includeCanonicalHeader(JsonField.of(includeCanonicalHeader)) + + /** + * Sets [Builder.includeCanonicalHeader] to an arbitrary JSON value. + * + * You should usually call [Builder.includeCanonicalHeader] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun includeCanonicalHeader(includeCanonicalHeader: JsonField) = apply { + this.includeCanonicalHeader = includeCanonicalHeader + } + + /** Path prefix inside the bucket. */ + fun prefix(prefix: String) = prefix(JsonField.of(prefix)) + + /** + * Sets [Builder.prefix] to an arbitrary JSON value. + * + * You should usually call [Builder.prefix] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun prefix(prefix: JsonField) = apply { this.prefix = prefix } + + /** Use path-style S3 URLs? */ + fun s3ForcePathStyle(s3ForcePathStyle: Boolean) = + s3ForcePathStyle(JsonField.of(s3ForcePathStyle)) + + /** + * Sets [Builder.s3ForcePathStyle] to an arbitrary JSON value. + * + * You should usually call [Builder.s3ForcePathStyle] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun s3ForcePathStyle(s3ForcePathStyle: JsonField) = apply { + this.s3ForcePathStyle = s3ForcePathStyle + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [S3Compatible]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .accessKey() + * .bucket() + * .endpoint() + * .name() + * .secretKey() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): S3Compatible = + S3Compatible( + checkRequired("accessKey", accessKey), + checkRequired("bucket", bucket), + checkRequired("endpoint", endpoint), + checkRequired("name", name), + checkRequired("secretKey", secretKey), + type, + baseUrlForCanonicalHeader, + includeCanonicalHeader, + prefix, + s3ForcePathStyle, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): S3Compatible = apply { + if (validated) { + return@apply + } + + accessKey() + bucket() + endpoint() + name() + secretKey() + _type().let { + if (it != JsonValue.from("S3_COMPATIBLE")) { + throw ImageKitInvalidDataException("'type' is invalid, received $it") + } + } + baseUrlForCanonicalHeader() + includeCanonicalHeader() + prefix() + s3ForcePathStyle() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (accessKey.asKnown().isPresent) 1 else 0) + + (if (bucket.asKnown().isPresent) 1 else 0) + + (if (endpoint.asKnown().isPresent) 1 else 0) + + (if (name.asKnown().isPresent) 1 else 0) + + (if (secretKey.asKnown().isPresent) 1 else 0) + + type.let { if (it == JsonValue.from("S3_COMPATIBLE")) 1 else 0 } + + (if (baseUrlForCanonicalHeader.asKnown().isPresent) 1 else 0) + + (if (includeCanonicalHeader.asKnown().isPresent) 1 else 0) + + (if (prefix.asKnown().isPresent) 1 else 0) + + (if (s3ForcePathStyle.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is S3Compatible && + accessKey == other.accessKey && + bucket == other.bucket && + endpoint == other.endpoint && + name == other.name && + secretKey == other.secretKey && + type == other.type && + baseUrlForCanonicalHeader == other.baseUrlForCanonicalHeader && + includeCanonicalHeader == other.includeCanonicalHeader && + prefix == other.prefix && + s3ForcePathStyle == other.s3ForcePathStyle && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + accessKey, + bucket, + endpoint, + name, + secretKey, + type, + baseUrlForCanonicalHeader, + includeCanonicalHeader, + prefix, + s3ForcePathStyle, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "S3Compatible{accessKey=$accessKey, bucket=$bucket, endpoint=$endpoint, name=$name, secretKey=$secretKey, type=$type, baseUrlForCanonicalHeader=$baseUrlForCanonicalHeader, includeCanonicalHeader=$includeCanonicalHeader, prefix=$prefix, s3ForcePathStyle=$s3ForcePathStyle, additionalProperties=$additionalProperties}" + } + + class CloudinaryBackup + private constructor( + private val accessKey: JsonField, + private val bucket: JsonField, + private val name: JsonField, + private val secretKey: JsonField, + private val type: JsonValue, + private val baseUrlForCanonicalHeader: JsonField, + private val includeCanonicalHeader: JsonField, + private val prefix: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("accessKey") + @ExcludeMissing + accessKey: JsonField = JsonMissing.of(), + @JsonProperty("bucket") @ExcludeMissing bucket: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("secretKey") + @ExcludeMissing + secretKey: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(), + @JsonProperty("baseUrlForCanonicalHeader") + @ExcludeMissing + baseUrlForCanonicalHeader: JsonField = JsonMissing.of(), + @JsonProperty("includeCanonicalHeader") + @ExcludeMissing + includeCanonicalHeader: JsonField = JsonMissing.of(), + @JsonProperty("prefix") @ExcludeMissing prefix: JsonField = JsonMissing.of(), + ) : this( + accessKey, + bucket, + name, + secretKey, + type, + baseUrlForCanonicalHeader, + includeCanonicalHeader, + prefix, + mutableMapOf(), + ) + + /** + * Access key for the bucket. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun accessKey(): String = accessKey.getRequired("accessKey") + + /** + * S3 bucket name. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun bucket(): String = bucket.getRequired("bucket") + + /** + * Display name of the origin. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun name(): String = name.getRequired("name") + + /** + * Secret key for the bucket. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun secretKey(): String = secretKey.getRequired("secretKey") + + /** + * Expected to always return the following: + * ```java + * JsonValue.from("CLOUDINARY_BACKUP") + * ``` + * + * However, this method can be useful for debugging and logging (e.g. if the server + * responded with an unexpected value). + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type + + /** + * URL used in the Canonical header (if enabled). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun baseUrlForCanonicalHeader(): Optional = + baseUrlForCanonicalHeader.getOptional("baseUrlForCanonicalHeader") + + /** + * Whether to send a Canonical header. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun includeCanonicalHeader(): Optional = + includeCanonicalHeader.getOptional("includeCanonicalHeader") + + /** + * Path prefix inside the bucket. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun prefix(): Optional = prefix.getOptional("prefix") + + /** + * Returns the raw JSON value of [accessKey]. + * + * Unlike [accessKey], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("accessKey") @ExcludeMissing fun _accessKey(): JsonField = accessKey + + /** + * Returns the raw JSON value of [bucket]. + * + * Unlike [bucket], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("bucket") @ExcludeMissing fun _bucket(): JsonField = bucket + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + + /** + * Returns the raw JSON value of [secretKey]. + * + * Unlike [secretKey], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("secretKey") @ExcludeMissing fun _secretKey(): JsonField = secretKey + + /** + * Returns the raw JSON value of [baseUrlForCanonicalHeader]. + * + * Unlike [baseUrlForCanonicalHeader], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("baseUrlForCanonicalHeader") + @ExcludeMissing + fun _baseUrlForCanonicalHeader(): JsonField = baseUrlForCanonicalHeader + + /** + * Returns the raw JSON value of [includeCanonicalHeader]. + * + * Unlike [includeCanonicalHeader], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("includeCanonicalHeader") + @ExcludeMissing + fun _includeCanonicalHeader(): JsonField = includeCanonicalHeader + + /** + * Returns the raw JSON value of [prefix]. + * + * Unlike [prefix], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("prefix") @ExcludeMissing fun _prefix(): JsonField = prefix + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [CloudinaryBackup]. + * + * The following fields are required: + * ```java + * .accessKey() + * .bucket() + * .name() + * .secretKey() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [CloudinaryBackup]. */ + class Builder internal constructor() { + + private var accessKey: JsonField? = null + private var bucket: JsonField? = null + private var name: JsonField? = null + private var secretKey: JsonField? = null + private var type: JsonValue = JsonValue.from("CLOUDINARY_BACKUP") + private var baseUrlForCanonicalHeader: JsonField = JsonMissing.of() + private var includeCanonicalHeader: JsonField = JsonMissing.of() + private var prefix: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(cloudinaryBackup: CloudinaryBackup) = apply { + accessKey = cloudinaryBackup.accessKey + bucket = cloudinaryBackup.bucket + name = cloudinaryBackup.name + secretKey = cloudinaryBackup.secretKey + type = cloudinaryBackup.type + baseUrlForCanonicalHeader = cloudinaryBackup.baseUrlForCanonicalHeader + includeCanonicalHeader = cloudinaryBackup.includeCanonicalHeader + prefix = cloudinaryBackup.prefix + additionalProperties = cloudinaryBackup.additionalProperties.toMutableMap() + } + + /** Access key for the bucket. */ + fun accessKey(accessKey: String) = accessKey(JsonField.of(accessKey)) + + /** + * Sets [Builder.accessKey] to an arbitrary JSON value. + * + * You should usually call [Builder.accessKey] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun accessKey(accessKey: JsonField) = apply { this.accessKey = accessKey } + + /** S3 bucket name. */ + fun bucket(bucket: String) = bucket(JsonField.of(bucket)) + + /** + * Sets [Builder.bucket] to an arbitrary JSON value. + * + * You should usually call [Builder.bucket] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun bucket(bucket: JsonField) = apply { this.bucket = bucket } + + /** Display name of the origin. */ + fun name(name: String) = name(JsonField.of(name)) + + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun name(name: JsonField) = apply { this.name = name } + + /** Secret key for the bucket. */ + fun secretKey(secretKey: String) = secretKey(JsonField.of(secretKey)) + + /** + * Sets [Builder.secretKey] to an arbitrary JSON value. + * + * You should usually call [Builder.secretKey] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun secretKey(secretKey: JsonField) = apply { this.secretKey = secretKey } + + /** + * Sets the field to an arbitrary JSON value. + * + * It is usually unnecessary to call this method because the field defaults to the + * following: + * ```java + * JsonValue.from("CLOUDINARY_BACKUP") + * ``` + * + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun type(type: JsonValue) = apply { this.type = type } + + /** URL used in the Canonical header (if enabled). */ + fun baseUrlForCanonicalHeader(baseUrlForCanonicalHeader: String) = + baseUrlForCanonicalHeader(JsonField.of(baseUrlForCanonicalHeader)) + + /** + * Sets [Builder.baseUrlForCanonicalHeader] to an arbitrary JSON value. + * + * You should usually call [Builder.baseUrlForCanonicalHeader] with a well-typed + * [String] value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun baseUrlForCanonicalHeader(baseUrlForCanonicalHeader: JsonField) = apply { + this.baseUrlForCanonicalHeader = baseUrlForCanonicalHeader + } + + /** Whether to send a Canonical header. */ + fun includeCanonicalHeader(includeCanonicalHeader: Boolean) = + includeCanonicalHeader(JsonField.of(includeCanonicalHeader)) + + /** + * Sets [Builder.includeCanonicalHeader] to an arbitrary JSON value. + * + * You should usually call [Builder.includeCanonicalHeader] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun includeCanonicalHeader(includeCanonicalHeader: JsonField) = apply { + this.includeCanonicalHeader = includeCanonicalHeader + } + + /** Path prefix inside the bucket. */ + fun prefix(prefix: String) = prefix(JsonField.of(prefix)) + + /** + * Sets [Builder.prefix] to an arbitrary JSON value. + * + * You should usually call [Builder.prefix] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun prefix(prefix: JsonField) = apply { this.prefix = prefix } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [CloudinaryBackup]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .accessKey() + * .bucket() + * .name() + * .secretKey() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): CloudinaryBackup = + CloudinaryBackup( + checkRequired("accessKey", accessKey), + checkRequired("bucket", bucket), + checkRequired("name", name), + checkRequired("secretKey", secretKey), + type, + baseUrlForCanonicalHeader, + includeCanonicalHeader, + prefix, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): CloudinaryBackup = apply { + if (validated) { + return@apply + } + + accessKey() + bucket() + name() + secretKey() + _type().let { + if (it != JsonValue.from("CLOUDINARY_BACKUP")) { + throw ImageKitInvalidDataException("'type' is invalid, received $it") + } + } + baseUrlForCanonicalHeader() + includeCanonicalHeader() + prefix() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (accessKey.asKnown().isPresent) 1 else 0) + + (if (bucket.asKnown().isPresent) 1 else 0) + + (if (name.asKnown().isPresent) 1 else 0) + + (if (secretKey.asKnown().isPresent) 1 else 0) + + type.let { if (it == JsonValue.from("CLOUDINARY_BACKUP")) 1 else 0 } + + (if (baseUrlForCanonicalHeader.asKnown().isPresent) 1 else 0) + + (if (includeCanonicalHeader.asKnown().isPresent) 1 else 0) + + (if (prefix.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is CloudinaryBackup && + accessKey == other.accessKey && + bucket == other.bucket && + name == other.name && + secretKey == other.secretKey && + type == other.type && + baseUrlForCanonicalHeader == other.baseUrlForCanonicalHeader && + includeCanonicalHeader == other.includeCanonicalHeader && + prefix == other.prefix && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + accessKey, + bucket, + name, + secretKey, + type, + baseUrlForCanonicalHeader, + includeCanonicalHeader, + prefix, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "CloudinaryBackup{accessKey=$accessKey, bucket=$bucket, name=$name, secretKey=$secretKey, type=$type, baseUrlForCanonicalHeader=$baseUrlForCanonicalHeader, includeCanonicalHeader=$includeCanonicalHeader, prefix=$prefix, additionalProperties=$additionalProperties}" + } + + class WebFolder + private constructor( + private val baseUrl: JsonField, + private val name: JsonField, + private val type: JsonValue, + private val baseUrlForCanonicalHeader: JsonField, + private val forwardHostHeaderToOrigin: JsonField, + private val includeCanonicalHeader: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("baseUrl") @ExcludeMissing baseUrl: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(), + @JsonProperty("baseUrlForCanonicalHeader") + @ExcludeMissing + baseUrlForCanonicalHeader: JsonField = JsonMissing.of(), + @JsonProperty("forwardHostHeaderToOrigin") + @ExcludeMissing + forwardHostHeaderToOrigin: JsonField = JsonMissing.of(), + @JsonProperty("includeCanonicalHeader") + @ExcludeMissing + includeCanonicalHeader: JsonField = JsonMissing.of(), + ) : this( + baseUrl, + name, + type, + baseUrlForCanonicalHeader, + forwardHostHeaderToOrigin, + includeCanonicalHeader, + mutableMapOf(), + ) + + /** + * Root URL for the web folder origin. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun baseUrl(): String = baseUrl.getRequired("baseUrl") + + /** + * Display name of the origin. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun name(): String = name.getRequired("name") + + /** + * Expected to always return the following: + * ```java + * JsonValue.from("WEB_FOLDER") + * ``` + * + * However, this method can be useful for debugging and logging (e.g. if the server + * responded with an unexpected value). + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type + + /** + * URL used in the Canonical header (if enabled). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun baseUrlForCanonicalHeader(): Optional = + baseUrlForCanonicalHeader.getOptional("baseUrlForCanonicalHeader") + + /** + * Forward the Host header to origin? + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun forwardHostHeaderToOrigin(): Optional = + forwardHostHeaderToOrigin.getOptional("forwardHostHeaderToOrigin") + + /** + * Whether to send a Canonical header. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun includeCanonicalHeader(): Optional = + includeCanonicalHeader.getOptional("includeCanonicalHeader") + + /** + * Returns the raw JSON value of [baseUrl]. + * + * Unlike [baseUrl], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("baseUrl") @ExcludeMissing fun _baseUrl(): JsonField = baseUrl + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + + /** + * Returns the raw JSON value of [baseUrlForCanonicalHeader]. + * + * Unlike [baseUrlForCanonicalHeader], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("baseUrlForCanonicalHeader") + @ExcludeMissing + fun _baseUrlForCanonicalHeader(): JsonField = baseUrlForCanonicalHeader + + /** + * Returns the raw JSON value of [forwardHostHeaderToOrigin]. + * + * Unlike [forwardHostHeaderToOrigin], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("forwardHostHeaderToOrigin") + @ExcludeMissing + fun _forwardHostHeaderToOrigin(): JsonField = forwardHostHeaderToOrigin + + /** + * Returns the raw JSON value of [includeCanonicalHeader]. + * + * Unlike [includeCanonicalHeader], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("includeCanonicalHeader") + @ExcludeMissing + fun _includeCanonicalHeader(): JsonField = includeCanonicalHeader + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [WebFolder]. + * + * The following fields are required: + * ```java + * .baseUrl() + * .name() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [WebFolder]. */ + class Builder internal constructor() { + + private var baseUrl: JsonField? = null + private var name: JsonField? = null + private var type: JsonValue = JsonValue.from("WEB_FOLDER") + private var baseUrlForCanonicalHeader: JsonField = JsonMissing.of() + private var forwardHostHeaderToOrigin: JsonField = JsonMissing.of() + private var includeCanonicalHeader: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(webFolder: WebFolder) = apply { + baseUrl = webFolder.baseUrl + name = webFolder.name + type = webFolder.type + baseUrlForCanonicalHeader = webFolder.baseUrlForCanonicalHeader + forwardHostHeaderToOrigin = webFolder.forwardHostHeaderToOrigin + includeCanonicalHeader = webFolder.includeCanonicalHeader + additionalProperties = webFolder.additionalProperties.toMutableMap() + } + + /** Root URL for the web folder origin. */ + fun baseUrl(baseUrl: String) = baseUrl(JsonField.of(baseUrl)) + + /** + * Sets [Builder.baseUrl] to an arbitrary JSON value. + * + * You should usually call [Builder.baseUrl] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun baseUrl(baseUrl: JsonField) = apply { this.baseUrl = baseUrl } + + /** Display name of the origin. */ + fun name(name: String) = name(JsonField.of(name)) + + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun name(name: JsonField) = apply { this.name = name } + + /** + * Sets the field to an arbitrary JSON value. + * + * It is usually unnecessary to call this method because the field defaults to the + * following: + * ```java + * JsonValue.from("WEB_FOLDER") + * ``` + * + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun type(type: JsonValue) = apply { this.type = type } + + /** URL used in the Canonical header (if enabled). */ + fun baseUrlForCanonicalHeader(baseUrlForCanonicalHeader: String) = + baseUrlForCanonicalHeader(JsonField.of(baseUrlForCanonicalHeader)) + + /** + * Sets [Builder.baseUrlForCanonicalHeader] to an arbitrary JSON value. + * + * You should usually call [Builder.baseUrlForCanonicalHeader] with a well-typed + * [String] value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun baseUrlForCanonicalHeader(baseUrlForCanonicalHeader: JsonField) = apply { + this.baseUrlForCanonicalHeader = baseUrlForCanonicalHeader + } + + /** Forward the Host header to origin? */ + fun forwardHostHeaderToOrigin(forwardHostHeaderToOrigin: Boolean) = + forwardHostHeaderToOrigin(JsonField.of(forwardHostHeaderToOrigin)) + + /** + * Sets [Builder.forwardHostHeaderToOrigin] to an arbitrary JSON value. + * + * You should usually call [Builder.forwardHostHeaderToOrigin] with a well-typed + * [Boolean] value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun forwardHostHeaderToOrigin(forwardHostHeaderToOrigin: JsonField) = apply { + this.forwardHostHeaderToOrigin = forwardHostHeaderToOrigin + } + + /** Whether to send a Canonical header. */ + fun includeCanonicalHeader(includeCanonicalHeader: Boolean) = + includeCanonicalHeader(JsonField.of(includeCanonicalHeader)) + + /** + * Sets [Builder.includeCanonicalHeader] to an arbitrary JSON value. + * + * You should usually call [Builder.includeCanonicalHeader] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun includeCanonicalHeader(includeCanonicalHeader: JsonField) = apply { + this.includeCanonicalHeader = includeCanonicalHeader + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [WebFolder]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .baseUrl() + * .name() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): WebFolder = + WebFolder( + checkRequired("baseUrl", baseUrl), + checkRequired("name", name), + type, + baseUrlForCanonicalHeader, + forwardHostHeaderToOrigin, + includeCanonicalHeader, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): WebFolder = apply { + if (validated) { + return@apply + } + + baseUrl() + name() + _type().let { + if (it != JsonValue.from("WEB_FOLDER")) { + throw ImageKitInvalidDataException("'type' is invalid, received $it") + } + } + baseUrlForCanonicalHeader() + forwardHostHeaderToOrigin() + includeCanonicalHeader() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (baseUrl.asKnown().isPresent) 1 else 0) + + (if (name.asKnown().isPresent) 1 else 0) + + type.let { if (it == JsonValue.from("WEB_FOLDER")) 1 else 0 } + + (if (baseUrlForCanonicalHeader.asKnown().isPresent) 1 else 0) + + (if (forwardHostHeaderToOrigin.asKnown().isPresent) 1 else 0) + + (if (includeCanonicalHeader.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is WebFolder && + baseUrl == other.baseUrl && + name == other.name && + type == other.type && + baseUrlForCanonicalHeader == other.baseUrlForCanonicalHeader && + forwardHostHeaderToOrigin == other.forwardHostHeaderToOrigin && + includeCanonicalHeader == other.includeCanonicalHeader && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + baseUrl, + name, + type, + baseUrlForCanonicalHeader, + forwardHostHeaderToOrigin, + includeCanonicalHeader, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "WebFolder{baseUrl=$baseUrl, name=$name, type=$type, baseUrlForCanonicalHeader=$baseUrlForCanonicalHeader, forwardHostHeaderToOrigin=$forwardHostHeaderToOrigin, includeCanonicalHeader=$includeCanonicalHeader, additionalProperties=$additionalProperties}" + } + + class WebProxy + private constructor( + private val name: JsonField, + private val type: JsonValue, + private val baseUrlForCanonicalHeader: JsonField, + private val includeCanonicalHeader: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(), + @JsonProperty("baseUrlForCanonicalHeader") + @ExcludeMissing + baseUrlForCanonicalHeader: JsonField = JsonMissing.of(), + @JsonProperty("includeCanonicalHeader") + @ExcludeMissing + includeCanonicalHeader: JsonField = JsonMissing.of(), + ) : this(name, type, baseUrlForCanonicalHeader, includeCanonicalHeader, mutableMapOf()) + + /** + * Display name of the origin. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun name(): String = name.getRequired("name") + + /** + * Expected to always return the following: + * ```java + * JsonValue.from("WEB_PROXY") + * ``` + * + * However, this method can be useful for debugging and logging (e.g. if the server + * responded with an unexpected value). + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type + + /** + * URL used in the Canonical header (if enabled). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun baseUrlForCanonicalHeader(): Optional = + baseUrlForCanonicalHeader.getOptional("baseUrlForCanonicalHeader") + + /** + * Whether to send a Canonical header. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun includeCanonicalHeader(): Optional = + includeCanonicalHeader.getOptional("includeCanonicalHeader") + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + + /** + * Returns the raw JSON value of [baseUrlForCanonicalHeader]. + * + * Unlike [baseUrlForCanonicalHeader], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("baseUrlForCanonicalHeader") + @ExcludeMissing + fun _baseUrlForCanonicalHeader(): JsonField = baseUrlForCanonicalHeader + + /** + * Returns the raw JSON value of [includeCanonicalHeader]. + * + * Unlike [includeCanonicalHeader], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("includeCanonicalHeader") + @ExcludeMissing + fun _includeCanonicalHeader(): JsonField = includeCanonicalHeader + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [WebProxy]. + * + * The following fields are required: + * ```java + * .name() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [WebProxy]. */ + class Builder internal constructor() { + + private var name: JsonField? = null + private var type: JsonValue = JsonValue.from("WEB_PROXY") + private var baseUrlForCanonicalHeader: JsonField = JsonMissing.of() + private var includeCanonicalHeader: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(webProxy: WebProxy) = apply { + name = webProxy.name + type = webProxy.type + baseUrlForCanonicalHeader = webProxy.baseUrlForCanonicalHeader + includeCanonicalHeader = webProxy.includeCanonicalHeader + additionalProperties = webProxy.additionalProperties.toMutableMap() + } + + /** Display name of the origin. */ + fun name(name: String) = name(JsonField.of(name)) + + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun name(name: JsonField) = apply { this.name = name } + + /** + * Sets the field to an arbitrary JSON value. + * + * It is usually unnecessary to call this method because the field defaults to the + * following: + * ```java + * JsonValue.from("WEB_PROXY") + * ``` + * + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun type(type: JsonValue) = apply { this.type = type } + + /** URL used in the Canonical header (if enabled). */ + fun baseUrlForCanonicalHeader(baseUrlForCanonicalHeader: String) = + baseUrlForCanonicalHeader(JsonField.of(baseUrlForCanonicalHeader)) + + /** + * Sets [Builder.baseUrlForCanonicalHeader] to an arbitrary JSON value. + * + * You should usually call [Builder.baseUrlForCanonicalHeader] with a well-typed + * [String] value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun baseUrlForCanonicalHeader(baseUrlForCanonicalHeader: JsonField) = apply { + this.baseUrlForCanonicalHeader = baseUrlForCanonicalHeader + } + + /** Whether to send a Canonical header. */ + fun includeCanonicalHeader(includeCanonicalHeader: Boolean) = + includeCanonicalHeader(JsonField.of(includeCanonicalHeader)) + + /** + * Sets [Builder.includeCanonicalHeader] to an arbitrary JSON value. + * + * You should usually call [Builder.includeCanonicalHeader] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun includeCanonicalHeader(includeCanonicalHeader: JsonField) = apply { + this.includeCanonicalHeader = includeCanonicalHeader + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [WebProxy]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .name() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): WebProxy = + WebProxy( + checkRequired("name", name), + type, + baseUrlForCanonicalHeader, + includeCanonicalHeader, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): WebProxy = apply { + if (validated) { + return@apply + } + + name() + _type().let { + if (it != JsonValue.from("WEB_PROXY")) { + throw ImageKitInvalidDataException("'type' is invalid, received $it") + } + } + baseUrlForCanonicalHeader() + includeCanonicalHeader() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (name.asKnown().isPresent) 1 else 0) + + type.let { if (it == JsonValue.from("WEB_PROXY")) 1 else 0 } + + (if (baseUrlForCanonicalHeader.asKnown().isPresent) 1 else 0) + + (if (includeCanonicalHeader.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is WebProxy && + name == other.name && + type == other.type && + baseUrlForCanonicalHeader == other.baseUrlForCanonicalHeader && + includeCanonicalHeader == other.includeCanonicalHeader && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + name, + type, + baseUrlForCanonicalHeader, + includeCanonicalHeader, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "WebProxy{name=$name, type=$type, baseUrlForCanonicalHeader=$baseUrlForCanonicalHeader, includeCanonicalHeader=$includeCanonicalHeader, additionalProperties=$additionalProperties}" + } + + class Gcs + private constructor( + private val bucket: JsonField, + private val clientEmail: JsonField, + private val name: JsonField, + private val privateKey: JsonField, + private val type: JsonValue, + private val baseUrlForCanonicalHeader: JsonField, + private val includeCanonicalHeader: JsonField, + private val prefix: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("bucket") @ExcludeMissing bucket: JsonField = JsonMissing.of(), + @JsonProperty("clientEmail") + @ExcludeMissing + clientEmail: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("privateKey") + @ExcludeMissing + privateKey: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(), + @JsonProperty("baseUrlForCanonicalHeader") + @ExcludeMissing + baseUrlForCanonicalHeader: JsonField = JsonMissing.of(), + @JsonProperty("includeCanonicalHeader") + @ExcludeMissing + includeCanonicalHeader: JsonField = JsonMissing.of(), + @JsonProperty("prefix") @ExcludeMissing prefix: JsonField = JsonMissing.of(), + ) : this( + bucket, + clientEmail, + name, + privateKey, + type, + baseUrlForCanonicalHeader, + includeCanonicalHeader, + prefix, + mutableMapOf(), + ) + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun bucket(): String = bucket.getRequired("bucket") + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun clientEmail(): String = clientEmail.getRequired("clientEmail") + + /** + * Display name of the origin. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun name(): String = name.getRequired("name") + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun privateKey(): String = privateKey.getRequired("privateKey") + + /** + * Expected to always return the following: + * ```java + * JsonValue.from("GCS") + * ``` + * + * However, this method can be useful for debugging and logging (e.g. if the server + * responded with an unexpected value). + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type + + /** + * URL used in the Canonical header (if enabled). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun baseUrlForCanonicalHeader(): Optional = + baseUrlForCanonicalHeader.getOptional("baseUrlForCanonicalHeader") + + /** + * Whether to send a Canonical header. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun includeCanonicalHeader(): Optional = + includeCanonicalHeader.getOptional("includeCanonicalHeader") + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun prefix(): Optional = prefix.getOptional("prefix") + + /** + * Returns the raw JSON value of [bucket]. + * + * Unlike [bucket], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("bucket") @ExcludeMissing fun _bucket(): JsonField = bucket + + /** + * Returns the raw JSON value of [clientEmail]. + * + * Unlike [clientEmail], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("clientEmail") + @ExcludeMissing + fun _clientEmail(): JsonField = clientEmail + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + + /** + * Returns the raw JSON value of [privateKey]. + * + * Unlike [privateKey], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("privateKey") + @ExcludeMissing + fun _privateKey(): JsonField = privateKey + + /** + * Returns the raw JSON value of [baseUrlForCanonicalHeader]. + * + * Unlike [baseUrlForCanonicalHeader], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("baseUrlForCanonicalHeader") + @ExcludeMissing + fun _baseUrlForCanonicalHeader(): JsonField = baseUrlForCanonicalHeader + + /** + * Returns the raw JSON value of [includeCanonicalHeader]. + * + * Unlike [includeCanonicalHeader], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("includeCanonicalHeader") + @ExcludeMissing + fun _includeCanonicalHeader(): JsonField = includeCanonicalHeader + + /** + * Returns the raw JSON value of [prefix]. + * + * Unlike [prefix], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("prefix") @ExcludeMissing fun _prefix(): JsonField = prefix + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Gcs]. + * + * The following fields are required: + * ```java + * .bucket() + * .clientEmail() + * .name() + * .privateKey() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Gcs]. */ + class Builder internal constructor() { + + private var bucket: JsonField? = null + private var clientEmail: JsonField? = null + private var name: JsonField? = null + private var privateKey: JsonField? = null + private var type: JsonValue = JsonValue.from("GCS") + private var baseUrlForCanonicalHeader: JsonField = JsonMissing.of() + private var includeCanonicalHeader: JsonField = JsonMissing.of() + private var prefix: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(gcs: Gcs) = apply { + bucket = gcs.bucket + clientEmail = gcs.clientEmail + name = gcs.name + privateKey = gcs.privateKey + type = gcs.type + baseUrlForCanonicalHeader = gcs.baseUrlForCanonicalHeader + includeCanonicalHeader = gcs.includeCanonicalHeader + prefix = gcs.prefix + additionalProperties = gcs.additionalProperties.toMutableMap() + } + + fun bucket(bucket: String) = bucket(JsonField.of(bucket)) + + /** + * Sets [Builder.bucket] to an arbitrary JSON value. + * + * You should usually call [Builder.bucket] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun bucket(bucket: JsonField) = apply { this.bucket = bucket } + + fun clientEmail(clientEmail: String) = clientEmail(JsonField.of(clientEmail)) + + /** + * Sets [Builder.clientEmail] to an arbitrary JSON value. + * + * You should usually call [Builder.clientEmail] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun clientEmail(clientEmail: JsonField) = apply { + this.clientEmail = clientEmail + } + + /** Display name of the origin. */ + fun name(name: String) = name(JsonField.of(name)) + + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun name(name: JsonField) = apply { this.name = name } + + fun privateKey(privateKey: String) = privateKey(JsonField.of(privateKey)) + + /** + * Sets [Builder.privateKey] to an arbitrary JSON value. + * + * You should usually call [Builder.privateKey] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun privateKey(privateKey: JsonField) = apply { this.privateKey = privateKey } + + /** + * Sets the field to an arbitrary JSON value. + * + * It is usually unnecessary to call this method because the field defaults to the + * following: + * ```java + * JsonValue.from("GCS") + * ``` + * + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun type(type: JsonValue) = apply { this.type = type } + + /** URL used in the Canonical header (if enabled). */ + fun baseUrlForCanonicalHeader(baseUrlForCanonicalHeader: String) = + baseUrlForCanonicalHeader(JsonField.of(baseUrlForCanonicalHeader)) + + /** + * Sets [Builder.baseUrlForCanonicalHeader] to an arbitrary JSON value. + * + * You should usually call [Builder.baseUrlForCanonicalHeader] with a well-typed + * [String] value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun baseUrlForCanonicalHeader(baseUrlForCanonicalHeader: JsonField) = apply { + this.baseUrlForCanonicalHeader = baseUrlForCanonicalHeader + } + + /** Whether to send a Canonical header. */ + fun includeCanonicalHeader(includeCanonicalHeader: Boolean) = + includeCanonicalHeader(JsonField.of(includeCanonicalHeader)) + + /** + * Sets [Builder.includeCanonicalHeader] to an arbitrary JSON value. + * + * You should usually call [Builder.includeCanonicalHeader] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun includeCanonicalHeader(includeCanonicalHeader: JsonField) = apply { + this.includeCanonicalHeader = includeCanonicalHeader + } + + fun prefix(prefix: String) = prefix(JsonField.of(prefix)) + + /** + * Sets [Builder.prefix] to an arbitrary JSON value. + * + * You should usually call [Builder.prefix] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun prefix(prefix: JsonField) = apply { this.prefix = prefix } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Gcs]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .bucket() + * .clientEmail() + * .name() + * .privateKey() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Gcs = + Gcs( + checkRequired("bucket", bucket), + checkRequired("clientEmail", clientEmail), + checkRequired("name", name), + checkRequired("privateKey", privateKey), + type, + baseUrlForCanonicalHeader, + includeCanonicalHeader, + prefix, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Gcs = apply { + if (validated) { + return@apply + } + + bucket() + clientEmail() + name() + privateKey() + _type().let { + if (it != JsonValue.from("GCS")) { + throw ImageKitInvalidDataException("'type' is invalid, received $it") + } + } + baseUrlForCanonicalHeader() + includeCanonicalHeader() + prefix() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (bucket.asKnown().isPresent) 1 else 0) + + (if (clientEmail.asKnown().isPresent) 1 else 0) + + (if (name.asKnown().isPresent) 1 else 0) + + (if (privateKey.asKnown().isPresent) 1 else 0) + + type.let { if (it == JsonValue.from("GCS")) 1 else 0 } + + (if (baseUrlForCanonicalHeader.asKnown().isPresent) 1 else 0) + + (if (includeCanonicalHeader.asKnown().isPresent) 1 else 0) + + (if (prefix.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Gcs && + bucket == other.bucket && + clientEmail == other.clientEmail && + name == other.name && + privateKey == other.privateKey && + type == other.type && + baseUrlForCanonicalHeader == other.baseUrlForCanonicalHeader && + includeCanonicalHeader == other.includeCanonicalHeader && + prefix == other.prefix && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + bucket, + clientEmail, + name, + privateKey, + type, + baseUrlForCanonicalHeader, + includeCanonicalHeader, + prefix, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Gcs{bucket=$bucket, clientEmail=$clientEmail, name=$name, privateKey=$privateKey, type=$type, baseUrlForCanonicalHeader=$baseUrlForCanonicalHeader, includeCanonicalHeader=$includeCanonicalHeader, prefix=$prefix, additionalProperties=$additionalProperties}" + } + + class AzureBlob + private constructor( + private val accountName: JsonField, + private val container: JsonField, + private val name: JsonField, + private val sasToken: JsonField, + private val type: JsonValue, + private val baseUrlForCanonicalHeader: JsonField, + private val includeCanonicalHeader: JsonField, + private val prefix: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("accountName") + @ExcludeMissing + accountName: JsonField = JsonMissing.of(), + @JsonProperty("container") + @ExcludeMissing + container: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("sasToken") + @ExcludeMissing + sasToken: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(), + @JsonProperty("baseUrlForCanonicalHeader") + @ExcludeMissing + baseUrlForCanonicalHeader: JsonField = JsonMissing.of(), + @JsonProperty("includeCanonicalHeader") + @ExcludeMissing + includeCanonicalHeader: JsonField = JsonMissing.of(), + @JsonProperty("prefix") @ExcludeMissing prefix: JsonField = JsonMissing.of(), + ) : this( + accountName, + container, + name, + sasToken, + type, + baseUrlForCanonicalHeader, + includeCanonicalHeader, + prefix, + mutableMapOf(), + ) + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun accountName(): String = accountName.getRequired("accountName") + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun container(): String = container.getRequired("container") + + /** + * Display name of the origin. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun name(): String = name.getRequired("name") + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun sasToken(): String = sasToken.getRequired("sasToken") + + /** + * Expected to always return the following: + * ```java + * JsonValue.from("AZURE_BLOB") + * ``` + * + * However, this method can be useful for debugging and logging (e.g. if the server + * responded with an unexpected value). + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type + + /** + * URL used in the Canonical header (if enabled). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun baseUrlForCanonicalHeader(): Optional = + baseUrlForCanonicalHeader.getOptional("baseUrlForCanonicalHeader") + + /** + * Whether to send a Canonical header. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun includeCanonicalHeader(): Optional = + includeCanonicalHeader.getOptional("includeCanonicalHeader") + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun prefix(): Optional = prefix.getOptional("prefix") + + /** + * Returns the raw JSON value of [accountName]. + * + * Unlike [accountName], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("accountName") + @ExcludeMissing + fun _accountName(): JsonField = accountName + + /** + * Returns the raw JSON value of [container]. + * + * Unlike [container], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("container") @ExcludeMissing fun _container(): JsonField = container + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + + /** + * Returns the raw JSON value of [sasToken]. + * + * Unlike [sasToken], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("sasToken") @ExcludeMissing fun _sasToken(): JsonField = sasToken + + /** + * Returns the raw JSON value of [baseUrlForCanonicalHeader]. + * + * Unlike [baseUrlForCanonicalHeader], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("baseUrlForCanonicalHeader") + @ExcludeMissing + fun _baseUrlForCanonicalHeader(): JsonField = baseUrlForCanonicalHeader + + /** + * Returns the raw JSON value of [includeCanonicalHeader]. + * + * Unlike [includeCanonicalHeader], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("includeCanonicalHeader") + @ExcludeMissing + fun _includeCanonicalHeader(): JsonField = includeCanonicalHeader + + /** + * Returns the raw JSON value of [prefix]. + * + * Unlike [prefix], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("prefix") @ExcludeMissing fun _prefix(): JsonField = prefix + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [AzureBlob]. + * + * The following fields are required: + * ```java + * .accountName() + * .container() + * .name() + * .sasToken() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [AzureBlob]. */ + class Builder internal constructor() { + + private var accountName: JsonField? = null + private var container: JsonField? = null + private var name: JsonField? = null + private var sasToken: JsonField? = null + private var type: JsonValue = JsonValue.from("AZURE_BLOB") + private var baseUrlForCanonicalHeader: JsonField = JsonMissing.of() + private var includeCanonicalHeader: JsonField = JsonMissing.of() + private var prefix: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(azureBlob: AzureBlob) = apply { + accountName = azureBlob.accountName + container = azureBlob.container + name = azureBlob.name + sasToken = azureBlob.sasToken + type = azureBlob.type + baseUrlForCanonicalHeader = azureBlob.baseUrlForCanonicalHeader + includeCanonicalHeader = azureBlob.includeCanonicalHeader + prefix = azureBlob.prefix + additionalProperties = azureBlob.additionalProperties.toMutableMap() + } + + fun accountName(accountName: String) = accountName(JsonField.of(accountName)) + + /** + * Sets [Builder.accountName] to an arbitrary JSON value. + * + * You should usually call [Builder.accountName] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun accountName(accountName: JsonField) = apply { + this.accountName = accountName + } + + fun container(container: String) = container(JsonField.of(container)) + + /** + * Sets [Builder.container] to an arbitrary JSON value. + * + * You should usually call [Builder.container] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun container(container: JsonField) = apply { this.container = container } + + /** Display name of the origin. */ + fun name(name: String) = name(JsonField.of(name)) + + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun name(name: JsonField) = apply { this.name = name } + + fun sasToken(sasToken: String) = sasToken(JsonField.of(sasToken)) + + /** + * Sets [Builder.sasToken] to an arbitrary JSON value. + * + * You should usually call [Builder.sasToken] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun sasToken(sasToken: JsonField) = apply { this.sasToken = sasToken } + + /** + * Sets the field to an arbitrary JSON value. + * + * It is usually unnecessary to call this method because the field defaults to the + * following: + * ```java + * JsonValue.from("AZURE_BLOB") + * ``` + * + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun type(type: JsonValue) = apply { this.type = type } + + /** URL used in the Canonical header (if enabled). */ + fun baseUrlForCanonicalHeader(baseUrlForCanonicalHeader: String) = + baseUrlForCanonicalHeader(JsonField.of(baseUrlForCanonicalHeader)) + + /** + * Sets [Builder.baseUrlForCanonicalHeader] to an arbitrary JSON value. + * + * You should usually call [Builder.baseUrlForCanonicalHeader] with a well-typed + * [String] value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun baseUrlForCanonicalHeader(baseUrlForCanonicalHeader: JsonField) = apply { + this.baseUrlForCanonicalHeader = baseUrlForCanonicalHeader + } + + /** Whether to send a Canonical header. */ + fun includeCanonicalHeader(includeCanonicalHeader: Boolean) = + includeCanonicalHeader(JsonField.of(includeCanonicalHeader)) + + /** + * Sets [Builder.includeCanonicalHeader] to an arbitrary JSON value. + * + * You should usually call [Builder.includeCanonicalHeader] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun includeCanonicalHeader(includeCanonicalHeader: JsonField) = apply { + this.includeCanonicalHeader = includeCanonicalHeader + } + + fun prefix(prefix: String) = prefix(JsonField.of(prefix)) + + /** + * Sets [Builder.prefix] to an arbitrary JSON value. + * + * You should usually call [Builder.prefix] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun prefix(prefix: JsonField) = apply { this.prefix = prefix } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [AzureBlob]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .accountName() + * .container() + * .name() + * .sasToken() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): AzureBlob = + AzureBlob( + checkRequired("accountName", accountName), + checkRequired("container", container), + checkRequired("name", name), + checkRequired("sasToken", sasToken), + type, + baseUrlForCanonicalHeader, + includeCanonicalHeader, + prefix, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): AzureBlob = apply { + if (validated) { + return@apply + } + + accountName() + container() + name() + sasToken() + _type().let { + if (it != JsonValue.from("AZURE_BLOB")) { + throw ImageKitInvalidDataException("'type' is invalid, received $it") + } + } + baseUrlForCanonicalHeader() + includeCanonicalHeader() + prefix() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (accountName.asKnown().isPresent) 1 else 0) + + (if (container.asKnown().isPresent) 1 else 0) + + (if (name.asKnown().isPresent) 1 else 0) + + (if (sasToken.asKnown().isPresent) 1 else 0) + + type.let { if (it == JsonValue.from("AZURE_BLOB")) 1 else 0 } + + (if (baseUrlForCanonicalHeader.asKnown().isPresent) 1 else 0) + + (if (includeCanonicalHeader.asKnown().isPresent) 1 else 0) + + (if (prefix.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is AzureBlob && + accountName == other.accountName && + container == other.container && + name == other.name && + sasToken == other.sasToken && + type == other.type && + baseUrlForCanonicalHeader == other.baseUrlForCanonicalHeader && + includeCanonicalHeader == other.includeCanonicalHeader && + prefix == other.prefix && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + accountName, + container, + name, + sasToken, + type, + baseUrlForCanonicalHeader, + includeCanonicalHeader, + prefix, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "AzureBlob{accountName=$accountName, container=$container, name=$name, sasToken=$sasToken, type=$type, baseUrlForCanonicalHeader=$baseUrlForCanonicalHeader, includeCanonicalHeader=$includeCanonicalHeader, prefix=$prefix, additionalProperties=$additionalProperties}" + } + + class AkeneoPim + private constructor( + private val baseUrl: JsonField, + private val clientId: JsonField, + private val clientSecret: JsonField, + private val name: JsonField, + private val password: JsonField, + private val type: JsonValue, + private val username: JsonField, + private val baseUrlForCanonicalHeader: JsonField, + private val includeCanonicalHeader: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("baseUrl") @ExcludeMissing baseUrl: JsonField = JsonMissing.of(), + @JsonProperty("clientId") + @ExcludeMissing + clientId: JsonField = JsonMissing.of(), + @JsonProperty("clientSecret") + @ExcludeMissing + clientSecret: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("password") + @ExcludeMissing + password: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(), + @JsonProperty("username") + @ExcludeMissing + username: JsonField = JsonMissing.of(), + @JsonProperty("baseUrlForCanonicalHeader") + @ExcludeMissing + baseUrlForCanonicalHeader: JsonField = JsonMissing.of(), + @JsonProperty("includeCanonicalHeader") + @ExcludeMissing + includeCanonicalHeader: JsonField = JsonMissing.of(), + ) : this( + baseUrl, + clientId, + clientSecret, + name, + password, + type, + username, + baseUrlForCanonicalHeader, + includeCanonicalHeader, + mutableMapOf(), + ) + + /** + * Akeneo instance base URL. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun baseUrl(): String = baseUrl.getRequired("baseUrl") + + /** + * Akeneo API client ID. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun clientId(): String = clientId.getRequired("clientId") + + /** + * Akeneo API client secret. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun clientSecret(): String = clientSecret.getRequired("clientSecret") + + /** + * Display name of the origin. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun name(): String = name.getRequired("name") + + /** + * Akeneo API password. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun password(): String = password.getRequired("password") + + /** + * Expected to always return the following: + * ```java + * JsonValue.from("AKENEO_PIM") + * ``` + * + * However, this method can be useful for debugging and logging (e.g. if the server + * responded with an unexpected value). + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type + + /** + * Akeneo API username. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun username(): String = username.getRequired("username") + + /** + * URL used in the Canonical header (if enabled). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun baseUrlForCanonicalHeader(): Optional = + baseUrlForCanonicalHeader.getOptional("baseUrlForCanonicalHeader") + + /** + * Whether to send a Canonical header. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun includeCanonicalHeader(): Optional = + includeCanonicalHeader.getOptional("includeCanonicalHeader") + + /** + * Returns the raw JSON value of [baseUrl]. + * + * Unlike [baseUrl], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("baseUrl") @ExcludeMissing fun _baseUrl(): JsonField = baseUrl + + /** + * Returns the raw JSON value of [clientId]. + * + * Unlike [clientId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("clientId") @ExcludeMissing fun _clientId(): JsonField = clientId + + /** + * Returns the raw JSON value of [clientSecret]. + * + * Unlike [clientSecret], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("clientSecret") + @ExcludeMissing + fun _clientSecret(): JsonField = clientSecret + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + + /** + * Returns the raw JSON value of [password]. + * + * Unlike [password], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("password") @ExcludeMissing fun _password(): JsonField = password + + /** + * Returns the raw JSON value of [username]. + * + * Unlike [username], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("username") @ExcludeMissing fun _username(): JsonField = username + + /** + * Returns the raw JSON value of [baseUrlForCanonicalHeader]. + * + * Unlike [baseUrlForCanonicalHeader], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("baseUrlForCanonicalHeader") + @ExcludeMissing + fun _baseUrlForCanonicalHeader(): JsonField = baseUrlForCanonicalHeader + + /** + * Returns the raw JSON value of [includeCanonicalHeader]. + * + * Unlike [includeCanonicalHeader], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("includeCanonicalHeader") + @ExcludeMissing + fun _includeCanonicalHeader(): JsonField = includeCanonicalHeader + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [AkeneoPim]. + * + * The following fields are required: + * ```java + * .baseUrl() + * .clientId() + * .clientSecret() + * .name() + * .password() + * .username() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [AkeneoPim]. */ + class Builder internal constructor() { + + private var baseUrl: JsonField? = null + private var clientId: JsonField? = null + private var clientSecret: JsonField? = null + private var name: JsonField? = null + private var password: JsonField? = null + private var type: JsonValue = JsonValue.from("AKENEO_PIM") + private var username: JsonField? = null + private var baseUrlForCanonicalHeader: JsonField = JsonMissing.of() + private var includeCanonicalHeader: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(akeneoPim: AkeneoPim) = apply { + baseUrl = akeneoPim.baseUrl + clientId = akeneoPim.clientId + clientSecret = akeneoPim.clientSecret + name = akeneoPim.name + password = akeneoPim.password + type = akeneoPim.type + username = akeneoPim.username + baseUrlForCanonicalHeader = akeneoPim.baseUrlForCanonicalHeader + includeCanonicalHeader = akeneoPim.includeCanonicalHeader + additionalProperties = akeneoPim.additionalProperties.toMutableMap() + } + + /** Akeneo instance base URL. */ + fun baseUrl(baseUrl: String) = baseUrl(JsonField.of(baseUrl)) + + /** + * Sets [Builder.baseUrl] to an arbitrary JSON value. + * + * You should usually call [Builder.baseUrl] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun baseUrl(baseUrl: JsonField) = apply { this.baseUrl = baseUrl } + + /** Akeneo API client ID. */ + fun clientId(clientId: String) = clientId(JsonField.of(clientId)) + + /** + * Sets [Builder.clientId] to an arbitrary JSON value. + * + * You should usually call [Builder.clientId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun clientId(clientId: JsonField) = apply { this.clientId = clientId } + + /** Akeneo API client secret. */ + fun clientSecret(clientSecret: String) = clientSecret(JsonField.of(clientSecret)) + + /** + * Sets [Builder.clientSecret] to an arbitrary JSON value. + * + * You should usually call [Builder.clientSecret] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun clientSecret(clientSecret: JsonField) = apply { + this.clientSecret = clientSecret + } + + /** Display name of the origin. */ + fun name(name: String) = name(JsonField.of(name)) + + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun name(name: JsonField) = apply { this.name = name } + + /** Akeneo API password. */ + fun password(password: String) = password(JsonField.of(password)) + + /** + * Sets [Builder.password] to an arbitrary JSON value. + * + * You should usually call [Builder.password] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun password(password: JsonField) = apply { this.password = password } + + /** + * Sets the field to an arbitrary JSON value. + * + * It is usually unnecessary to call this method because the field defaults to the + * following: + * ```java + * JsonValue.from("AKENEO_PIM") + * ``` + * + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun type(type: JsonValue) = apply { this.type = type } + + /** Akeneo API username. */ + fun username(username: String) = username(JsonField.of(username)) + + /** + * Sets [Builder.username] to an arbitrary JSON value. + * + * You should usually call [Builder.username] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun username(username: JsonField) = apply { this.username = username } + + /** URL used in the Canonical header (if enabled). */ + fun baseUrlForCanonicalHeader(baseUrlForCanonicalHeader: String) = + baseUrlForCanonicalHeader(JsonField.of(baseUrlForCanonicalHeader)) + + /** + * Sets [Builder.baseUrlForCanonicalHeader] to an arbitrary JSON value. + * + * You should usually call [Builder.baseUrlForCanonicalHeader] with a well-typed + * [String] value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun baseUrlForCanonicalHeader(baseUrlForCanonicalHeader: JsonField) = apply { + this.baseUrlForCanonicalHeader = baseUrlForCanonicalHeader + } + + /** Whether to send a Canonical header. */ + fun includeCanonicalHeader(includeCanonicalHeader: Boolean) = + includeCanonicalHeader(JsonField.of(includeCanonicalHeader)) + + /** + * Sets [Builder.includeCanonicalHeader] to an arbitrary JSON value. + * + * You should usually call [Builder.includeCanonicalHeader] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun includeCanonicalHeader(includeCanonicalHeader: JsonField) = apply { + this.includeCanonicalHeader = includeCanonicalHeader + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [AkeneoPim]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .baseUrl() + * .clientId() + * .clientSecret() + * .name() + * .password() + * .username() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): AkeneoPim = + AkeneoPim( + checkRequired("baseUrl", baseUrl), + checkRequired("clientId", clientId), + checkRequired("clientSecret", clientSecret), + checkRequired("name", name), + checkRequired("password", password), + type, + checkRequired("username", username), + baseUrlForCanonicalHeader, + includeCanonicalHeader, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): AkeneoPim = apply { + if (validated) { + return@apply + } + + baseUrl() + clientId() + clientSecret() + name() + password() + _type().let { + if (it != JsonValue.from("AKENEO_PIM")) { + throw ImageKitInvalidDataException("'type' is invalid, received $it") + } + } + username() + baseUrlForCanonicalHeader() + includeCanonicalHeader() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (baseUrl.asKnown().isPresent) 1 else 0) + + (if (clientId.asKnown().isPresent) 1 else 0) + + (if (clientSecret.asKnown().isPresent) 1 else 0) + + (if (name.asKnown().isPresent) 1 else 0) + + (if (password.asKnown().isPresent) 1 else 0) + + type.let { if (it == JsonValue.from("AKENEO_PIM")) 1 else 0 } + + (if (username.asKnown().isPresent) 1 else 0) + + (if (baseUrlForCanonicalHeader.asKnown().isPresent) 1 else 0) + + (if (includeCanonicalHeader.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is AkeneoPim && + baseUrl == other.baseUrl && + clientId == other.clientId && + clientSecret == other.clientSecret && + name == other.name && + password == other.password && + type == other.type && + username == other.username && + baseUrlForCanonicalHeader == other.baseUrlForCanonicalHeader && + includeCanonicalHeader == other.includeCanonicalHeader && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + baseUrl, + clientId, + clientSecret, + name, + password, + type, + username, + baseUrlForCanonicalHeader, + includeCanonicalHeader, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "AkeneoPim{baseUrl=$baseUrl, clientId=$clientId, clientSecret=$clientSecret, name=$name, password=$password, type=$type, username=$username, baseUrlForCanonicalHeader=$baseUrlForCanonicalHeader, includeCanonicalHeader=$includeCanonicalHeader, additionalProperties=$additionalProperties}" + } +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/accounts/origins/OriginResponse.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/accounts/origins/OriginResponse.kt new file mode 100644 index 0000000..5f8eed2 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/accounts/origins/OriginResponse.kt @@ -0,0 +1,3789 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.accounts.origins + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.fasterxml.jackson.core.JsonGenerator +import com.fasterxml.jackson.core.ObjectCodec +import com.fasterxml.jackson.databind.JsonNode +import com.fasterxml.jackson.databind.SerializerProvider +import com.fasterxml.jackson.databind.annotation.JsonDeserialize +import com.fasterxml.jackson.databind.annotation.JsonSerialize +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.imagekit.api.core.BaseDeserializer +import com.imagekit.api.core.BaseSerializer +import com.imagekit.api.core.ExcludeMissing +import com.imagekit.api.core.JsonField +import com.imagekit.api.core.JsonMissing +import com.imagekit.api.core.JsonValue +import com.imagekit.api.core.checkRequired +import com.imagekit.api.core.getOrThrow +import com.imagekit.api.errors.ImageKitInvalidDataException +import java.util.Collections +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** Origin object as returned by the API (sensitive fields removed). */ +@JsonDeserialize(using = OriginResponse.Deserializer::class) +@JsonSerialize(using = OriginResponse.Serializer::class) +class OriginResponse +private constructor( + private val s3: S3? = null, + private val s3Compatible: S3Compatible? = null, + private val cloudinaryBackup: CloudinaryBackup? = null, + private val webFolder: WebFolder? = null, + private val webProxy: WebProxy? = null, + private val gcs: Gcs? = null, + private val azureBlob: AzureBlob? = null, + private val akeneoPim: AkeneoPim? = null, + private val _json: JsonValue? = null, +) { + + fun s3(): Optional = Optional.ofNullable(s3) + + fun s3Compatible(): Optional = Optional.ofNullable(s3Compatible) + + fun cloudinaryBackup(): Optional = Optional.ofNullable(cloudinaryBackup) + + fun webFolder(): Optional = Optional.ofNullable(webFolder) + + fun webProxy(): Optional = Optional.ofNullable(webProxy) + + fun gcs(): Optional = Optional.ofNullable(gcs) + + fun azureBlob(): Optional = Optional.ofNullable(azureBlob) + + fun akeneoPim(): Optional = Optional.ofNullable(akeneoPim) + + fun isS3(): Boolean = s3 != null + + fun isS3Compatible(): Boolean = s3Compatible != null + + fun isCloudinaryBackup(): Boolean = cloudinaryBackup != null + + fun isWebFolder(): Boolean = webFolder != null + + fun isWebProxy(): Boolean = webProxy != null + + fun isGcs(): Boolean = gcs != null + + fun isAzureBlob(): Boolean = azureBlob != null + + fun isAkeneoPim(): Boolean = akeneoPim != null + + fun asS3(): S3 = s3.getOrThrow("s3") + + fun asS3Compatible(): S3Compatible = s3Compatible.getOrThrow("s3Compatible") + + fun asCloudinaryBackup(): CloudinaryBackup = cloudinaryBackup.getOrThrow("cloudinaryBackup") + + fun asWebFolder(): WebFolder = webFolder.getOrThrow("webFolder") + + fun asWebProxy(): WebProxy = webProxy.getOrThrow("webProxy") + + fun asGcs(): Gcs = gcs.getOrThrow("gcs") + + fun asAzureBlob(): AzureBlob = azureBlob.getOrThrow("azureBlob") + + fun asAkeneoPim(): AkeneoPim = akeneoPim.getOrThrow("akeneoPim") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + s3 != null -> visitor.visitS3(s3) + s3Compatible != null -> visitor.visitS3Compatible(s3Compatible) + cloudinaryBackup != null -> visitor.visitCloudinaryBackup(cloudinaryBackup) + webFolder != null -> visitor.visitWebFolder(webFolder) + webProxy != null -> visitor.visitWebProxy(webProxy) + gcs != null -> visitor.visitGcs(gcs) + azureBlob != null -> visitor.visitAzureBlob(azureBlob) + akeneoPim != null -> visitor.visitAkeneoPim(akeneoPim) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): OriginResponse = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitS3(s3: S3) { + s3.validate() + } + + override fun visitS3Compatible(s3Compatible: S3Compatible) { + s3Compatible.validate() + } + + override fun visitCloudinaryBackup(cloudinaryBackup: CloudinaryBackup) { + cloudinaryBackup.validate() + } + + override fun visitWebFolder(webFolder: WebFolder) { + webFolder.validate() + } + + override fun visitWebProxy(webProxy: WebProxy) { + webProxy.validate() + } + + override fun visitGcs(gcs: Gcs) { + gcs.validate() + } + + override fun visitAzureBlob(azureBlob: AzureBlob) { + azureBlob.validate() + } + + override fun visitAkeneoPim(akeneoPim: AkeneoPim) { + akeneoPim.validate() + } + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitS3(s3: S3) = s3.validity() + + override fun visitS3Compatible(s3Compatible: S3Compatible) = s3Compatible.validity() + + override fun visitCloudinaryBackup(cloudinaryBackup: CloudinaryBackup) = + cloudinaryBackup.validity() + + override fun visitWebFolder(webFolder: WebFolder) = webFolder.validity() + + override fun visitWebProxy(webProxy: WebProxy) = webProxy.validity() + + override fun visitGcs(gcs: Gcs) = gcs.validity() + + override fun visitAzureBlob(azureBlob: AzureBlob) = azureBlob.validity() + + override fun visitAkeneoPim(akeneoPim: AkeneoPim) = akeneoPim.validity() + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is OriginResponse && + s3 == other.s3 && + s3Compatible == other.s3Compatible && + cloudinaryBackup == other.cloudinaryBackup && + webFolder == other.webFolder && + webProxy == other.webProxy && + gcs == other.gcs && + azureBlob == other.azureBlob && + akeneoPim == other.akeneoPim + } + + override fun hashCode(): Int = + Objects.hash( + s3, + s3Compatible, + cloudinaryBackup, + webFolder, + webProxy, + gcs, + azureBlob, + akeneoPim, + ) + + override fun toString(): String = + when { + s3 != null -> "OriginResponse{s3=$s3}" + s3Compatible != null -> "OriginResponse{s3Compatible=$s3Compatible}" + cloudinaryBackup != null -> "OriginResponse{cloudinaryBackup=$cloudinaryBackup}" + webFolder != null -> "OriginResponse{webFolder=$webFolder}" + webProxy != null -> "OriginResponse{webProxy=$webProxy}" + gcs != null -> "OriginResponse{gcs=$gcs}" + azureBlob != null -> "OriginResponse{azureBlob=$azureBlob}" + akeneoPim != null -> "OriginResponse{akeneoPim=$akeneoPim}" + _json != null -> "OriginResponse{_unknown=$_json}" + else -> throw IllegalStateException("Invalid OriginResponse") + } + + companion object { + + @JvmStatic fun ofS3(s3: S3) = OriginResponse(s3 = s3) + + @JvmStatic + fun ofS3Compatible(s3Compatible: S3Compatible) = OriginResponse(s3Compatible = s3Compatible) + + @JvmStatic + fun ofCloudinaryBackup(cloudinaryBackup: CloudinaryBackup) = + OriginResponse(cloudinaryBackup = cloudinaryBackup) + + @JvmStatic fun ofWebFolder(webFolder: WebFolder) = OriginResponse(webFolder = webFolder) + + @JvmStatic fun ofWebProxy(webProxy: WebProxy) = OriginResponse(webProxy = webProxy) + + @JvmStatic fun ofGcs(gcs: Gcs) = OriginResponse(gcs = gcs) + + @JvmStatic fun ofAzureBlob(azureBlob: AzureBlob) = OriginResponse(azureBlob = azureBlob) + + @JvmStatic fun ofAkeneoPim(akeneoPim: AkeneoPim) = OriginResponse(akeneoPim = akeneoPim) + } + + /** + * An interface that defines how to map each variant of [OriginResponse] to a value of type [T]. + */ + interface Visitor { + + fun visitS3(s3: S3): T + + fun visitS3Compatible(s3Compatible: S3Compatible): T + + fun visitCloudinaryBackup(cloudinaryBackup: CloudinaryBackup): T + + fun visitWebFolder(webFolder: WebFolder): T + + fun visitWebProxy(webProxy: WebProxy): T + + fun visitGcs(gcs: Gcs): T + + fun visitAzureBlob(azureBlob: AzureBlob): T + + fun visitAkeneoPim(akeneoPim: AkeneoPim): T + + /** + * Maps an unknown variant of [OriginResponse] to a value of type [T]. + * + * An instance of [OriginResponse] can contain an unknown variant if it was deserialized + * from data that doesn't match any known variant. For example, if the SDK is on an older + * version than the API, then the API may respond with new variants that the SDK is unaware + * of. + * + * @throws ImageKitInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw ImageKitInvalidDataException("Unknown OriginResponse: $json") + } + } + + internal class Deserializer : BaseDeserializer(OriginResponse::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): OriginResponse { + val json = JsonValue.fromJsonNode(node) + val type = json.asObject().getOrNull()?.get("type")?.asString()?.getOrNull() + + when (type) { + "S3" -> { + return tryDeserialize(node, jacksonTypeRef())?.let { + OriginResponse(s3 = it, _json = json) + } ?: OriginResponse(_json = json) + } + "S3_COMPATIBLE" -> { + return tryDeserialize(node, jacksonTypeRef())?.let { + OriginResponse(s3Compatible = it, _json = json) + } ?: OriginResponse(_json = json) + } + "CLOUDINARY_BACKUP" -> { + return tryDeserialize(node, jacksonTypeRef())?.let { + OriginResponse(cloudinaryBackup = it, _json = json) + } ?: OriginResponse(_json = json) + } + "WEB_FOLDER" -> { + return tryDeserialize(node, jacksonTypeRef())?.let { + OriginResponse(webFolder = it, _json = json) + } ?: OriginResponse(_json = json) + } + "WEB_PROXY" -> { + return tryDeserialize(node, jacksonTypeRef())?.let { + OriginResponse(webProxy = it, _json = json) + } ?: OriginResponse(_json = json) + } + "GCS" -> { + return tryDeserialize(node, jacksonTypeRef())?.let { + OriginResponse(gcs = it, _json = json) + } ?: OriginResponse(_json = json) + } + "AZURE_BLOB" -> { + return tryDeserialize(node, jacksonTypeRef())?.let { + OriginResponse(azureBlob = it, _json = json) + } ?: OriginResponse(_json = json) + } + "AKENEO_PIM" -> { + return tryDeserialize(node, jacksonTypeRef())?.let { + OriginResponse(akeneoPim = it, _json = json) + } ?: OriginResponse(_json = json) + } + } + + return OriginResponse(_json = json) + } + } + + internal class Serializer : BaseSerializer(OriginResponse::class) { + + override fun serialize( + value: OriginResponse, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.s3 != null -> generator.writeObject(value.s3) + value.s3Compatible != null -> generator.writeObject(value.s3Compatible) + value.cloudinaryBackup != null -> generator.writeObject(value.cloudinaryBackup) + value.webFolder != null -> generator.writeObject(value.webFolder) + value.webProxy != null -> generator.writeObject(value.webProxy) + value.gcs != null -> generator.writeObject(value.gcs) + value.azureBlob != null -> generator.writeObject(value.azureBlob) + value.akeneoPim != null -> generator.writeObject(value.akeneoPim) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid OriginResponse") + } + } + } + + class S3 + private constructor( + private val id: JsonField, + private val bucket: JsonField, + private val includeCanonicalHeader: JsonField, + private val name: JsonField, + private val prefix: JsonField, + private val type: JsonValue, + private val baseUrlForCanonicalHeader: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), + @JsonProperty("bucket") @ExcludeMissing bucket: JsonField = JsonMissing.of(), + @JsonProperty("includeCanonicalHeader") + @ExcludeMissing + includeCanonicalHeader: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("prefix") @ExcludeMissing prefix: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(), + @JsonProperty("baseUrlForCanonicalHeader") + @ExcludeMissing + baseUrlForCanonicalHeader: JsonField = JsonMissing.of(), + ) : this( + id, + bucket, + includeCanonicalHeader, + name, + prefix, + type, + baseUrlForCanonicalHeader, + mutableMapOf(), + ) + + /** + * Unique identifier for the origin. This is generated by ImageKit when you create a new + * origin. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun id(): String = id.getRequired("id") + + /** + * S3 bucket name. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun bucket(): String = bucket.getRequired("bucket") + + /** + * Whether to send a Canonical header. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun includeCanonicalHeader(): Boolean = + includeCanonicalHeader.getRequired("includeCanonicalHeader") + + /** + * Display name of the origin. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun name(): String = name.getRequired("name") + + /** + * Path prefix inside the bucket. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun prefix(): String = prefix.getRequired("prefix") + + /** + * Expected to always return the following: + * ```java + * JsonValue.from("S3") + * ``` + * + * However, this method can be useful for debugging and logging (e.g. if the server + * responded with an unexpected value). + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type + + /** + * URL used in the Canonical header (if enabled). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun baseUrlForCanonicalHeader(): Optional = + baseUrlForCanonicalHeader.getOptional("baseUrlForCanonicalHeader") + + /** + * Returns the raw JSON value of [id]. + * + * Unlike [id], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id + + /** + * Returns the raw JSON value of [bucket]. + * + * Unlike [bucket], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("bucket") @ExcludeMissing fun _bucket(): JsonField = bucket + + /** + * Returns the raw JSON value of [includeCanonicalHeader]. + * + * Unlike [includeCanonicalHeader], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("includeCanonicalHeader") + @ExcludeMissing + fun _includeCanonicalHeader(): JsonField = includeCanonicalHeader + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + + /** + * Returns the raw JSON value of [prefix]. + * + * Unlike [prefix], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("prefix") @ExcludeMissing fun _prefix(): JsonField = prefix + + /** + * Returns the raw JSON value of [baseUrlForCanonicalHeader]. + * + * Unlike [baseUrlForCanonicalHeader], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("baseUrlForCanonicalHeader") + @ExcludeMissing + fun _baseUrlForCanonicalHeader(): JsonField = baseUrlForCanonicalHeader + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [S3]. + * + * The following fields are required: + * ```java + * .id() + * .bucket() + * .includeCanonicalHeader() + * .name() + * .prefix() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [S3]. */ + class Builder internal constructor() { + + private var id: JsonField? = null + private var bucket: JsonField? = null + private var includeCanonicalHeader: JsonField? = null + private var name: JsonField? = null + private var prefix: JsonField? = null + private var type: JsonValue = JsonValue.from("S3") + private var baseUrlForCanonicalHeader: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(s3: S3) = apply { + id = s3.id + bucket = s3.bucket + includeCanonicalHeader = s3.includeCanonicalHeader + name = s3.name + prefix = s3.prefix + type = s3.type + baseUrlForCanonicalHeader = s3.baseUrlForCanonicalHeader + additionalProperties = s3.additionalProperties.toMutableMap() + } + + /** + * Unique identifier for the origin. This is generated by ImageKit when you create a new + * origin. + */ + fun id(id: String) = id(JsonField.of(id)) + + /** + * Sets [Builder.id] to an arbitrary JSON value. + * + * You should usually call [Builder.id] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun id(id: JsonField) = apply { this.id = id } + + /** S3 bucket name. */ + fun bucket(bucket: String) = bucket(JsonField.of(bucket)) + + /** + * Sets [Builder.bucket] to an arbitrary JSON value. + * + * You should usually call [Builder.bucket] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun bucket(bucket: JsonField) = apply { this.bucket = bucket } + + /** Whether to send a Canonical header. */ + fun includeCanonicalHeader(includeCanonicalHeader: Boolean) = + includeCanonicalHeader(JsonField.of(includeCanonicalHeader)) + + /** + * Sets [Builder.includeCanonicalHeader] to an arbitrary JSON value. + * + * You should usually call [Builder.includeCanonicalHeader] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun includeCanonicalHeader(includeCanonicalHeader: JsonField) = apply { + this.includeCanonicalHeader = includeCanonicalHeader + } + + /** Display name of the origin. */ + fun name(name: String) = name(JsonField.of(name)) + + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun name(name: JsonField) = apply { this.name = name } + + /** Path prefix inside the bucket. */ + fun prefix(prefix: String) = prefix(JsonField.of(prefix)) + + /** + * Sets [Builder.prefix] to an arbitrary JSON value. + * + * You should usually call [Builder.prefix] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun prefix(prefix: JsonField) = apply { this.prefix = prefix } + + /** + * Sets the field to an arbitrary JSON value. + * + * It is usually unnecessary to call this method because the field defaults to the + * following: + * ```java + * JsonValue.from("S3") + * ``` + * + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun type(type: JsonValue) = apply { this.type = type } + + /** URL used in the Canonical header (if enabled). */ + fun baseUrlForCanonicalHeader(baseUrlForCanonicalHeader: String) = + baseUrlForCanonicalHeader(JsonField.of(baseUrlForCanonicalHeader)) + + /** + * Sets [Builder.baseUrlForCanonicalHeader] to an arbitrary JSON value. + * + * You should usually call [Builder.baseUrlForCanonicalHeader] with a well-typed + * [String] value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun baseUrlForCanonicalHeader(baseUrlForCanonicalHeader: JsonField) = apply { + this.baseUrlForCanonicalHeader = baseUrlForCanonicalHeader + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [S3]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .id() + * .bucket() + * .includeCanonicalHeader() + * .name() + * .prefix() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): S3 = + S3( + checkRequired("id", id), + checkRequired("bucket", bucket), + checkRequired("includeCanonicalHeader", includeCanonicalHeader), + checkRequired("name", name), + checkRequired("prefix", prefix), + type, + baseUrlForCanonicalHeader, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): S3 = apply { + if (validated) { + return@apply + } + + id() + bucket() + includeCanonicalHeader() + name() + prefix() + _type().let { + if (it != JsonValue.from("S3")) { + throw ImageKitInvalidDataException("'type' is invalid, received $it") + } + } + baseUrlForCanonicalHeader() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (id.asKnown().isPresent) 1 else 0) + + (if (bucket.asKnown().isPresent) 1 else 0) + + (if (includeCanonicalHeader.asKnown().isPresent) 1 else 0) + + (if (name.asKnown().isPresent) 1 else 0) + + (if (prefix.asKnown().isPresent) 1 else 0) + + type.let { if (it == JsonValue.from("S3")) 1 else 0 } + + (if (baseUrlForCanonicalHeader.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is S3 && + id == other.id && + bucket == other.bucket && + includeCanonicalHeader == other.includeCanonicalHeader && + name == other.name && + prefix == other.prefix && + type == other.type && + baseUrlForCanonicalHeader == other.baseUrlForCanonicalHeader && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + id, + bucket, + includeCanonicalHeader, + name, + prefix, + type, + baseUrlForCanonicalHeader, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "S3{id=$id, bucket=$bucket, includeCanonicalHeader=$includeCanonicalHeader, name=$name, prefix=$prefix, type=$type, baseUrlForCanonicalHeader=$baseUrlForCanonicalHeader, additionalProperties=$additionalProperties}" + } + + class S3Compatible + private constructor( + private val id: JsonField, + private val bucket: JsonField, + private val endpoint: JsonField, + private val includeCanonicalHeader: JsonField, + private val name: JsonField, + private val prefix: JsonField, + private val s3ForcePathStyle: JsonField, + private val type: JsonValue, + private val baseUrlForCanonicalHeader: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), + @JsonProperty("bucket") @ExcludeMissing bucket: JsonField = JsonMissing.of(), + @JsonProperty("endpoint") + @ExcludeMissing + endpoint: JsonField = JsonMissing.of(), + @JsonProperty("includeCanonicalHeader") + @ExcludeMissing + includeCanonicalHeader: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("prefix") @ExcludeMissing prefix: JsonField = JsonMissing.of(), + @JsonProperty("s3ForcePathStyle") + @ExcludeMissing + s3ForcePathStyle: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(), + @JsonProperty("baseUrlForCanonicalHeader") + @ExcludeMissing + baseUrlForCanonicalHeader: JsonField = JsonMissing.of(), + ) : this( + id, + bucket, + endpoint, + includeCanonicalHeader, + name, + prefix, + s3ForcePathStyle, + type, + baseUrlForCanonicalHeader, + mutableMapOf(), + ) + + /** + * Unique identifier for the origin. This is generated by ImageKit when you create a new + * origin. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun id(): String = id.getRequired("id") + + /** + * S3 bucket name. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun bucket(): String = bucket.getRequired("bucket") + + /** + * Custom S3-compatible endpoint. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun endpoint(): String = endpoint.getRequired("endpoint") + + /** + * Whether to send a Canonical header. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun includeCanonicalHeader(): Boolean = + includeCanonicalHeader.getRequired("includeCanonicalHeader") + + /** + * Display name of the origin. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun name(): String = name.getRequired("name") + + /** + * Path prefix inside the bucket. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun prefix(): String = prefix.getRequired("prefix") + + /** + * Use path-style S3 URLs? + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun s3ForcePathStyle(): Boolean = s3ForcePathStyle.getRequired("s3ForcePathStyle") + + /** + * Expected to always return the following: + * ```java + * JsonValue.from("S3_COMPATIBLE") + * ``` + * + * However, this method can be useful for debugging and logging (e.g. if the server + * responded with an unexpected value). + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type + + /** + * URL used in the Canonical header (if enabled). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun baseUrlForCanonicalHeader(): Optional = + baseUrlForCanonicalHeader.getOptional("baseUrlForCanonicalHeader") + + /** + * Returns the raw JSON value of [id]. + * + * Unlike [id], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id + + /** + * Returns the raw JSON value of [bucket]. + * + * Unlike [bucket], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("bucket") @ExcludeMissing fun _bucket(): JsonField = bucket + + /** + * Returns the raw JSON value of [endpoint]. + * + * Unlike [endpoint], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("endpoint") @ExcludeMissing fun _endpoint(): JsonField = endpoint + + /** + * Returns the raw JSON value of [includeCanonicalHeader]. + * + * Unlike [includeCanonicalHeader], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("includeCanonicalHeader") + @ExcludeMissing + fun _includeCanonicalHeader(): JsonField = includeCanonicalHeader + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + + /** + * Returns the raw JSON value of [prefix]. + * + * Unlike [prefix], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("prefix") @ExcludeMissing fun _prefix(): JsonField = prefix + + /** + * Returns the raw JSON value of [s3ForcePathStyle]. + * + * Unlike [s3ForcePathStyle], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("s3ForcePathStyle") + @ExcludeMissing + fun _s3ForcePathStyle(): JsonField = s3ForcePathStyle + + /** + * Returns the raw JSON value of [baseUrlForCanonicalHeader]. + * + * Unlike [baseUrlForCanonicalHeader], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("baseUrlForCanonicalHeader") + @ExcludeMissing + fun _baseUrlForCanonicalHeader(): JsonField = baseUrlForCanonicalHeader + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [S3Compatible]. + * + * The following fields are required: + * ```java + * .id() + * .bucket() + * .endpoint() + * .includeCanonicalHeader() + * .name() + * .prefix() + * .s3ForcePathStyle() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [S3Compatible]. */ + class Builder internal constructor() { + + private var id: JsonField? = null + private var bucket: JsonField? = null + private var endpoint: JsonField? = null + private var includeCanonicalHeader: JsonField? = null + private var name: JsonField? = null + private var prefix: JsonField? = null + private var s3ForcePathStyle: JsonField? = null + private var type: JsonValue = JsonValue.from("S3_COMPATIBLE") + private var baseUrlForCanonicalHeader: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(s3Compatible: S3Compatible) = apply { + id = s3Compatible.id + bucket = s3Compatible.bucket + endpoint = s3Compatible.endpoint + includeCanonicalHeader = s3Compatible.includeCanonicalHeader + name = s3Compatible.name + prefix = s3Compatible.prefix + s3ForcePathStyle = s3Compatible.s3ForcePathStyle + type = s3Compatible.type + baseUrlForCanonicalHeader = s3Compatible.baseUrlForCanonicalHeader + additionalProperties = s3Compatible.additionalProperties.toMutableMap() + } + + /** + * Unique identifier for the origin. This is generated by ImageKit when you create a new + * origin. + */ + fun id(id: String) = id(JsonField.of(id)) + + /** + * Sets [Builder.id] to an arbitrary JSON value. + * + * You should usually call [Builder.id] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun id(id: JsonField) = apply { this.id = id } + + /** S3 bucket name. */ + fun bucket(bucket: String) = bucket(JsonField.of(bucket)) + + /** + * Sets [Builder.bucket] to an arbitrary JSON value. + * + * You should usually call [Builder.bucket] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun bucket(bucket: JsonField) = apply { this.bucket = bucket } + + /** Custom S3-compatible endpoint. */ + fun endpoint(endpoint: String) = endpoint(JsonField.of(endpoint)) + + /** + * Sets [Builder.endpoint] to an arbitrary JSON value. + * + * You should usually call [Builder.endpoint] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun endpoint(endpoint: JsonField) = apply { this.endpoint = endpoint } + + /** Whether to send a Canonical header. */ + fun includeCanonicalHeader(includeCanonicalHeader: Boolean) = + includeCanonicalHeader(JsonField.of(includeCanonicalHeader)) + + /** + * Sets [Builder.includeCanonicalHeader] to an arbitrary JSON value. + * + * You should usually call [Builder.includeCanonicalHeader] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun includeCanonicalHeader(includeCanonicalHeader: JsonField) = apply { + this.includeCanonicalHeader = includeCanonicalHeader + } + + /** Display name of the origin. */ + fun name(name: String) = name(JsonField.of(name)) + + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun name(name: JsonField) = apply { this.name = name } + + /** Path prefix inside the bucket. */ + fun prefix(prefix: String) = prefix(JsonField.of(prefix)) + + /** + * Sets [Builder.prefix] to an arbitrary JSON value. + * + * You should usually call [Builder.prefix] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun prefix(prefix: JsonField) = apply { this.prefix = prefix } + + /** Use path-style S3 URLs? */ + fun s3ForcePathStyle(s3ForcePathStyle: Boolean) = + s3ForcePathStyle(JsonField.of(s3ForcePathStyle)) + + /** + * Sets [Builder.s3ForcePathStyle] to an arbitrary JSON value. + * + * You should usually call [Builder.s3ForcePathStyle] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun s3ForcePathStyle(s3ForcePathStyle: JsonField) = apply { + this.s3ForcePathStyle = s3ForcePathStyle + } + + /** + * Sets the field to an arbitrary JSON value. + * + * It is usually unnecessary to call this method because the field defaults to the + * following: + * ```java + * JsonValue.from("S3_COMPATIBLE") + * ``` + * + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun type(type: JsonValue) = apply { this.type = type } + + /** URL used in the Canonical header (if enabled). */ + fun baseUrlForCanonicalHeader(baseUrlForCanonicalHeader: String) = + baseUrlForCanonicalHeader(JsonField.of(baseUrlForCanonicalHeader)) + + /** + * Sets [Builder.baseUrlForCanonicalHeader] to an arbitrary JSON value. + * + * You should usually call [Builder.baseUrlForCanonicalHeader] with a well-typed + * [String] value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun baseUrlForCanonicalHeader(baseUrlForCanonicalHeader: JsonField) = apply { + this.baseUrlForCanonicalHeader = baseUrlForCanonicalHeader + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [S3Compatible]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .id() + * .bucket() + * .endpoint() + * .includeCanonicalHeader() + * .name() + * .prefix() + * .s3ForcePathStyle() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): S3Compatible = + S3Compatible( + checkRequired("id", id), + checkRequired("bucket", bucket), + checkRequired("endpoint", endpoint), + checkRequired("includeCanonicalHeader", includeCanonicalHeader), + checkRequired("name", name), + checkRequired("prefix", prefix), + checkRequired("s3ForcePathStyle", s3ForcePathStyle), + type, + baseUrlForCanonicalHeader, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): S3Compatible = apply { + if (validated) { + return@apply + } + + id() + bucket() + endpoint() + includeCanonicalHeader() + name() + prefix() + s3ForcePathStyle() + _type().let { + if (it != JsonValue.from("S3_COMPATIBLE")) { + throw ImageKitInvalidDataException("'type' is invalid, received $it") + } + } + baseUrlForCanonicalHeader() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (id.asKnown().isPresent) 1 else 0) + + (if (bucket.asKnown().isPresent) 1 else 0) + + (if (endpoint.asKnown().isPresent) 1 else 0) + + (if (includeCanonicalHeader.asKnown().isPresent) 1 else 0) + + (if (name.asKnown().isPresent) 1 else 0) + + (if (prefix.asKnown().isPresent) 1 else 0) + + (if (s3ForcePathStyle.asKnown().isPresent) 1 else 0) + + type.let { if (it == JsonValue.from("S3_COMPATIBLE")) 1 else 0 } + + (if (baseUrlForCanonicalHeader.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is S3Compatible && + id == other.id && + bucket == other.bucket && + endpoint == other.endpoint && + includeCanonicalHeader == other.includeCanonicalHeader && + name == other.name && + prefix == other.prefix && + s3ForcePathStyle == other.s3ForcePathStyle && + type == other.type && + baseUrlForCanonicalHeader == other.baseUrlForCanonicalHeader && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + id, + bucket, + endpoint, + includeCanonicalHeader, + name, + prefix, + s3ForcePathStyle, + type, + baseUrlForCanonicalHeader, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "S3Compatible{id=$id, bucket=$bucket, endpoint=$endpoint, includeCanonicalHeader=$includeCanonicalHeader, name=$name, prefix=$prefix, s3ForcePathStyle=$s3ForcePathStyle, type=$type, baseUrlForCanonicalHeader=$baseUrlForCanonicalHeader, additionalProperties=$additionalProperties}" + } + + class CloudinaryBackup + private constructor( + private val id: JsonField, + private val bucket: JsonField, + private val includeCanonicalHeader: JsonField, + private val name: JsonField, + private val prefix: JsonField, + private val type: JsonValue, + private val baseUrlForCanonicalHeader: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), + @JsonProperty("bucket") @ExcludeMissing bucket: JsonField = JsonMissing.of(), + @JsonProperty("includeCanonicalHeader") + @ExcludeMissing + includeCanonicalHeader: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("prefix") @ExcludeMissing prefix: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(), + @JsonProperty("baseUrlForCanonicalHeader") + @ExcludeMissing + baseUrlForCanonicalHeader: JsonField = JsonMissing.of(), + ) : this( + id, + bucket, + includeCanonicalHeader, + name, + prefix, + type, + baseUrlForCanonicalHeader, + mutableMapOf(), + ) + + /** + * Unique identifier for the origin. This is generated by ImageKit when you create a new + * origin. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun id(): String = id.getRequired("id") + + /** + * S3 bucket name. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun bucket(): String = bucket.getRequired("bucket") + + /** + * Whether to send a Canonical header. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun includeCanonicalHeader(): Boolean = + includeCanonicalHeader.getRequired("includeCanonicalHeader") + + /** + * Display name of the origin. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun name(): String = name.getRequired("name") + + /** + * Path prefix inside the bucket. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun prefix(): String = prefix.getRequired("prefix") + + /** + * Expected to always return the following: + * ```java + * JsonValue.from("CLOUDINARY_BACKUP") + * ``` + * + * However, this method can be useful for debugging and logging (e.g. if the server + * responded with an unexpected value). + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type + + /** + * URL used in the Canonical header (if enabled). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun baseUrlForCanonicalHeader(): Optional = + baseUrlForCanonicalHeader.getOptional("baseUrlForCanonicalHeader") + + /** + * Returns the raw JSON value of [id]. + * + * Unlike [id], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id + + /** + * Returns the raw JSON value of [bucket]. + * + * Unlike [bucket], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("bucket") @ExcludeMissing fun _bucket(): JsonField = bucket + + /** + * Returns the raw JSON value of [includeCanonicalHeader]. + * + * Unlike [includeCanonicalHeader], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("includeCanonicalHeader") + @ExcludeMissing + fun _includeCanonicalHeader(): JsonField = includeCanonicalHeader + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + + /** + * Returns the raw JSON value of [prefix]. + * + * Unlike [prefix], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("prefix") @ExcludeMissing fun _prefix(): JsonField = prefix + + /** + * Returns the raw JSON value of [baseUrlForCanonicalHeader]. + * + * Unlike [baseUrlForCanonicalHeader], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("baseUrlForCanonicalHeader") + @ExcludeMissing + fun _baseUrlForCanonicalHeader(): JsonField = baseUrlForCanonicalHeader + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [CloudinaryBackup]. + * + * The following fields are required: + * ```java + * .id() + * .bucket() + * .includeCanonicalHeader() + * .name() + * .prefix() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [CloudinaryBackup]. */ + class Builder internal constructor() { + + private var id: JsonField? = null + private var bucket: JsonField? = null + private var includeCanonicalHeader: JsonField? = null + private var name: JsonField? = null + private var prefix: JsonField? = null + private var type: JsonValue = JsonValue.from("CLOUDINARY_BACKUP") + private var baseUrlForCanonicalHeader: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(cloudinaryBackup: CloudinaryBackup) = apply { + id = cloudinaryBackup.id + bucket = cloudinaryBackup.bucket + includeCanonicalHeader = cloudinaryBackup.includeCanonicalHeader + name = cloudinaryBackup.name + prefix = cloudinaryBackup.prefix + type = cloudinaryBackup.type + baseUrlForCanonicalHeader = cloudinaryBackup.baseUrlForCanonicalHeader + additionalProperties = cloudinaryBackup.additionalProperties.toMutableMap() + } + + /** + * Unique identifier for the origin. This is generated by ImageKit when you create a new + * origin. + */ + fun id(id: String) = id(JsonField.of(id)) + + /** + * Sets [Builder.id] to an arbitrary JSON value. + * + * You should usually call [Builder.id] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun id(id: JsonField) = apply { this.id = id } + + /** S3 bucket name. */ + fun bucket(bucket: String) = bucket(JsonField.of(bucket)) + + /** + * Sets [Builder.bucket] to an arbitrary JSON value. + * + * You should usually call [Builder.bucket] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun bucket(bucket: JsonField) = apply { this.bucket = bucket } + + /** Whether to send a Canonical header. */ + fun includeCanonicalHeader(includeCanonicalHeader: Boolean) = + includeCanonicalHeader(JsonField.of(includeCanonicalHeader)) + + /** + * Sets [Builder.includeCanonicalHeader] to an arbitrary JSON value. + * + * You should usually call [Builder.includeCanonicalHeader] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun includeCanonicalHeader(includeCanonicalHeader: JsonField) = apply { + this.includeCanonicalHeader = includeCanonicalHeader + } + + /** Display name of the origin. */ + fun name(name: String) = name(JsonField.of(name)) + + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun name(name: JsonField) = apply { this.name = name } + + /** Path prefix inside the bucket. */ + fun prefix(prefix: String) = prefix(JsonField.of(prefix)) + + /** + * Sets [Builder.prefix] to an arbitrary JSON value. + * + * You should usually call [Builder.prefix] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun prefix(prefix: JsonField) = apply { this.prefix = prefix } + + /** + * Sets the field to an arbitrary JSON value. + * + * It is usually unnecessary to call this method because the field defaults to the + * following: + * ```java + * JsonValue.from("CLOUDINARY_BACKUP") + * ``` + * + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun type(type: JsonValue) = apply { this.type = type } + + /** URL used in the Canonical header (if enabled). */ + fun baseUrlForCanonicalHeader(baseUrlForCanonicalHeader: String) = + baseUrlForCanonicalHeader(JsonField.of(baseUrlForCanonicalHeader)) + + /** + * Sets [Builder.baseUrlForCanonicalHeader] to an arbitrary JSON value. + * + * You should usually call [Builder.baseUrlForCanonicalHeader] with a well-typed + * [String] value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun baseUrlForCanonicalHeader(baseUrlForCanonicalHeader: JsonField) = apply { + this.baseUrlForCanonicalHeader = baseUrlForCanonicalHeader + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [CloudinaryBackup]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .id() + * .bucket() + * .includeCanonicalHeader() + * .name() + * .prefix() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): CloudinaryBackup = + CloudinaryBackup( + checkRequired("id", id), + checkRequired("bucket", bucket), + checkRequired("includeCanonicalHeader", includeCanonicalHeader), + checkRequired("name", name), + checkRequired("prefix", prefix), + type, + baseUrlForCanonicalHeader, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): CloudinaryBackup = apply { + if (validated) { + return@apply + } + + id() + bucket() + includeCanonicalHeader() + name() + prefix() + _type().let { + if (it != JsonValue.from("CLOUDINARY_BACKUP")) { + throw ImageKitInvalidDataException("'type' is invalid, received $it") + } + } + baseUrlForCanonicalHeader() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (id.asKnown().isPresent) 1 else 0) + + (if (bucket.asKnown().isPresent) 1 else 0) + + (if (includeCanonicalHeader.asKnown().isPresent) 1 else 0) + + (if (name.asKnown().isPresent) 1 else 0) + + (if (prefix.asKnown().isPresent) 1 else 0) + + type.let { if (it == JsonValue.from("CLOUDINARY_BACKUP")) 1 else 0 } + + (if (baseUrlForCanonicalHeader.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is CloudinaryBackup && + id == other.id && + bucket == other.bucket && + includeCanonicalHeader == other.includeCanonicalHeader && + name == other.name && + prefix == other.prefix && + type == other.type && + baseUrlForCanonicalHeader == other.baseUrlForCanonicalHeader && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + id, + bucket, + includeCanonicalHeader, + name, + prefix, + type, + baseUrlForCanonicalHeader, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "CloudinaryBackup{id=$id, bucket=$bucket, includeCanonicalHeader=$includeCanonicalHeader, name=$name, prefix=$prefix, type=$type, baseUrlForCanonicalHeader=$baseUrlForCanonicalHeader, additionalProperties=$additionalProperties}" + } + + class WebFolder + private constructor( + private val id: JsonField, + private val baseUrl: JsonField, + private val forwardHostHeaderToOrigin: JsonField, + private val includeCanonicalHeader: JsonField, + private val name: JsonField, + private val type: JsonValue, + private val baseUrlForCanonicalHeader: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), + @JsonProperty("baseUrl") @ExcludeMissing baseUrl: JsonField = JsonMissing.of(), + @JsonProperty("forwardHostHeaderToOrigin") + @ExcludeMissing + forwardHostHeaderToOrigin: JsonField = JsonMissing.of(), + @JsonProperty("includeCanonicalHeader") + @ExcludeMissing + includeCanonicalHeader: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(), + @JsonProperty("baseUrlForCanonicalHeader") + @ExcludeMissing + baseUrlForCanonicalHeader: JsonField = JsonMissing.of(), + ) : this( + id, + baseUrl, + forwardHostHeaderToOrigin, + includeCanonicalHeader, + name, + type, + baseUrlForCanonicalHeader, + mutableMapOf(), + ) + + /** + * Unique identifier for the origin. This is generated by ImageKit when you create a new + * origin. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun id(): String = id.getRequired("id") + + /** + * Root URL for the web folder origin. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun baseUrl(): String = baseUrl.getRequired("baseUrl") + + /** + * Forward the Host header to origin? + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun forwardHostHeaderToOrigin(): Boolean = + forwardHostHeaderToOrigin.getRequired("forwardHostHeaderToOrigin") + + /** + * Whether to send a Canonical header. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun includeCanonicalHeader(): Boolean = + includeCanonicalHeader.getRequired("includeCanonicalHeader") + + /** + * Display name of the origin. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun name(): String = name.getRequired("name") + + /** + * Expected to always return the following: + * ```java + * JsonValue.from("WEB_FOLDER") + * ``` + * + * However, this method can be useful for debugging and logging (e.g. if the server + * responded with an unexpected value). + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type + + /** + * URL used in the Canonical header (if enabled). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun baseUrlForCanonicalHeader(): Optional = + baseUrlForCanonicalHeader.getOptional("baseUrlForCanonicalHeader") + + /** + * Returns the raw JSON value of [id]. + * + * Unlike [id], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id + + /** + * Returns the raw JSON value of [baseUrl]. + * + * Unlike [baseUrl], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("baseUrl") @ExcludeMissing fun _baseUrl(): JsonField = baseUrl + + /** + * Returns the raw JSON value of [forwardHostHeaderToOrigin]. + * + * Unlike [forwardHostHeaderToOrigin], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("forwardHostHeaderToOrigin") + @ExcludeMissing + fun _forwardHostHeaderToOrigin(): JsonField = forwardHostHeaderToOrigin + + /** + * Returns the raw JSON value of [includeCanonicalHeader]. + * + * Unlike [includeCanonicalHeader], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("includeCanonicalHeader") + @ExcludeMissing + fun _includeCanonicalHeader(): JsonField = includeCanonicalHeader + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + + /** + * Returns the raw JSON value of [baseUrlForCanonicalHeader]. + * + * Unlike [baseUrlForCanonicalHeader], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("baseUrlForCanonicalHeader") + @ExcludeMissing + fun _baseUrlForCanonicalHeader(): JsonField = baseUrlForCanonicalHeader + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [WebFolder]. + * + * The following fields are required: + * ```java + * .id() + * .baseUrl() + * .forwardHostHeaderToOrigin() + * .includeCanonicalHeader() + * .name() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [WebFolder]. */ + class Builder internal constructor() { + + private var id: JsonField? = null + private var baseUrl: JsonField? = null + private var forwardHostHeaderToOrigin: JsonField? = null + private var includeCanonicalHeader: JsonField? = null + private var name: JsonField? = null + private var type: JsonValue = JsonValue.from("WEB_FOLDER") + private var baseUrlForCanonicalHeader: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(webFolder: WebFolder) = apply { + id = webFolder.id + baseUrl = webFolder.baseUrl + forwardHostHeaderToOrigin = webFolder.forwardHostHeaderToOrigin + includeCanonicalHeader = webFolder.includeCanonicalHeader + name = webFolder.name + type = webFolder.type + baseUrlForCanonicalHeader = webFolder.baseUrlForCanonicalHeader + additionalProperties = webFolder.additionalProperties.toMutableMap() + } + + /** + * Unique identifier for the origin. This is generated by ImageKit when you create a new + * origin. + */ + fun id(id: String) = id(JsonField.of(id)) + + /** + * Sets [Builder.id] to an arbitrary JSON value. + * + * You should usually call [Builder.id] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun id(id: JsonField) = apply { this.id = id } + + /** Root URL for the web folder origin. */ + fun baseUrl(baseUrl: String) = baseUrl(JsonField.of(baseUrl)) + + /** + * Sets [Builder.baseUrl] to an arbitrary JSON value. + * + * You should usually call [Builder.baseUrl] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun baseUrl(baseUrl: JsonField) = apply { this.baseUrl = baseUrl } + + /** Forward the Host header to origin? */ + fun forwardHostHeaderToOrigin(forwardHostHeaderToOrigin: Boolean) = + forwardHostHeaderToOrigin(JsonField.of(forwardHostHeaderToOrigin)) + + /** + * Sets [Builder.forwardHostHeaderToOrigin] to an arbitrary JSON value. + * + * You should usually call [Builder.forwardHostHeaderToOrigin] with a well-typed + * [Boolean] value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun forwardHostHeaderToOrigin(forwardHostHeaderToOrigin: JsonField) = apply { + this.forwardHostHeaderToOrigin = forwardHostHeaderToOrigin + } + + /** Whether to send a Canonical header. */ + fun includeCanonicalHeader(includeCanonicalHeader: Boolean) = + includeCanonicalHeader(JsonField.of(includeCanonicalHeader)) + + /** + * Sets [Builder.includeCanonicalHeader] to an arbitrary JSON value. + * + * You should usually call [Builder.includeCanonicalHeader] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun includeCanonicalHeader(includeCanonicalHeader: JsonField) = apply { + this.includeCanonicalHeader = includeCanonicalHeader + } + + /** Display name of the origin. */ + fun name(name: String) = name(JsonField.of(name)) + + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun name(name: JsonField) = apply { this.name = name } + + /** + * Sets the field to an arbitrary JSON value. + * + * It is usually unnecessary to call this method because the field defaults to the + * following: + * ```java + * JsonValue.from("WEB_FOLDER") + * ``` + * + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun type(type: JsonValue) = apply { this.type = type } + + /** URL used in the Canonical header (if enabled). */ + fun baseUrlForCanonicalHeader(baseUrlForCanonicalHeader: String) = + baseUrlForCanonicalHeader(JsonField.of(baseUrlForCanonicalHeader)) + + /** + * Sets [Builder.baseUrlForCanonicalHeader] to an arbitrary JSON value. + * + * You should usually call [Builder.baseUrlForCanonicalHeader] with a well-typed + * [String] value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun baseUrlForCanonicalHeader(baseUrlForCanonicalHeader: JsonField) = apply { + this.baseUrlForCanonicalHeader = baseUrlForCanonicalHeader + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [WebFolder]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .id() + * .baseUrl() + * .forwardHostHeaderToOrigin() + * .includeCanonicalHeader() + * .name() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): WebFolder = + WebFolder( + checkRequired("id", id), + checkRequired("baseUrl", baseUrl), + checkRequired("forwardHostHeaderToOrigin", forwardHostHeaderToOrigin), + checkRequired("includeCanonicalHeader", includeCanonicalHeader), + checkRequired("name", name), + type, + baseUrlForCanonicalHeader, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): WebFolder = apply { + if (validated) { + return@apply + } + + id() + baseUrl() + forwardHostHeaderToOrigin() + includeCanonicalHeader() + name() + _type().let { + if (it != JsonValue.from("WEB_FOLDER")) { + throw ImageKitInvalidDataException("'type' is invalid, received $it") + } + } + baseUrlForCanonicalHeader() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (id.asKnown().isPresent) 1 else 0) + + (if (baseUrl.asKnown().isPresent) 1 else 0) + + (if (forwardHostHeaderToOrigin.asKnown().isPresent) 1 else 0) + + (if (includeCanonicalHeader.asKnown().isPresent) 1 else 0) + + (if (name.asKnown().isPresent) 1 else 0) + + type.let { if (it == JsonValue.from("WEB_FOLDER")) 1 else 0 } + + (if (baseUrlForCanonicalHeader.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is WebFolder && + id == other.id && + baseUrl == other.baseUrl && + forwardHostHeaderToOrigin == other.forwardHostHeaderToOrigin && + includeCanonicalHeader == other.includeCanonicalHeader && + name == other.name && + type == other.type && + baseUrlForCanonicalHeader == other.baseUrlForCanonicalHeader && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + id, + baseUrl, + forwardHostHeaderToOrigin, + includeCanonicalHeader, + name, + type, + baseUrlForCanonicalHeader, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "WebFolder{id=$id, baseUrl=$baseUrl, forwardHostHeaderToOrigin=$forwardHostHeaderToOrigin, includeCanonicalHeader=$includeCanonicalHeader, name=$name, type=$type, baseUrlForCanonicalHeader=$baseUrlForCanonicalHeader, additionalProperties=$additionalProperties}" + } + + class WebProxy + private constructor( + private val id: JsonField, + private val includeCanonicalHeader: JsonField, + private val name: JsonField, + private val type: JsonValue, + private val baseUrlForCanonicalHeader: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), + @JsonProperty("includeCanonicalHeader") + @ExcludeMissing + includeCanonicalHeader: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(), + @JsonProperty("baseUrlForCanonicalHeader") + @ExcludeMissing + baseUrlForCanonicalHeader: JsonField = JsonMissing.of(), + ) : this(id, includeCanonicalHeader, name, type, baseUrlForCanonicalHeader, mutableMapOf()) + + /** + * Unique identifier for the origin. This is generated by ImageKit when you create a new + * origin. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun id(): String = id.getRequired("id") + + /** + * Whether to send a Canonical header. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun includeCanonicalHeader(): Boolean = + includeCanonicalHeader.getRequired("includeCanonicalHeader") + + /** + * Display name of the origin. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun name(): String = name.getRequired("name") + + /** + * Expected to always return the following: + * ```java + * JsonValue.from("WEB_PROXY") + * ``` + * + * However, this method can be useful for debugging and logging (e.g. if the server + * responded with an unexpected value). + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type + + /** + * URL used in the Canonical header (if enabled). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun baseUrlForCanonicalHeader(): Optional = + baseUrlForCanonicalHeader.getOptional("baseUrlForCanonicalHeader") + + /** + * Returns the raw JSON value of [id]. + * + * Unlike [id], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id + + /** + * Returns the raw JSON value of [includeCanonicalHeader]. + * + * Unlike [includeCanonicalHeader], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("includeCanonicalHeader") + @ExcludeMissing + fun _includeCanonicalHeader(): JsonField = includeCanonicalHeader + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + + /** + * Returns the raw JSON value of [baseUrlForCanonicalHeader]. + * + * Unlike [baseUrlForCanonicalHeader], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("baseUrlForCanonicalHeader") + @ExcludeMissing + fun _baseUrlForCanonicalHeader(): JsonField = baseUrlForCanonicalHeader + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [WebProxy]. + * + * The following fields are required: + * ```java + * .id() + * .includeCanonicalHeader() + * .name() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [WebProxy]. */ + class Builder internal constructor() { + + private var id: JsonField? = null + private var includeCanonicalHeader: JsonField? = null + private var name: JsonField? = null + private var type: JsonValue = JsonValue.from("WEB_PROXY") + private var baseUrlForCanonicalHeader: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(webProxy: WebProxy) = apply { + id = webProxy.id + includeCanonicalHeader = webProxy.includeCanonicalHeader + name = webProxy.name + type = webProxy.type + baseUrlForCanonicalHeader = webProxy.baseUrlForCanonicalHeader + additionalProperties = webProxy.additionalProperties.toMutableMap() + } + + /** + * Unique identifier for the origin. This is generated by ImageKit when you create a new + * origin. + */ + fun id(id: String) = id(JsonField.of(id)) + + /** + * Sets [Builder.id] to an arbitrary JSON value. + * + * You should usually call [Builder.id] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun id(id: JsonField) = apply { this.id = id } + + /** Whether to send a Canonical header. */ + fun includeCanonicalHeader(includeCanonicalHeader: Boolean) = + includeCanonicalHeader(JsonField.of(includeCanonicalHeader)) + + /** + * Sets [Builder.includeCanonicalHeader] to an arbitrary JSON value. + * + * You should usually call [Builder.includeCanonicalHeader] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun includeCanonicalHeader(includeCanonicalHeader: JsonField) = apply { + this.includeCanonicalHeader = includeCanonicalHeader + } + + /** Display name of the origin. */ + fun name(name: String) = name(JsonField.of(name)) + + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun name(name: JsonField) = apply { this.name = name } + + /** + * Sets the field to an arbitrary JSON value. + * + * It is usually unnecessary to call this method because the field defaults to the + * following: + * ```java + * JsonValue.from("WEB_PROXY") + * ``` + * + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun type(type: JsonValue) = apply { this.type = type } + + /** URL used in the Canonical header (if enabled). */ + fun baseUrlForCanonicalHeader(baseUrlForCanonicalHeader: String) = + baseUrlForCanonicalHeader(JsonField.of(baseUrlForCanonicalHeader)) + + /** + * Sets [Builder.baseUrlForCanonicalHeader] to an arbitrary JSON value. + * + * You should usually call [Builder.baseUrlForCanonicalHeader] with a well-typed + * [String] value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun baseUrlForCanonicalHeader(baseUrlForCanonicalHeader: JsonField) = apply { + this.baseUrlForCanonicalHeader = baseUrlForCanonicalHeader + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [WebProxy]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .id() + * .includeCanonicalHeader() + * .name() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): WebProxy = + WebProxy( + checkRequired("id", id), + checkRequired("includeCanonicalHeader", includeCanonicalHeader), + checkRequired("name", name), + type, + baseUrlForCanonicalHeader, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): WebProxy = apply { + if (validated) { + return@apply + } + + id() + includeCanonicalHeader() + name() + _type().let { + if (it != JsonValue.from("WEB_PROXY")) { + throw ImageKitInvalidDataException("'type' is invalid, received $it") + } + } + baseUrlForCanonicalHeader() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (id.asKnown().isPresent) 1 else 0) + + (if (includeCanonicalHeader.asKnown().isPresent) 1 else 0) + + (if (name.asKnown().isPresent) 1 else 0) + + type.let { if (it == JsonValue.from("WEB_PROXY")) 1 else 0 } + + (if (baseUrlForCanonicalHeader.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is WebProxy && + id == other.id && + includeCanonicalHeader == other.includeCanonicalHeader && + name == other.name && + type == other.type && + baseUrlForCanonicalHeader == other.baseUrlForCanonicalHeader && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + id, + includeCanonicalHeader, + name, + type, + baseUrlForCanonicalHeader, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "WebProxy{id=$id, includeCanonicalHeader=$includeCanonicalHeader, name=$name, type=$type, baseUrlForCanonicalHeader=$baseUrlForCanonicalHeader, additionalProperties=$additionalProperties}" + } + + class Gcs + private constructor( + private val id: JsonField, + private val bucket: JsonField, + private val clientEmail: JsonField, + private val includeCanonicalHeader: JsonField, + private val name: JsonField, + private val prefix: JsonField, + private val type: JsonValue, + private val baseUrlForCanonicalHeader: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), + @JsonProperty("bucket") @ExcludeMissing bucket: JsonField = JsonMissing.of(), + @JsonProperty("clientEmail") + @ExcludeMissing + clientEmail: JsonField = JsonMissing.of(), + @JsonProperty("includeCanonicalHeader") + @ExcludeMissing + includeCanonicalHeader: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("prefix") @ExcludeMissing prefix: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(), + @JsonProperty("baseUrlForCanonicalHeader") + @ExcludeMissing + baseUrlForCanonicalHeader: JsonField = JsonMissing.of(), + ) : this( + id, + bucket, + clientEmail, + includeCanonicalHeader, + name, + prefix, + type, + baseUrlForCanonicalHeader, + mutableMapOf(), + ) + + /** + * Unique identifier for the origin. This is generated by ImageKit when you create a new + * origin. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun id(): String = id.getRequired("id") + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun bucket(): String = bucket.getRequired("bucket") + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun clientEmail(): String = clientEmail.getRequired("clientEmail") + + /** + * Whether to send a Canonical header. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun includeCanonicalHeader(): Boolean = + includeCanonicalHeader.getRequired("includeCanonicalHeader") + + /** + * Display name of the origin. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun name(): String = name.getRequired("name") + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun prefix(): String = prefix.getRequired("prefix") + + /** + * Expected to always return the following: + * ```java + * JsonValue.from("GCS") + * ``` + * + * However, this method can be useful for debugging and logging (e.g. if the server + * responded with an unexpected value). + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type + + /** + * URL used in the Canonical header (if enabled). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun baseUrlForCanonicalHeader(): Optional = + baseUrlForCanonicalHeader.getOptional("baseUrlForCanonicalHeader") + + /** + * Returns the raw JSON value of [id]. + * + * Unlike [id], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id + + /** + * Returns the raw JSON value of [bucket]. + * + * Unlike [bucket], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("bucket") @ExcludeMissing fun _bucket(): JsonField = bucket + + /** + * Returns the raw JSON value of [clientEmail]. + * + * Unlike [clientEmail], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("clientEmail") + @ExcludeMissing + fun _clientEmail(): JsonField = clientEmail + + /** + * Returns the raw JSON value of [includeCanonicalHeader]. + * + * Unlike [includeCanonicalHeader], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("includeCanonicalHeader") + @ExcludeMissing + fun _includeCanonicalHeader(): JsonField = includeCanonicalHeader + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + + /** + * Returns the raw JSON value of [prefix]. + * + * Unlike [prefix], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("prefix") @ExcludeMissing fun _prefix(): JsonField = prefix + + /** + * Returns the raw JSON value of [baseUrlForCanonicalHeader]. + * + * Unlike [baseUrlForCanonicalHeader], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("baseUrlForCanonicalHeader") + @ExcludeMissing + fun _baseUrlForCanonicalHeader(): JsonField = baseUrlForCanonicalHeader + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Gcs]. + * + * The following fields are required: + * ```java + * .id() + * .bucket() + * .clientEmail() + * .includeCanonicalHeader() + * .name() + * .prefix() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Gcs]. */ + class Builder internal constructor() { + + private var id: JsonField? = null + private var bucket: JsonField? = null + private var clientEmail: JsonField? = null + private var includeCanonicalHeader: JsonField? = null + private var name: JsonField? = null + private var prefix: JsonField? = null + private var type: JsonValue = JsonValue.from("GCS") + private var baseUrlForCanonicalHeader: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(gcs: Gcs) = apply { + id = gcs.id + bucket = gcs.bucket + clientEmail = gcs.clientEmail + includeCanonicalHeader = gcs.includeCanonicalHeader + name = gcs.name + prefix = gcs.prefix + type = gcs.type + baseUrlForCanonicalHeader = gcs.baseUrlForCanonicalHeader + additionalProperties = gcs.additionalProperties.toMutableMap() + } + + /** + * Unique identifier for the origin. This is generated by ImageKit when you create a new + * origin. + */ + fun id(id: String) = id(JsonField.of(id)) + + /** + * Sets [Builder.id] to an arbitrary JSON value. + * + * You should usually call [Builder.id] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun id(id: JsonField) = apply { this.id = id } + + fun bucket(bucket: String) = bucket(JsonField.of(bucket)) + + /** + * Sets [Builder.bucket] to an arbitrary JSON value. + * + * You should usually call [Builder.bucket] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun bucket(bucket: JsonField) = apply { this.bucket = bucket } + + fun clientEmail(clientEmail: String) = clientEmail(JsonField.of(clientEmail)) + + /** + * Sets [Builder.clientEmail] to an arbitrary JSON value. + * + * You should usually call [Builder.clientEmail] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun clientEmail(clientEmail: JsonField) = apply { + this.clientEmail = clientEmail + } + + /** Whether to send a Canonical header. */ + fun includeCanonicalHeader(includeCanonicalHeader: Boolean) = + includeCanonicalHeader(JsonField.of(includeCanonicalHeader)) + + /** + * Sets [Builder.includeCanonicalHeader] to an arbitrary JSON value. + * + * You should usually call [Builder.includeCanonicalHeader] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun includeCanonicalHeader(includeCanonicalHeader: JsonField) = apply { + this.includeCanonicalHeader = includeCanonicalHeader + } + + /** Display name of the origin. */ + fun name(name: String) = name(JsonField.of(name)) + + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun name(name: JsonField) = apply { this.name = name } + + fun prefix(prefix: String) = prefix(JsonField.of(prefix)) + + /** + * Sets [Builder.prefix] to an arbitrary JSON value. + * + * You should usually call [Builder.prefix] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun prefix(prefix: JsonField) = apply { this.prefix = prefix } + + /** + * Sets the field to an arbitrary JSON value. + * + * It is usually unnecessary to call this method because the field defaults to the + * following: + * ```java + * JsonValue.from("GCS") + * ``` + * + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun type(type: JsonValue) = apply { this.type = type } + + /** URL used in the Canonical header (if enabled). */ + fun baseUrlForCanonicalHeader(baseUrlForCanonicalHeader: String) = + baseUrlForCanonicalHeader(JsonField.of(baseUrlForCanonicalHeader)) + + /** + * Sets [Builder.baseUrlForCanonicalHeader] to an arbitrary JSON value. + * + * You should usually call [Builder.baseUrlForCanonicalHeader] with a well-typed + * [String] value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun baseUrlForCanonicalHeader(baseUrlForCanonicalHeader: JsonField) = apply { + this.baseUrlForCanonicalHeader = baseUrlForCanonicalHeader + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Gcs]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .id() + * .bucket() + * .clientEmail() + * .includeCanonicalHeader() + * .name() + * .prefix() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Gcs = + Gcs( + checkRequired("id", id), + checkRequired("bucket", bucket), + checkRequired("clientEmail", clientEmail), + checkRequired("includeCanonicalHeader", includeCanonicalHeader), + checkRequired("name", name), + checkRequired("prefix", prefix), + type, + baseUrlForCanonicalHeader, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Gcs = apply { + if (validated) { + return@apply + } + + id() + bucket() + clientEmail() + includeCanonicalHeader() + name() + prefix() + _type().let { + if (it != JsonValue.from("GCS")) { + throw ImageKitInvalidDataException("'type' is invalid, received $it") + } + } + baseUrlForCanonicalHeader() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (id.asKnown().isPresent) 1 else 0) + + (if (bucket.asKnown().isPresent) 1 else 0) + + (if (clientEmail.asKnown().isPresent) 1 else 0) + + (if (includeCanonicalHeader.asKnown().isPresent) 1 else 0) + + (if (name.asKnown().isPresent) 1 else 0) + + (if (prefix.asKnown().isPresent) 1 else 0) + + type.let { if (it == JsonValue.from("GCS")) 1 else 0 } + + (if (baseUrlForCanonicalHeader.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Gcs && + id == other.id && + bucket == other.bucket && + clientEmail == other.clientEmail && + includeCanonicalHeader == other.includeCanonicalHeader && + name == other.name && + prefix == other.prefix && + type == other.type && + baseUrlForCanonicalHeader == other.baseUrlForCanonicalHeader && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + id, + bucket, + clientEmail, + includeCanonicalHeader, + name, + prefix, + type, + baseUrlForCanonicalHeader, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Gcs{id=$id, bucket=$bucket, clientEmail=$clientEmail, includeCanonicalHeader=$includeCanonicalHeader, name=$name, prefix=$prefix, type=$type, baseUrlForCanonicalHeader=$baseUrlForCanonicalHeader, additionalProperties=$additionalProperties}" + } + + class AzureBlob + private constructor( + private val id: JsonField, + private val accountName: JsonField, + private val container: JsonField, + private val includeCanonicalHeader: JsonField, + private val name: JsonField, + private val prefix: JsonField, + private val type: JsonValue, + private val baseUrlForCanonicalHeader: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), + @JsonProperty("accountName") + @ExcludeMissing + accountName: JsonField = JsonMissing.of(), + @JsonProperty("container") + @ExcludeMissing + container: JsonField = JsonMissing.of(), + @JsonProperty("includeCanonicalHeader") + @ExcludeMissing + includeCanonicalHeader: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("prefix") @ExcludeMissing prefix: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(), + @JsonProperty("baseUrlForCanonicalHeader") + @ExcludeMissing + baseUrlForCanonicalHeader: JsonField = JsonMissing.of(), + ) : this( + id, + accountName, + container, + includeCanonicalHeader, + name, + prefix, + type, + baseUrlForCanonicalHeader, + mutableMapOf(), + ) + + /** + * Unique identifier for the origin. This is generated by ImageKit when you create a new + * origin. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun id(): String = id.getRequired("id") + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun accountName(): String = accountName.getRequired("accountName") + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun container(): String = container.getRequired("container") + + /** + * Whether to send a Canonical header. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun includeCanonicalHeader(): Boolean = + includeCanonicalHeader.getRequired("includeCanonicalHeader") + + /** + * Display name of the origin. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun name(): String = name.getRequired("name") + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun prefix(): String = prefix.getRequired("prefix") + + /** + * Expected to always return the following: + * ```java + * JsonValue.from("AZURE_BLOB") + * ``` + * + * However, this method can be useful for debugging and logging (e.g. if the server + * responded with an unexpected value). + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type + + /** + * URL used in the Canonical header (if enabled). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun baseUrlForCanonicalHeader(): Optional = + baseUrlForCanonicalHeader.getOptional("baseUrlForCanonicalHeader") + + /** + * Returns the raw JSON value of [id]. + * + * Unlike [id], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id + + /** + * Returns the raw JSON value of [accountName]. + * + * Unlike [accountName], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("accountName") + @ExcludeMissing + fun _accountName(): JsonField = accountName + + /** + * Returns the raw JSON value of [container]. + * + * Unlike [container], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("container") @ExcludeMissing fun _container(): JsonField = container + + /** + * Returns the raw JSON value of [includeCanonicalHeader]. + * + * Unlike [includeCanonicalHeader], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("includeCanonicalHeader") + @ExcludeMissing + fun _includeCanonicalHeader(): JsonField = includeCanonicalHeader + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + + /** + * Returns the raw JSON value of [prefix]. + * + * Unlike [prefix], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("prefix") @ExcludeMissing fun _prefix(): JsonField = prefix + + /** + * Returns the raw JSON value of [baseUrlForCanonicalHeader]. + * + * Unlike [baseUrlForCanonicalHeader], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("baseUrlForCanonicalHeader") + @ExcludeMissing + fun _baseUrlForCanonicalHeader(): JsonField = baseUrlForCanonicalHeader + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [AzureBlob]. + * + * The following fields are required: + * ```java + * .id() + * .accountName() + * .container() + * .includeCanonicalHeader() + * .name() + * .prefix() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [AzureBlob]. */ + class Builder internal constructor() { + + private var id: JsonField? = null + private var accountName: JsonField? = null + private var container: JsonField? = null + private var includeCanonicalHeader: JsonField? = null + private var name: JsonField? = null + private var prefix: JsonField? = null + private var type: JsonValue = JsonValue.from("AZURE_BLOB") + private var baseUrlForCanonicalHeader: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(azureBlob: AzureBlob) = apply { + id = azureBlob.id + accountName = azureBlob.accountName + container = azureBlob.container + includeCanonicalHeader = azureBlob.includeCanonicalHeader + name = azureBlob.name + prefix = azureBlob.prefix + type = azureBlob.type + baseUrlForCanonicalHeader = azureBlob.baseUrlForCanonicalHeader + additionalProperties = azureBlob.additionalProperties.toMutableMap() + } + + /** + * Unique identifier for the origin. This is generated by ImageKit when you create a new + * origin. + */ + fun id(id: String) = id(JsonField.of(id)) + + /** + * Sets [Builder.id] to an arbitrary JSON value. + * + * You should usually call [Builder.id] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun id(id: JsonField) = apply { this.id = id } + + fun accountName(accountName: String) = accountName(JsonField.of(accountName)) + + /** + * Sets [Builder.accountName] to an arbitrary JSON value. + * + * You should usually call [Builder.accountName] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun accountName(accountName: JsonField) = apply { + this.accountName = accountName + } + + fun container(container: String) = container(JsonField.of(container)) + + /** + * Sets [Builder.container] to an arbitrary JSON value. + * + * You should usually call [Builder.container] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun container(container: JsonField) = apply { this.container = container } + + /** Whether to send a Canonical header. */ + fun includeCanonicalHeader(includeCanonicalHeader: Boolean) = + includeCanonicalHeader(JsonField.of(includeCanonicalHeader)) + + /** + * Sets [Builder.includeCanonicalHeader] to an arbitrary JSON value. + * + * You should usually call [Builder.includeCanonicalHeader] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun includeCanonicalHeader(includeCanonicalHeader: JsonField) = apply { + this.includeCanonicalHeader = includeCanonicalHeader + } + + /** Display name of the origin. */ + fun name(name: String) = name(JsonField.of(name)) + + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun name(name: JsonField) = apply { this.name = name } + + fun prefix(prefix: String) = prefix(JsonField.of(prefix)) + + /** + * Sets [Builder.prefix] to an arbitrary JSON value. + * + * You should usually call [Builder.prefix] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun prefix(prefix: JsonField) = apply { this.prefix = prefix } + + /** + * Sets the field to an arbitrary JSON value. + * + * It is usually unnecessary to call this method because the field defaults to the + * following: + * ```java + * JsonValue.from("AZURE_BLOB") + * ``` + * + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun type(type: JsonValue) = apply { this.type = type } + + /** URL used in the Canonical header (if enabled). */ + fun baseUrlForCanonicalHeader(baseUrlForCanonicalHeader: String) = + baseUrlForCanonicalHeader(JsonField.of(baseUrlForCanonicalHeader)) + + /** + * Sets [Builder.baseUrlForCanonicalHeader] to an arbitrary JSON value. + * + * You should usually call [Builder.baseUrlForCanonicalHeader] with a well-typed + * [String] value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun baseUrlForCanonicalHeader(baseUrlForCanonicalHeader: JsonField) = apply { + this.baseUrlForCanonicalHeader = baseUrlForCanonicalHeader + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [AzureBlob]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .id() + * .accountName() + * .container() + * .includeCanonicalHeader() + * .name() + * .prefix() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): AzureBlob = + AzureBlob( + checkRequired("id", id), + checkRequired("accountName", accountName), + checkRequired("container", container), + checkRequired("includeCanonicalHeader", includeCanonicalHeader), + checkRequired("name", name), + checkRequired("prefix", prefix), + type, + baseUrlForCanonicalHeader, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): AzureBlob = apply { + if (validated) { + return@apply + } + + id() + accountName() + container() + includeCanonicalHeader() + name() + prefix() + _type().let { + if (it != JsonValue.from("AZURE_BLOB")) { + throw ImageKitInvalidDataException("'type' is invalid, received $it") + } + } + baseUrlForCanonicalHeader() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (id.asKnown().isPresent) 1 else 0) + + (if (accountName.asKnown().isPresent) 1 else 0) + + (if (container.asKnown().isPresent) 1 else 0) + + (if (includeCanonicalHeader.asKnown().isPresent) 1 else 0) + + (if (name.asKnown().isPresent) 1 else 0) + + (if (prefix.asKnown().isPresent) 1 else 0) + + type.let { if (it == JsonValue.from("AZURE_BLOB")) 1 else 0 } + + (if (baseUrlForCanonicalHeader.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is AzureBlob && + id == other.id && + accountName == other.accountName && + container == other.container && + includeCanonicalHeader == other.includeCanonicalHeader && + name == other.name && + prefix == other.prefix && + type == other.type && + baseUrlForCanonicalHeader == other.baseUrlForCanonicalHeader && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + id, + accountName, + container, + includeCanonicalHeader, + name, + prefix, + type, + baseUrlForCanonicalHeader, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "AzureBlob{id=$id, accountName=$accountName, container=$container, includeCanonicalHeader=$includeCanonicalHeader, name=$name, prefix=$prefix, type=$type, baseUrlForCanonicalHeader=$baseUrlForCanonicalHeader, additionalProperties=$additionalProperties}" + } + + class AkeneoPim + private constructor( + private val id: JsonField, + private val baseUrl: JsonField, + private val includeCanonicalHeader: JsonField, + private val name: JsonField, + private val type: JsonValue, + private val baseUrlForCanonicalHeader: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), + @JsonProperty("baseUrl") @ExcludeMissing baseUrl: JsonField = JsonMissing.of(), + @JsonProperty("includeCanonicalHeader") + @ExcludeMissing + includeCanonicalHeader: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(), + @JsonProperty("baseUrlForCanonicalHeader") + @ExcludeMissing + baseUrlForCanonicalHeader: JsonField = JsonMissing.of(), + ) : this( + id, + baseUrl, + includeCanonicalHeader, + name, + type, + baseUrlForCanonicalHeader, + mutableMapOf(), + ) + + /** + * Unique identifier for the origin. This is generated by ImageKit when you create a new + * origin. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun id(): String = id.getRequired("id") + + /** + * Akeneo instance base URL. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun baseUrl(): String = baseUrl.getRequired("baseUrl") + + /** + * Whether to send a Canonical header. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun includeCanonicalHeader(): Boolean = + includeCanonicalHeader.getRequired("includeCanonicalHeader") + + /** + * Display name of the origin. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun name(): String = name.getRequired("name") + + /** + * Expected to always return the following: + * ```java + * JsonValue.from("AKENEO_PIM") + * ``` + * + * However, this method can be useful for debugging and logging (e.g. if the server + * responded with an unexpected value). + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type + + /** + * URL used in the Canonical header (if enabled). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun baseUrlForCanonicalHeader(): Optional = + baseUrlForCanonicalHeader.getOptional("baseUrlForCanonicalHeader") + + /** + * Returns the raw JSON value of [id]. + * + * Unlike [id], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id + + /** + * Returns the raw JSON value of [baseUrl]. + * + * Unlike [baseUrl], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("baseUrl") @ExcludeMissing fun _baseUrl(): JsonField = baseUrl + + /** + * Returns the raw JSON value of [includeCanonicalHeader]. + * + * Unlike [includeCanonicalHeader], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("includeCanonicalHeader") + @ExcludeMissing + fun _includeCanonicalHeader(): JsonField = includeCanonicalHeader + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + + /** + * Returns the raw JSON value of [baseUrlForCanonicalHeader]. + * + * Unlike [baseUrlForCanonicalHeader], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("baseUrlForCanonicalHeader") + @ExcludeMissing + fun _baseUrlForCanonicalHeader(): JsonField = baseUrlForCanonicalHeader + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [AkeneoPim]. + * + * The following fields are required: + * ```java + * .id() + * .baseUrl() + * .includeCanonicalHeader() + * .name() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [AkeneoPim]. */ + class Builder internal constructor() { + + private var id: JsonField? = null + private var baseUrl: JsonField? = null + private var includeCanonicalHeader: JsonField? = null + private var name: JsonField? = null + private var type: JsonValue = JsonValue.from("AKENEO_PIM") + private var baseUrlForCanonicalHeader: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(akeneoPim: AkeneoPim) = apply { + id = akeneoPim.id + baseUrl = akeneoPim.baseUrl + includeCanonicalHeader = akeneoPim.includeCanonicalHeader + name = akeneoPim.name + type = akeneoPim.type + baseUrlForCanonicalHeader = akeneoPim.baseUrlForCanonicalHeader + additionalProperties = akeneoPim.additionalProperties.toMutableMap() + } + + /** + * Unique identifier for the origin. This is generated by ImageKit when you create a new + * origin. + */ + fun id(id: String) = id(JsonField.of(id)) + + /** + * Sets [Builder.id] to an arbitrary JSON value. + * + * You should usually call [Builder.id] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun id(id: JsonField) = apply { this.id = id } + + /** Akeneo instance base URL. */ + fun baseUrl(baseUrl: String) = baseUrl(JsonField.of(baseUrl)) + + /** + * Sets [Builder.baseUrl] to an arbitrary JSON value. + * + * You should usually call [Builder.baseUrl] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun baseUrl(baseUrl: JsonField) = apply { this.baseUrl = baseUrl } + + /** Whether to send a Canonical header. */ + fun includeCanonicalHeader(includeCanonicalHeader: Boolean) = + includeCanonicalHeader(JsonField.of(includeCanonicalHeader)) + + /** + * Sets [Builder.includeCanonicalHeader] to an arbitrary JSON value. + * + * You should usually call [Builder.includeCanonicalHeader] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun includeCanonicalHeader(includeCanonicalHeader: JsonField) = apply { + this.includeCanonicalHeader = includeCanonicalHeader + } + + /** Display name of the origin. */ + fun name(name: String) = name(JsonField.of(name)) + + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun name(name: JsonField) = apply { this.name = name } + + /** + * Sets the field to an arbitrary JSON value. + * + * It is usually unnecessary to call this method because the field defaults to the + * following: + * ```java + * JsonValue.from("AKENEO_PIM") + * ``` + * + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun type(type: JsonValue) = apply { this.type = type } + + /** URL used in the Canonical header (if enabled). */ + fun baseUrlForCanonicalHeader(baseUrlForCanonicalHeader: String) = + baseUrlForCanonicalHeader(JsonField.of(baseUrlForCanonicalHeader)) + + /** + * Sets [Builder.baseUrlForCanonicalHeader] to an arbitrary JSON value. + * + * You should usually call [Builder.baseUrlForCanonicalHeader] with a well-typed + * [String] value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun baseUrlForCanonicalHeader(baseUrlForCanonicalHeader: JsonField) = apply { + this.baseUrlForCanonicalHeader = baseUrlForCanonicalHeader + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [AkeneoPim]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .id() + * .baseUrl() + * .includeCanonicalHeader() + * .name() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): AkeneoPim = + AkeneoPim( + checkRequired("id", id), + checkRequired("baseUrl", baseUrl), + checkRequired("includeCanonicalHeader", includeCanonicalHeader), + checkRequired("name", name), + type, + baseUrlForCanonicalHeader, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): AkeneoPim = apply { + if (validated) { + return@apply + } + + id() + baseUrl() + includeCanonicalHeader() + name() + _type().let { + if (it != JsonValue.from("AKENEO_PIM")) { + throw ImageKitInvalidDataException("'type' is invalid, received $it") + } + } + baseUrlForCanonicalHeader() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (id.asKnown().isPresent) 1 else 0) + + (if (baseUrl.asKnown().isPresent) 1 else 0) + + (if (includeCanonicalHeader.asKnown().isPresent) 1 else 0) + + (if (name.asKnown().isPresent) 1 else 0) + + type.let { if (it == JsonValue.from("AKENEO_PIM")) 1 else 0 } + + (if (baseUrlForCanonicalHeader.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is AkeneoPim && + id == other.id && + baseUrl == other.baseUrl && + includeCanonicalHeader == other.includeCanonicalHeader && + name == other.name && + type == other.type && + baseUrlForCanonicalHeader == other.baseUrlForCanonicalHeader && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + id, + baseUrl, + includeCanonicalHeader, + name, + type, + baseUrlForCanonicalHeader, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "AkeneoPim{id=$id, baseUrl=$baseUrl, includeCanonicalHeader=$includeCanonicalHeader, name=$name, type=$type, baseUrlForCanonicalHeader=$baseUrlForCanonicalHeader, additionalProperties=$additionalProperties}" + } +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/accounts/origins/OriginUpdateParams.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/accounts/origins/OriginUpdateParams.kt new file mode 100644 index 0000000..fb70ae4 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/accounts/origins/OriginUpdateParams.kt @@ -0,0 +1,276 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.accounts.origins + +import com.imagekit.api.core.Params +import com.imagekit.api.core.checkRequired +import com.imagekit.api.core.http.Headers +import com.imagekit.api.core.http.QueryParams +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** + * **Note:** This API is currently in beta. Updates the origin identified by `id` and returns the + * updated origin object. + */ +class OriginUpdateParams +private constructor( + private val id: String?, + private val originRequest: OriginRequest, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** + * Unique identifier for the origin. This is generated by ImageKit when you create a new origin. + */ + fun id(): Optional = Optional.ofNullable(id) + + /** Schema for origin request resources. */ + fun originRequest(): OriginRequest = originRequest + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [OriginUpdateParams]. + * + * The following fields are required: + * ```java + * .originRequest() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [OriginUpdateParams]. */ + class Builder internal constructor() { + + private var id: String? = null + private var originRequest: OriginRequest? = null + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + + @JvmSynthetic + internal fun from(originUpdateParams: OriginUpdateParams) = apply { + id = originUpdateParams.id + originRequest = originUpdateParams.originRequest + additionalHeaders = originUpdateParams.additionalHeaders.toBuilder() + additionalQueryParams = originUpdateParams.additionalQueryParams.toBuilder() + } + + /** + * Unique identifier for the origin. This is generated by ImageKit when you create a new + * origin. + */ + fun id(id: String?) = apply { this.id = id } + + /** Alias for calling [Builder.id] with `id.orElse(null)`. */ + fun id(id: Optional) = id(id.getOrNull()) + + /** Schema for origin request resources. */ + fun originRequest(originRequest: OriginRequest) = apply { + this.originRequest = originRequest + } + + /** Alias for calling [originRequest] with `OriginRequest.ofS3(s3)`. */ + fun originRequest(s3: OriginRequest.S3) = originRequest(OriginRequest.ofS3(s3)) + + /** Alias for calling [originRequest] with `OriginRequest.ofS3Compatible(s3Compatible)`. */ + fun originRequest(s3Compatible: OriginRequest.S3Compatible) = + originRequest(OriginRequest.ofS3Compatible(s3Compatible)) + + /** + * Alias for calling [originRequest] with + * `OriginRequest.ofCloudinaryBackup(cloudinaryBackup)`. + */ + fun originRequest(cloudinaryBackup: OriginRequest.CloudinaryBackup) = + originRequest(OriginRequest.ofCloudinaryBackup(cloudinaryBackup)) + + /** Alias for calling [originRequest] with `OriginRequest.ofWebFolder(webFolder)`. */ + fun originRequest(webFolder: OriginRequest.WebFolder) = + originRequest(OriginRequest.ofWebFolder(webFolder)) + + /** Alias for calling [originRequest] with `OriginRequest.ofWebProxy(webProxy)`. */ + fun originRequest(webProxy: OriginRequest.WebProxy) = + originRequest(OriginRequest.ofWebProxy(webProxy)) + + /** + * Alias for calling [originRequest] with the following: + * ```java + * OriginRequest.WebProxy.builder() + * .name(name) + * .build() + * ``` + */ + fun webProxyOriginRequest(name: String) = + originRequest(OriginRequest.WebProxy.builder().name(name).build()) + + /** Alias for calling [originRequest] with `OriginRequest.ofGcs(gcs)`. */ + fun originRequest(gcs: OriginRequest.Gcs) = originRequest(OriginRequest.ofGcs(gcs)) + + /** Alias for calling [originRequest] with `OriginRequest.ofAzureBlob(azureBlob)`. */ + fun originRequest(azureBlob: OriginRequest.AzureBlob) = + originRequest(OriginRequest.ofAzureBlob(azureBlob)) + + /** Alias for calling [originRequest] with `OriginRequest.ofAkeneoPim(akeneoPim)`. */ + fun originRequest(akeneoPim: OriginRequest.AkeneoPim) = + originRequest(OriginRequest.ofAkeneoPim(akeneoPim)) + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + /** + * Returns an immutable instance of [OriginUpdateParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .originRequest() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): OriginUpdateParams = + OriginUpdateParams( + id, + checkRequired("originRequest", originRequest), + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } + + fun _body(): OriginRequest = originRequest + + fun _pathParam(index: Int): String = + when (index) { + 0 -> id ?: "" + else -> "" + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is OriginUpdateParams && + id == other.id && + originRequest == other.originRequest && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = + Objects.hash(id, originRequest, additionalHeaders, additionalQueryParams) + + override fun toString() = + "OriginUpdateParams{id=$id, originRequest=$originRequest, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/accounts/urlendpoints/UrlEndpointCreateParams.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/accounts/urlendpoints/UrlEndpointCreateParams.kt new file mode 100644 index 0000000..82e57e9 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/accounts/urlendpoints/UrlEndpointCreateParams.kt @@ -0,0 +1,209 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.accounts.urlendpoints + +import com.imagekit.api.core.JsonValue +import com.imagekit.api.core.Params +import com.imagekit.api.core.checkRequired +import com.imagekit.api.core.http.Headers +import com.imagekit.api.core.http.QueryParams +import java.util.Objects + +/** + * **Note:** This API is currently in beta. Creates a new URL‑endpoint and returns the resulting + * object. + */ +class UrlEndpointCreateParams +private constructor( + private val urlEndpointRequest: UrlEndpointRequest, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** Schema for URL endpoint resource. */ + fun urlEndpointRequest(): UrlEndpointRequest = urlEndpointRequest + + fun _additionalBodyProperties(): Map = + urlEndpointRequest._additionalProperties() + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [UrlEndpointCreateParams]. + * + * The following fields are required: + * ```java + * .urlEndpointRequest() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [UrlEndpointCreateParams]. */ + class Builder internal constructor() { + + private var urlEndpointRequest: UrlEndpointRequest? = null + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + + @JvmSynthetic + internal fun from(urlEndpointCreateParams: UrlEndpointCreateParams) = apply { + urlEndpointRequest = urlEndpointCreateParams.urlEndpointRequest + additionalHeaders = urlEndpointCreateParams.additionalHeaders.toBuilder() + additionalQueryParams = urlEndpointCreateParams.additionalQueryParams.toBuilder() + } + + /** Schema for URL endpoint resource. */ + fun urlEndpointRequest(urlEndpointRequest: UrlEndpointRequest) = apply { + this.urlEndpointRequest = urlEndpointRequest + } + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + /** + * Returns an immutable instance of [UrlEndpointCreateParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .urlEndpointRequest() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): UrlEndpointCreateParams = + UrlEndpointCreateParams( + checkRequired("urlEndpointRequest", urlEndpointRequest), + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } + + fun _body(): UrlEndpointRequest = urlEndpointRequest + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is UrlEndpointCreateParams && + urlEndpointRequest == other.urlEndpointRequest && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = + Objects.hash(urlEndpointRequest, additionalHeaders, additionalQueryParams) + + override fun toString() = + "UrlEndpointCreateParams{urlEndpointRequest=$urlEndpointRequest, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/accounts/urlendpoints/UrlEndpointDeleteParams.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/accounts/urlendpoints/UrlEndpointDeleteParams.kt new file mode 100644 index 0000000..754f929 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/accounts/urlendpoints/UrlEndpointDeleteParams.kt @@ -0,0 +1,241 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.accounts.urlendpoints + +import com.imagekit.api.core.JsonValue +import com.imagekit.api.core.Params +import com.imagekit.api.core.http.Headers +import com.imagekit.api.core.http.QueryParams +import com.imagekit.api.core.toImmutable +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** + * **Note:** This API is currently in beta. Deletes the URL‑endpoint identified by `id`. You cannot + * delete the default URL‑endpoint created by ImageKit during account creation. + */ +class UrlEndpointDeleteParams +private constructor( + private val id: String?, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, + private val additionalBodyProperties: Map, +) : Params { + + /** + * Unique identifier for the URL-endpoint. This is generated by ImageKit when you create a new + * URL-endpoint. For the default URL-endpoint, this is always `default`. + */ + fun id(): Optional = Optional.ofNullable(id) + + /** Additional body properties to send with the request. */ + fun _additionalBodyProperties(): Map = additionalBodyProperties + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun none(): UrlEndpointDeleteParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [UrlEndpointDeleteParams]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [UrlEndpointDeleteParams]. */ + class Builder internal constructor() { + + private var id: String? = null + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + private var additionalBodyProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(urlEndpointDeleteParams: UrlEndpointDeleteParams) = apply { + id = urlEndpointDeleteParams.id + additionalHeaders = urlEndpointDeleteParams.additionalHeaders.toBuilder() + additionalQueryParams = urlEndpointDeleteParams.additionalQueryParams.toBuilder() + additionalBodyProperties = + urlEndpointDeleteParams.additionalBodyProperties.toMutableMap() + } + + /** + * Unique identifier for the URL-endpoint. This is generated by ImageKit when you create a + * new URL-endpoint. For the default URL-endpoint, this is always `default`. + */ + fun id(id: String?) = apply { this.id = id } + + /** Alias for calling [Builder.id] with `id.orElse(null)`. */ + fun id(id: Optional) = id(id.getOrNull()) + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + this.additionalBodyProperties.clear() + putAllAdditionalBodyProperties(additionalBodyProperties) + } + + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + additionalBodyProperties.put(key, value) + } + + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + this.additionalBodyProperties.putAll(additionalBodyProperties) + } + + fun removeAdditionalBodyProperty(key: String) = apply { + additionalBodyProperties.remove(key) + } + + fun removeAllAdditionalBodyProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalBodyProperty) + } + + /** + * Returns an immutable instance of [UrlEndpointDeleteParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): UrlEndpointDeleteParams = + UrlEndpointDeleteParams( + id, + additionalHeaders.build(), + additionalQueryParams.build(), + additionalBodyProperties.toImmutable(), + ) + } + + fun _body(): Optional> = + Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) + + fun _pathParam(index: Int): String = + when (index) { + 0 -> id ?: "" + else -> "" + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is UrlEndpointDeleteParams && + id == other.id && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams && + additionalBodyProperties == other.additionalBodyProperties + } + + override fun hashCode(): Int = + Objects.hash(id, additionalHeaders, additionalQueryParams, additionalBodyProperties) + + override fun toString() = + "UrlEndpointDeleteParams{id=$id, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams, additionalBodyProperties=$additionalBodyProperties}" +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/accounts/urlendpoints/UrlEndpointGetParams.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/accounts/urlendpoints/UrlEndpointGetParams.kt new file mode 100644 index 0000000..a07244e --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/accounts/urlendpoints/UrlEndpointGetParams.kt @@ -0,0 +1,197 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.accounts.urlendpoints + +import com.imagekit.api.core.Params +import com.imagekit.api.core.http.Headers +import com.imagekit.api.core.http.QueryParams +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** **Note:** This API is currently in beta. Retrieves the URL‑endpoint identified by `id`. */ +class UrlEndpointGetParams +private constructor( + private val id: String?, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** + * Unique identifier for the URL-endpoint. This is generated by ImageKit when you create a new + * URL-endpoint. For the default URL-endpoint, this is always `default`. + */ + fun id(): Optional = Optional.ofNullable(id) + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun none(): UrlEndpointGetParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [UrlEndpointGetParams]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [UrlEndpointGetParams]. */ + class Builder internal constructor() { + + private var id: String? = null + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + + @JvmSynthetic + internal fun from(urlEndpointGetParams: UrlEndpointGetParams) = apply { + id = urlEndpointGetParams.id + additionalHeaders = urlEndpointGetParams.additionalHeaders.toBuilder() + additionalQueryParams = urlEndpointGetParams.additionalQueryParams.toBuilder() + } + + /** + * Unique identifier for the URL-endpoint. This is generated by ImageKit when you create a + * new URL-endpoint. For the default URL-endpoint, this is always `default`. + */ + fun id(id: String?) = apply { this.id = id } + + /** Alias for calling [Builder.id] with `id.orElse(null)`. */ + fun id(id: Optional) = id(id.getOrNull()) + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + /** + * Returns an immutable instance of [UrlEndpointGetParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): UrlEndpointGetParams = + UrlEndpointGetParams(id, additionalHeaders.build(), additionalQueryParams.build()) + } + + fun _pathParam(index: Int): String = + when (index) { + 0 -> id ?: "" + else -> "" + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is UrlEndpointGetParams && + id == other.id && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = Objects.hash(id, additionalHeaders, additionalQueryParams) + + override fun toString() = + "UrlEndpointGetParams{id=$id, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/accounts/urlendpoints/UrlEndpointListParams.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/accounts/urlendpoints/UrlEndpointListParams.kt new file mode 100644 index 0000000..a37cdae --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/accounts/urlendpoints/UrlEndpointListParams.kt @@ -0,0 +1,173 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.accounts.urlendpoints + +import com.imagekit.api.core.Params +import com.imagekit.api.core.http.Headers +import com.imagekit.api.core.http.QueryParams +import java.util.Objects + +/** + * **Note:** This API is currently in beta. Returns an array of all URL‑endpoints configured + * including the default URL-endpoint generated by ImageKit during account creation. + */ +class UrlEndpointListParams +private constructor( + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun none(): UrlEndpointListParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [UrlEndpointListParams]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [UrlEndpointListParams]. */ + class Builder internal constructor() { + + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + + @JvmSynthetic + internal fun from(urlEndpointListParams: UrlEndpointListParams) = apply { + additionalHeaders = urlEndpointListParams.additionalHeaders.toBuilder() + additionalQueryParams = urlEndpointListParams.additionalQueryParams.toBuilder() + } + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + /** + * Returns an immutable instance of [UrlEndpointListParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): UrlEndpointListParams = + UrlEndpointListParams(additionalHeaders.build(), additionalQueryParams.build()) + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is UrlEndpointListParams && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = Objects.hash(additionalHeaders, additionalQueryParams) + + override fun toString() = + "UrlEndpointListParams{additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/accounts/urlendpoints/UrlEndpointRequest.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/accounts/urlendpoints/UrlEndpointRequest.kt new file mode 100644 index 0000000..40f3d60 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/accounts/urlendpoints/UrlEndpointRequest.kt @@ -0,0 +1,751 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.accounts.urlendpoints + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.fasterxml.jackson.core.JsonGenerator +import com.fasterxml.jackson.core.ObjectCodec +import com.fasterxml.jackson.databind.JsonNode +import com.fasterxml.jackson.databind.SerializerProvider +import com.fasterxml.jackson.databind.annotation.JsonDeserialize +import com.fasterxml.jackson.databind.annotation.JsonSerialize +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.imagekit.api.core.BaseDeserializer +import com.imagekit.api.core.BaseSerializer +import com.imagekit.api.core.ExcludeMissing +import com.imagekit.api.core.JsonField +import com.imagekit.api.core.JsonMissing +import com.imagekit.api.core.JsonValue +import com.imagekit.api.core.checkKnown +import com.imagekit.api.core.checkRequired +import com.imagekit.api.core.getOrThrow +import com.imagekit.api.core.toImmutable +import com.imagekit.api.errors.ImageKitInvalidDataException +import java.util.Collections +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** Schema for URL endpoint resource. */ +class UrlEndpointRequest +private constructor( + private val description: JsonField, + private val origins: JsonField>, + private val urlPrefix: JsonField, + private val urlRewriter: JsonField, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("description") + @ExcludeMissing + description: JsonField = JsonMissing.of(), + @JsonProperty("origins") + @ExcludeMissing + origins: JsonField> = JsonMissing.of(), + @JsonProperty("urlPrefix") @ExcludeMissing urlPrefix: JsonField = JsonMissing.of(), + @JsonProperty("urlRewriter") + @ExcludeMissing + urlRewriter: JsonField = JsonMissing.of(), + ) : this(description, origins, urlPrefix, urlRewriter, mutableMapOf()) + + /** + * Description of the URL endpoint. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun description(): String = description.getRequired("description") + + /** + * Ordered list of origin IDs to try when the file isn’t in the Media Library; ImageKit checks + * them in the sequence provided. Origin must be created before it can be used in a URL + * endpoint. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun origins(): Optional> = origins.getOptional("origins") + + /** + * Path segment appended to your base URL to form the endpoint (letters, digits, and hyphens + * only — or empty for the default endpoint). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun urlPrefix(): Optional = urlPrefix.getOptional("urlPrefix") + + /** + * Configuration for third-party URL rewriting. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun urlRewriter(): Optional = urlRewriter.getOptional("urlRewriter") + + /** + * Returns the raw JSON value of [description]. + * + * Unlike [description], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("description") @ExcludeMissing fun _description(): JsonField = description + + /** + * Returns the raw JSON value of [origins]. + * + * Unlike [origins], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("origins") @ExcludeMissing fun _origins(): JsonField> = origins + + /** + * Returns the raw JSON value of [urlPrefix]. + * + * Unlike [urlPrefix], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("urlPrefix") @ExcludeMissing fun _urlPrefix(): JsonField = urlPrefix + + /** + * Returns the raw JSON value of [urlRewriter]. + * + * Unlike [urlRewriter], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("urlRewriter") + @ExcludeMissing + fun _urlRewriter(): JsonField = urlRewriter + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [UrlEndpointRequest]. + * + * The following fields are required: + * ```java + * .description() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [UrlEndpointRequest]. */ + class Builder internal constructor() { + + private var description: JsonField? = null + private var origins: JsonField>? = null + private var urlPrefix: JsonField = JsonMissing.of() + private var urlRewriter: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(urlEndpointRequest: UrlEndpointRequest) = apply { + description = urlEndpointRequest.description + origins = urlEndpointRequest.origins.map { it.toMutableList() } + urlPrefix = urlEndpointRequest.urlPrefix + urlRewriter = urlEndpointRequest.urlRewriter + additionalProperties = urlEndpointRequest.additionalProperties.toMutableMap() + } + + /** Description of the URL endpoint. */ + fun description(description: String) = description(JsonField.of(description)) + + /** + * Sets [Builder.description] to an arbitrary JSON value. + * + * You should usually call [Builder.description] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun description(description: JsonField) = apply { this.description = description } + + /** + * Ordered list of origin IDs to try when the file isn’t in the Media Library; ImageKit + * checks them in the sequence provided. Origin must be created before it can be used in a + * URL endpoint. + */ + fun origins(origins: List) = origins(JsonField.of(origins)) + + /** + * Sets [Builder.origins] to an arbitrary JSON value. + * + * You should usually call [Builder.origins] with a well-typed `List` value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun origins(origins: JsonField>) = apply { + this.origins = origins.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [origins]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addOrigin(origin: String) = apply { + origins = + (origins ?: JsonField.of(mutableListOf())).also { + checkKnown("origins", it).add(origin) + } + } + + /** + * Path segment appended to your base URL to form the endpoint (letters, digits, and hyphens + * only — or empty for the default endpoint). + */ + fun urlPrefix(urlPrefix: String) = urlPrefix(JsonField.of(urlPrefix)) + + /** + * Sets [Builder.urlPrefix] to an arbitrary JSON value. + * + * You should usually call [Builder.urlPrefix] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun urlPrefix(urlPrefix: JsonField) = apply { this.urlPrefix = urlPrefix } + + /** Configuration for third-party URL rewriting. */ + fun urlRewriter(urlRewriter: UrlRewriter) = urlRewriter(JsonField.of(urlRewriter)) + + /** + * Sets [Builder.urlRewriter] to an arbitrary JSON value. + * + * You should usually call [Builder.urlRewriter] with a well-typed [UrlRewriter] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun urlRewriter(urlRewriter: JsonField) = apply { + this.urlRewriter = urlRewriter + } + + /** Alias for calling [urlRewriter] with `UrlRewriter.ofCloudinary(cloudinary)`. */ + fun urlRewriter(cloudinary: UrlRewriter.Cloudinary) = + urlRewriter(UrlRewriter.ofCloudinary(cloudinary)) + + /** Alias for calling [urlRewriter] with `UrlRewriter.ofImgix()`. */ + fun urlRewriterImgix() = urlRewriter(UrlRewriter.ofImgix()) + + /** Alias for calling [urlRewriter] with `UrlRewriter.ofAkamai()`. */ + fun urlRewriterAkamai() = urlRewriter(UrlRewriter.ofAkamai()) + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [UrlEndpointRequest]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .description() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): UrlEndpointRequest = + UrlEndpointRequest( + checkRequired("description", description), + (origins ?: JsonMissing.of()).map { it.toImmutable() }, + urlPrefix, + urlRewriter, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): UrlEndpointRequest = apply { + if (validated) { + return@apply + } + + description() + origins() + urlPrefix() + urlRewriter().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (description.asKnown().isPresent) 1 else 0) + + (origins.asKnown().getOrNull()?.size ?: 0) + + (if (urlPrefix.asKnown().isPresent) 1 else 0) + + (urlRewriter.asKnown().getOrNull()?.validity() ?: 0) + + /** Configuration for third-party URL rewriting. */ + @JsonDeserialize(using = UrlRewriter.Deserializer::class) + @JsonSerialize(using = UrlRewriter.Serializer::class) + class UrlRewriter + private constructor( + private val cloudinary: Cloudinary? = null, + private val imgix: JsonValue? = null, + private val akamai: JsonValue? = null, + private val _json: JsonValue? = null, + ) { + + fun cloudinary(): Optional = Optional.ofNullable(cloudinary) + + fun imgix(): Optional = Optional.ofNullable(imgix) + + fun akamai(): Optional = Optional.ofNullable(akamai) + + fun isCloudinary(): Boolean = cloudinary != null + + fun isImgix(): Boolean = imgix != null + + fun isAkamai(): Boolean = akamai != null + + fun asCloudinary(): Cloudinary = cloudinary.getOrThrow("cloudinary") + + fun asImgix(): JsonValue = imgix.getOrThrow("imgix") + + fun asAkamai(): JsonValue = akamai.getOrThrow("akamai") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + cloudinary != null -> visitor.visitCloudinary(cloudinary) + imgix != null -> visitor.visitImgix(imgix) + akamai != null -> visitor.visitAkamai(akamai) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): UrlRewriter = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitCloudinary(cloudinary: Cloudinary) { + cloudinary.validate() + } + + override fun visitImgix(imgix: JsonValue) { + imgix.let { + if (it != JsonValue.from(mapOf("type" to "IMGIX"))) { + throw ImageKitInvalidDataException( + "'imgix' is invalid, received $it" + ) + } + } + } + + override fun visitAkamai(akamai: JsonValue) { + akamai.let { + if (it != JsonValue.from(mapOf("type" to "AKAMAI"))) { + throw ImageKitInvalidDataException( + "'akamai' is invalid, received $it" + ) + } + } + } + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitCloudinary(cloudinary: Cloudinary) = cloudinary.validity() + + override fun visitImgix(imgix: JsonValue) = + imgix.let { if (it == JsonValue.from(mapOf("type" to "IMGIX"))) 1 else 0 } + + override fun visitAkamai(akamai: JsonValue) = + akamai.let { if (it == JsonValue.from(mapOf("type" to "AKAMAI"))) 1 else 0 } + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is UrlRewriter && + cloudinary == other.cloudinary && + imgix == other.imgix && + akamai == other.akamai + } + + override fun hashCode(): Int = Objects.hash(cloudinary, imgix, akamai) + + override fun toString(): String = + when { + cloudinary != null -> "UrlRewriter{cloudinary=$cloudinary}" + imgix != null -> "UrlRewriter{imgix=$imgix}" + akamai != null -> "UrlRewriter{akamai=$akamai}" + _json != null -> "UrlRewriter{_unknown=$_json}" + else -> throw IllegalStateException("Invalid UrlRewriter") + } + + companion object { + + @JvmStatic + fun ofCloudinary(cloudinary: Cloudinary) = UrlRewriter(cloudinary = cloudinary) + + @JvmStatic fun ofImgix() = UrlRewriter(imgix = JsonValue.from(mapOf("type" to "IMGIX"))) + + @JvmStatic + fun ofAkamai() = UrlRewriter(akamai = JsonValue.from(mapOf("type" to "AKAMAI"))) + } + + /** + * An interface that defines how to map each variant of [UrlRewriter] to a value of type + * [T]. + */ + interface Visitor { + + fun visitCloudinary(cloudinary: Cloudinary): T + + fun visitImgix(imgix: JsonValue): T + + fun visitAkamai(akamai: JsonValue): T + + /** + * Maps an unknown variant of [UrlRewriter] to a value of type [T]. + * + * An instance of [UrlRewriter] can contain an unknown variant if it was deserialized + * from data that doesn't match any known variant. For example, if the SDK is on an + * older version than the API, then the API may respond with new variants that the SDK + * is unaware of. + * + * @throws ImageKitInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw ImageKitInvalidDataException("Unknown UrlRewriter: $json") + } + } + + internal class Deserializer : BaseDeserializer(UrlRewriter::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): UrlRewriter { + val json = JsonValue.fromJsonNode(node) + val type = json.asObject().getOrNull()?.get("type")?.asString()?.getOrNull() + + when (type) { + "CLOUDINARY" -> { + return tryDeserialize(node, jacksonTypeRef())?.let { + UrlRewriter(cloudinary = it, _json = json) + } ?: UrlRewriter(_json = json) + } + "IMGIX" -> { + return tryDeserialize(node, jacksonTypeRef()) + ?.let { UrlRewriter(imgix = it, _json = json) } + ?.takeIf { it.isValid() } ?: UrlRewriter(_json = json) + } + "AKAMAI" -> { + return tryDeserialize(node, jacksonTypeRef()) + ?.let { UrlRewriter(akamai = it, _json = json) } + ?.takeIf { it.isValid() } ?: UrlRewriter(_json = json) + } + } + + return UrlRewriter(_json = json) + } + } + + internal class Serializer : BaseSerializer(UrlRewriter::class) { + + override fun serialize( + value: UrlRewriter, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.cloudinary != null -> generator.writeObject(value.cloudinary) + value.imgix != null -> generator.writeObject(value.imgix) + value.akamai != null -> generator.writeObject(value.akamai) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid UrlRewriter") + } + } + } + + class Cloudinary + private constructor( + private val type: JsonValue, + private val preserveAssetDeliveryTypes: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(), + @JsonProperty("preserveAssetDeliveryTypes") + @ExcludeMissing + preserveAssetDeliveryTypes: JsonField = JsonMissing.of(), + ) : this(type, preserveAssetDeliveryTypes, mutableMapOf()) + + /** + * Expected to always return the following: + * ```java + * JsonValue.from("CLOUDINARY") + * ``` + * + * However, this method can be useful for debugging and logging (e.g. if the server + * responded with an unexpected value). + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type + + /** + * Whether to preserve `/` in the rewritten URL. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun preserveAssetDeliveryTypes(): Optional = + preserveAssetDeliveryTypes.getOptional("preserveAssetDeliveryTypes") + + /** + * Returns the raw JSON value of [preserveAssetDeliveryTypes]. + * + * Unlike [preserveAssetDeliveryTypes], this method doesn't throw if the JSON field has + * an unexpected type. + */ + @JsonProperty("preserveAssetDeliveryTypes") + @ExcludeMissing + fun _preserveAssetDeliveryTypes(): JsonField = preserveAssetDeliveryTypes + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Cloudinary]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Cloudinary]. */ + class Builder internal constructor() { + + private var type: JsonValue = JsonValue.from("CLOUDINARY") + private var preserveAssetDeliveryTypes: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(cloudinary: Cloudinary) = apply { + type = cloudinary.type + preserveAssetDeliveryTypes = cloudinary.preserveAssetDeliveryTypes + additionalProperties = cloudinary.additionalProperties.toMutableMap() + } + + /** + * Sets the field to an arbitrary JSON value. + * + * It is usually unnecessary to call this method because the field defaults to the + * following: + * ```java + * JsonValue.from("CLOUDINARY") + * ``` + * + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun type(type: JsonValue) = apply { this.type = type } + + /** Whether to preserve `/` in the rewritten URL. */ + fun preserveAssetDeliveryTypes(preserveAssetDeliveryTypes: Boolean) = + preserveAssetDeliveryTypes(JsonField.of(preserveAssetDeliveryTypes)) + + /** + * Sets [Builder.preserveAssetDeliveryTypes] to an arbitrary JSON value. + * + * You should usually call [Builder.preserveAssetDeliveryTypes] with a well-typed + * [Boolean] value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun preserveAssetDeliveryTypes(preserveAssetDeliveryTypes: JsonField) = + apply { + this.preserveAssetDeliveryTypes = preserveAssetDeliveryTypes + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Cloudinary]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Cloudinary = + Cloudinary( + type, + preserveAssetDeliveryTypes, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Cloudinary = apply { + if (validated) { + return@apply + } + + _type().let { + if (it != JsonValue.from("CLOUDINARY")) { + throw ImageKitInvalidDataException("'type' is invalid, received $it") + } + } + preserveAssetDeliveryTypes() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + type.let { if (it == JsonValue.from("CLOUDINARY")) 1 else 0 } + + (if (preserveAssetDeliveryTypes.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Cloudinary && + type == other.type && + preserveAssetDeliveryTypes == other.preserveAssetDeliveryTypes && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(type, preserveAssetDeliveryTypes, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Cloudinary{type=$type, preserveAssetDeliveryTypes=$preserveAssetDeliveryTypes, additionalProperties=$additionalProperties}" + } + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is UrlEndpointRequest && + description == other.description && + origins == other.origins && + urlPrefix == other.urlPrefix && + urlRewriter == other.urlRewriter && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(description, origins, urlPrefix, urlRewriter, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "UrlEndpointRequest{description=$description, origins=$origins, urlPrefix=$urlPrefix, urlRewriter=$urlRewriter, additionalProperties=$additionalProperties}" +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/accounts/urlendpoints/UrlEndpointResponse.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/accounts/urlendpoints/UrlEndpointResponse.kt new file mode 100644 index 0000000..e6bbbd7 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/accounts/urlendpoints/UrlEndpointResponse.kt @@ -0,0 +1,825 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.accounts.urlendpoints + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.fasterxml.jackson.core.JsonGenerator +import com.fasterxml.jackson.core.ObjectCodec +import com.fasterxml.jackson.databind.JsonNode +import com.fasterxml.jackson.databind.SerializerProvider +import com.fasterxml.jackson.databind.annotation.JsonDeserialize +import com.fasterxml.jackson.databind.annotation.JsonSerialize +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.imagekit.api.core.BaseDeserializer +import com.imagekit.api.core.BaseSerializer +import com.imagekit.api.core.ExcludeMissing +import com.imagekit.api.core.JsonField +import com.imagekit.api.core.JsonMissing +import com.imagekit.api.core.JsonValue +import com.imagekit.api.core.checkKnown +import com.imagekit.api.core.checkRequired +import com.imagekit.api.core.getOrThrow +import com.imagekit.api.core.toImmutable +import com.imagekit.api.errors.ImageKitInvalidDataException +import java.util.Collections +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** URL‑endpoint object as returned by the API. */ +class UrlEndpointResponse +private constructor( + private val id: JsonField, + private val description: JsonField, + private val origins: JsonField>, + private val urlPrefix: JsonField, + private val urlRewriter: JsonField, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), + @JsonProperty("description") + @ExcludeMissing + description: JsonField = JsonMissing.of(), + @JsonProperty("origins") + @ExcludeMissing + origins: JsonField> = JsonMissing.of(), + @JsonProperty("urlPrefix") @ExcludeMissing urlPrefix: JsonField = JsonMissing.of(), + @JsonProperty("urlRewriter") + @ExcludeMissing + urlRewriter: JsonField = JsonMissing.of(), + ) : this(id, description, origins, urlPrefix, urlRewriter, mutableMapOf()) + + /** + * Unique identifier for the URL-endpoint. This is generated by ImageKit when you create a new + * URL-endpoint. For the default URL-endpoint, this is always `default`. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun id(): String = id.getRequired("id") + + /** + * Description of the URL endpoint. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun description(): String = description.getRequired("description") + + /** + * Ordered list of origin IDs to try when the file isn’t in the Media Library; ImageKit checks + * them in the sequence provided. Origin must be created before it can be used in a URL + * endpoint. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun origins(): List = origins.getRequired("origins") + + /** + * Path segment appended to your base URL to form the endpoint (letters, digits, and hyphens + * only — or empty for the default endpoint). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun urlPrefix(): String = urlPrefix.getRequired("urlPrefix") + + /** + * Configuration for third-party URL rewriting. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun urlRewriter(): Optional = urlRewriter.getOptional("urlRewriter") + + /** + * Returns the raw JSON value of [id]. + * + * Unlike [id], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id + + /** + * Returns the raw JSON value of [description]. + * + * Unlike [description], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("description") @ExcludeMissing fun _description(): JsonField = description + + /** + * Returns the raw JSON value of [origins]. + * + * Unlike [origins], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("origins") @ExcludeMissing fun _origins(): JsonField> = origins + + /** + * Returns the raw JSON value of [urlPrefix]. + * + * Unlike [urlPrefix], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("urlPrefix") @ExcludeMissing fun _urlPrefix(): JsonField = urlPrefix + + /** + * Returns the raw JSON value of [urlRewriter]. + * + * Unlike [urlRewriter], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("urlRewriter") + @ExcludeMissing + fun _urlRewriter(): JsonField = urlRewriter + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [UrlEndpointResponse]. + * + * The following fields are required: + * ```java + * .id() + * .description() + * .origins() + * .urlPrefix() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [UrlEndpointResponse]. */ + class Builder internal constructor() { + + private var id: JsonField? = null + private var description: JsonField? = null + private var origins: JsonField>? = null + private var urlPrefix: JsonField? = null + private var urlRewriter: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(urlEndpointResponse: UrlEndpointResponse) = apply { + id = urlEndpointResponse.id + description = urlEndpointResponse.description + origins = urlEndpointResponse.origins.map { it.toMutableList() } + urlPrefix = urlEndpointResponse.urlPrefix + urlRewriter = urlEndpointResponse.urlRewriter + additionalProperties = urlEndpointResponse.additionalProperties.toMutableMap() + } + + /** + * Unique identifier for the URL-endpoint. This is generated by ImageKit when you create a + * new URL-endpoint. For the default URL-endpoint, this is always `default`. + */ + fun id(id: String) = id(JsonField.of(id)) + + /** + * Sets [Builder.id] to an arbitrary JSON value. + * + * You should usually call [Builder.id] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun id(id: JsonField) = apply { this.id = id } + + /** Description of the URL endpoint. */ + fun description(description: String) = description(JsonField.of(description)) + + /** + * Sets [Builder.description] to an arbitrary JSON value. + * + * You should usually call [Builder.description] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun description(description: JsonField) = apply { this.description = description } + + /** + * Ordered list of origin IDs to try when the file isn’t in the Media Library; ImageKit + * checks them in the sequence provided. Origin must be created before it can be used in a + * URL endpoint. + */ + fun origins(origins: List) = origins(JsonField.of(origins)) + + /** + * Sets [Builder.origins] to an arbitrary JSON value. + * + * You should usually call [Builder.origins] with a well-typed `List` value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun origins(origins: JsonField>) = apply { + this.origins = origins.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [origins]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addOrigin(origin: String) = apply { + origins = + (origins ?: JsonField.of(mutableListOf())).also { + checkKnown("origins", it).add(origin) + } + } + + /** + * Path segment appended to your base URL to form the endpoint (letters, digits, and hyphens + * only — or empty for the default endpoint). + */ + fun urlPrefix(urlPrefix: String) = urlPrefix(JsonField.of(urlPrefix)) + + /** + * Sets [Builder.urlPrefix] to an arbitrary JSON value. + * + * You should usually call [Builder.urlPrefix] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun urlPrefix(urlPrefix: JsonField) = apply { this.urlPrefix = urlPrefix } + + /** Configuration for third-party URL rewriting. */ + fun urlRewriter(urlRewriter: UrlRewriter) = urlRewriter(JsonField.of(urlRewriter)) + + /** + * Sets [Builder.urlRewriter] to an arbitrary JSON value. + * + * You should usually call [Builder.urlRewriter] with a well-typed [UrlRewriter] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun urlRewriter(urlRewriter: JsonField) = apply { + this.urlRewriter = urlRewriter + } + + /** Alias for calling [urlRewriter] with `UrlRewriter.ofCloudinary(cloudinary)`. */ + fun urlRewriter(cloudinary: UrlRewriter.Cloudinary) = + urlRewriter(UrlRewriter.ofCloudinary(cloudinary)) + + /** + * Alias for calling [urlRewriter] with the following: + * ```java + * UrlRewriter.Cloudinary.builder() + * .preserveAssetDeliveryTypes(preserveAssetDeliveryTypes) + * .build() + * ``` + */ + fun cloudinaryUrlRewriter(preserveAssetDeliveryTypes: Boolean) = + urlRewriter( + UrlRewriter.Cloudinary.builder() + .preserveAssetDeliveryTypes(preserveAssetDeliveryTypes) + .build() + ) + + /** Alias for calling [urlRewriter] with `UrlRewriter.ofImgix()`. */ + fun urlRewriterImgix() = urlRewriter(UrlRewriter.ofImgix()) + + /** Alias for calling [urlRewriter] with `UrlRewriter.ofAkamai()`. */ + fun urlRewriterAkamai() = urlRewriter(UrlRewriter.ofAkamai()) + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [UrlEndpointResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .id() + * .description() + * .origins() + * .urlPrefix() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): UrlEndpointResponse = + UrlEndpointResponse( + checkRequired("id", id), + checkRequired("description", description), + checkRequired("origins", origins).map { it.toImmutable() }, + checkRequired("urlPrefix", urlPrefix), + urlRewriter, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): UrlEndpointResponse = apply { + if (validated) { + return@apply + } + + id() + description() + origins() + urlPrefix() + urlRewriter().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (id.asKnown().isPresent) 1 else 0) + + (if (description.asKnown().isPresent) 1 else 0) + + (origins.asKnown().getOrNull()?.size ?: 0) + + (if (urlPrefix.asKnown().isPresent) 1 else 0) + + (urlRewriter.asKnown().getOrNull()?.validity() ?: 0) + + /** Configuration for third-party URL rewriting. */ + @JsonDeserialize(using = UrlRewriter.Deserializer::class) + @JsonSerialize(using = UrlRewriter.Serializer::class) + class UrlRewriter + private constructor( + private val cloudinary: Cloudinary? = null, + private val imgix: JsonValue? = null, + private val akamai: JsonValue? = null, + private val _json: JsonValue? = null, + ) { + + fun cloudinary(): Optional = Optional.ofNullable(cloudinary) + + fun imgix(): Optional = Optional.ofNullable(imgix) + + fun akamai(): Optional = Optional.ofNullable(akamai) + + fun isCloudinary(): Boolean = cloudinary != null + + fun isImgix(): Boolean = imgix != null + + fun isAkamai(): Boolean = akamai != null + + fun asCloudinary(): Cloudinary = cloudinary.getOrThrow("cloudinary") + + fun asImgix(): JsonValue = imgix.getOrThrow("imgix") + + fun asAkamai(): JsonValue = akamai.getOrThrow("akamai") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + cloudinary != null -> visitor.visitCloudinary(cloudinary) + imgix != null -> visitor.visitImgix(imgix) + akamai != null -> visitor.visitAkamai(akamai) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): UrlRewriter = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitCloudinary(cloudinary: Cloudinary) { + cloudinary.validate() + } + + override fun visitImgix(imgix: JsonValue) { + imgix.let { + if (it != JsonValue.from(mapOf("type" to "IMGIX"))) { + throw ImageKitInvalidDataException( + "'imgix' is invalid, received $it" + ) + } + } + } + + override fun visitAkamai(akamai: JsonValue) { + akamai.let { + if (it != JsonValue.from(mapOf("type" to "AKAMAI"))) { + throw ImageKitInvalidDataException( + "'akamai' is invalid, received $it" + ) + } + } + } + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitCloudinary(cloudinary: Cloudinary) = cloudinary.validity() + + override fun visitImgix(imgix: JsonValue) = + imgix.let { if (it == JsonValue.from(mapOf("type" to "IMGIX"))) 1 else 0 } + + override fun visitAkamai(akamai: JsonValue) = + akamai.let { if (it == JsonValue.from(mapOf("type" to "AKAMAI"))) 1 else 0 } + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is UrlRewriter && + cloudinary == other.cloudinary && + imgix == other.imgix && + akamai == other.akamai + } + + override fun hashCode(): Int = Objects.hash(cloudinary, imgix, akamai) + + override fun toString(): String = + when { + cloudinary != null -> "UrlRewriter{cloudinary=$cloudinary}" + imgix != null -> "UrlRewriter{imgix=$imgix}" + akamai != null -> "UrlRewriter{akamai=$akamai}" + _json != null -> "UrlRewriter{_unknown=$_json}" + else -> throw IllegalStateException("Invalid UrlRewriter") + } + + companion object { + + @JvmStatic + fun ofCloudinary(cloudinary: Cloudinary) = UrlRewriter(cloudinary = cloudinary) + + @JvmStatic fun ofImgix() = UrlRewriter(imgix = JsonValue.from(mapOf("type" to "IMGIX"))) + + @JvmStatic + fun ofAkamai() = UrlRewriter(akamai = JsonValue.from(mapOf("type" to "AKAMAI"))) + } + + /** + * An interface that defines how to map each variant of [UrlRewriter] to a value of type + * [T]. + */ + interface Visitor { + + fun visitCloudinary(cloudinary: Cloudinary): T + + fun visitImgix(imgix: JsonValue): T + + fun visitAkamai(akamai: JsonValue): T + + /** + * Maps an unknown variant of [UrlRewriter] to a value of type [T]. + * + * An instance of [UrlRewriter] can contain an unknown variant if it was deserialized + * from data that doesn't match any known variant. For example, if the SDK is on an + * older version than the API, then the API may respond with new variants that the SDK + * is unaware of. + * + * @throws ImageKitInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw ImageKitInvalidDataException("Unknown UrlRewriter: $json") + } + } + + internal class Deserializer : BaseDeserializer(UrlRewriter::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): UrlRewriter { + val json = JsonValue.fromJsonNode(node) + val type = json.asObject().getOrNull()?.get("type")?.asString()?.getOrNull() + + when (type) { + "CLOUDINARY" -> { + return tryDeserialize(node, jacksonTypeRef())?.let { + UrlRewriter(cloudinary = it, _json = json) + } ?: UrlRewriter(_json = json) + } + "IMGIX" -> { + return tryDeserialize(node, jacksonTypeRef()) + ?.let { UrlRewriter(imgix = it, _json = json) } + ?.takeIf { it.isValid() } ?: UrlRewriter(_json = json) + } + "AKAMAI" -> { + return tryDeserialize(node, jacksonTypeRef()) + ?.let { UrlRewriter(akamai = it, _json = json) } + ?.takeIf { it.isValid() } ?: UrlRewriter(_json = json) + } + } + + return UrlRewriter(_json = json) + } + } + + internal class Serializer : BaseSerializer(UrlRewriter::class) { + + override fun serialize( + value: UrlRewriter, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.cloudinary != null -> generator.writeObject(value.cloudinary) + value.imgix != null -> generator.writeObject(value.imgix) + value.akamai != null -> generator.writeObject(value.akamai) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid UrlRewriter") + } + } + } + + class Cloudinary + private constructor( + private val preserveAssetDeliveryTypes: JsonField, + private val type: JsonValue, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("preserveAssetDeliveryTypes") + @ExcludeMissing + preserveAssetDeliveryTypes: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(), + ) : this(preserveAssetDeliveryTypes, type, mutableMapOf()) + + /** + * Whether to preserve `/` in the rewritten URL. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected + * value). + */ + fun preserveAssetDeliveryTypes(): Boolean = + preserveAssetDeliveryTypes.getRequired("preserveAssetDeliveryTypes") + + /** + * Expected to always return the following: + * ```java + * JsonValue.from("CLOUDINARY") + * ``` + * + * However, this method can be useful for debugging and logging (e.g. if the server + * responded with an unexpected value). + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type + + /** + * Returns the raw JSON value of [preserveAssetDeliveryTypes]. + * + * Unlike [preserveAssetDeliveryTypes], this method doesn't throw if the JSON field has + * an unexpected type. + */ + @JsonProperty("preserveAssetDeliveryTypes") + @ExcludeMissing + fun _preserveAssetDeliveryTypes(): JsonField = preserveAssetDeliveryTypes + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Cloudinary]. + * + * The following fields are required: + * ```java + * .preserveAssetDeliveryTypes() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Cloudinary]. */ + class Builder internal constructor() { + + private var preserveAssetDeliveryTypes: JsonField? = null + private var type: JsonValue = JsonValue.from("CLOUDINARY") + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(cloudinary: Cloudinary) = apply { + preserveAssetDeliveryTypes = cloudinary.preserveAssetDeliveryTypes + type = cloudinary.type + additionalProperties = cloudinary.additionalProperties.toMutableMap() + } + + /** Whether to preserve `/` in the rewritten URL. */ + fun preserveAssetDeliveryTypes(preserveAssetDeliveryTypes: Boolean) = + preserveAssetDeliveryTypes(JsonField.of(preserveAssetDeliveryTypes)) + + /** + * Sets [Builder.preserveAssetDeliveryTypes] to an arbitrary JSON value. + * + * You should usually call [Builder.preserveAssetDeliveryTypes] with a well-typed + * [Boolean] value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun preserveAssetDeliveryTypes(preserveAssetDeliveryTypes: JsonField) = + apply { + this.preserveAssetDeliveryTypes = preserveAssetDeliveryTypes + } + + /** + * Sets the field to an arbitrary JSON value. + * + * It is usually unnecessary to call this method because the field defaults to the + * following: + * ```java + * JsonValue.from("CLOUDINARY") + * ``` + * + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun type(type: JsonValue) = apply { this.type = type } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Cloudinary]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .preserveAssetDeliveryTypes() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Cloudinary = + Cloudinary( + checkRequired("preserveAssetDeliveryTypes", preserveAssetDeliveryTypes), + type, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Cloudinary = apply { + if (validated) { + return@apply + } + + preserveAssetDeliveryTypes() + _type().let { + if (it != JsonValue.from("CLOUDINARY")) { + throw ImageKitInvalidDataException("'type' is invalid, received $it") + } + } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (preserveAssetDeliveryTypes.asKnown().isPresent) 1 else 0) + + type.let { if (it == JsonValue.from("CLOUDINARY")) 1 else 0 } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Cloudinary && + preserveAssetDeliveryTypes == other.preserveAssetDeliveryTypes && + type == other.type && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(preserveAssetDeliveryTypes, type, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Cloudinary{preserveAssetDeliveryTypes=$preserveAssetDeliveryTypes, type=$type, additionalProperties=$additionalProperties}" + } + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is UrlEndpointResponse && + id == other.id && + description == other.description && + origins == other.origins && + urlPrefix == other.urlPrefix && + urlRewriter == other.urlRewriter && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(id, description, origins, urlPrefix, urlRewriter, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "UrlEndpointResponse{id=$id, description=$description, origins=$origins, urlPrefix=$urlPrefix, urlRewriter=$urlRewriter, additionalProperties=$additionalProperties}" +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/accounts/urlendpoints/UrlEndpointUpdateParams.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/accounts/urlendpoints/UrlEndpointUpdateParams.kt new file mode 100644 index 0000000..0af7b50 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/accounts/urlendpoints/UrlEndpointUpdateParams.kt @@ -0,0 +1,237 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.accounts.urlendpoints + +import com.imagekit.api.core.JsonValue +import com.imagekit.api.core.Params +import com.imagekit.api.core.checkRequired +import com.imagekit.api.core.http.Headers +import com.imagekit.api.core.http.QueryParams +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** + * **Note:** This API is currently in beta. Updates the URL‑endpoint identified by `id` and returns + * the updated object. + */ +class UrlEndpointUpdateParams +private constructor( + private val id: String?, + private val urlEndpointRequest: UrlEndpointRequest, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** + * Unique identifier for the URL-endpoint. This is generated by ImageKit when you create a new + * URL-endpoint. For the default URL-endpoint, this is always `default`. + */ + fun id(): Optional = Optional.ofNullable(id) + + /** Schema for URL endpoint resource. */ + fun urlEndpointRequest(): UrlEndpointRequest = urlEndpointRequest + + fun _additionalBodyProperties(): Map = + urlEndpointRequest._additionalProperties() + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [UrlEndpointUpdateParams]. + * + * The following fields are required: + * ```java + * .urlEndpointRequest() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [UrlEndpointUpdateParams]. */ + class Builder internal constructor() { + + private var id: String? = null + private var urlEndpointRequest: UrlEndpointRequest? = null + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + + @JvmSynthetic + internal fun from(urlEndpointUpdateParams: UrlEndpointUpdateParams) = apply { + id = urlEndpointUpdateParams.id + urlEndpointRequest = urlEndpointUpdateParams.urlEndpointRequest + additionalHeaders = urlEndpointUpdateParams.additionalHeaders.toBuilder() + additionalQueryParams = urlEndpointUpdateParams.additionalQueryParams.toBuilder() + } + + /** + * Unique identifier for the URL-endpoint. This is generated by ImageKit when you create a + * new URL-endpoint. For the default URL-endpoint, this is always `default`. + */ + fun id(id: String?) = apply { this.id = id } + + /** Alias for calling [Builder.id] with `id.orElse(null)`. */ + fun id(id: Optional) = id(id.getOrNull()) + + /** Schema for URL endpoint resource. */ + fun urlEndpointRequest(urlEndpointRequest: UrlEndpointRequest) = apply { + this.urlEndpointRequest = urlEndpointRequest + } + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + /** + * Returns an immutable instance of [UrlEndpointUpdateParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .urlEndpointRequest() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): UrlEndpointUpdateParams = + UrlEndpointUpdateParams( + id, + checkRequired("urlEndpointRequest", urlEndpointRequest), + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } + + fun _body(): UrlEndpointRequest = urlEndpointRequest + + fun _pathParam(index: Int): String = + when (index) { + 0 -> id ?: "" + else -> "" + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is UrlEndpointUpdateParams && + id == other.id && + urlEndpointRequest == other.urlEndpointRequest && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = + Objects.hash(id, urlEndpointRequest, additionalHeaders, additionalQueryParams) + + override fun toString() = + "UrlEndpointUpdateParams{id=$id, urlEndpointRequest=$urlEndpointRequest, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/accounts/usage/UsageGetParams.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/accounts/usage/UsageGetParams.kt new file mode 100644 index 0000000..a8e88bf --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/accounts/usage/UsageGetParams.kt @@ -0,0 +1,235 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.accounts.usage + +import com.imagekit.api.core.Params +import com.imagekit.api.core.checkRequired +import com.imagekit.api.core.http.Headers +import com.imagekit.api.core.http.QueryParams +import java.time.LocalDate +import java.util.Objects + +/** + * Get the account usage information between two dates. Note that the API response includes data + * from the start date while excluding data from the end date. In other words, the data covers the + * period starting from the specified start date up to, but not including, the end date. + */ +class UsageGetParams +private constructor( + private val endDate: LocalDate, + private val startDate: LocalDate, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** + * Specify a `endDate` in `YYYY-MM-DD` format. It should be after the `startDate`. The + * difference between `startDate` and `endDate` should be less than 90 days. + */ + fun endDate(): LocalDate = endDate + + /** + * Specify a `startDate` in `YYYY-MM-DD` format. It should be before the `endDate`. The + * difference between `startDate` and `endDate` should be less than 90 days. + */ + fun startDate(): LocalDate = startDate + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [UsageGetParams]. + * + * The following fields are required: + * ```java + * .endDate() + * .startDate() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [UsageGetParams]. */ + class Builder internal constructor() { + + private var endDate: LocalDate? = null + private var startDate: LocalDate? = null + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + + @JvmSynthetic + internal fun from(usageGetParams: UsageGetParams) = apply { + endDate = usageGetParams.endDate + startDate = usageGetParams.startDate + additionalHeaders = usageGetParams.additionalHeaders.toBuilder() + additionalQueryParams = usageGetParams.additionalQueryParams.toBuilder() + } + + /** + * Specify a `endDate` in `YYYY-MM-DD` format. It should be after the `startDate`. The + * difference between `startDate` and `endDate` should be less than 90 days. + */ + fun endDate(endDate: LocalDate) = apply { this.endDate = endDate } + + /** + * Specify a `startDate` in `YYYY-MM-DD` format. It should be before the `endDate`. The + * difference between `startDate` and `endDate` should be less than 90 days. + */ + fun startDate(startDate: LocalDate) = apply { this.startDate = startDate } + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + /** + * Returns an immutable instance of [UsageGetParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .endDate() + * .startDate() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): UsageGetParams = + UsageGetParams( + checkRequired("endDate", endDate), + checkRequired("startDate", startDate), + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = + QueryParams.builder() + .apply { + put("endDate", endDate.toString()) + put("startDate", startDate.toString()) + putAll(additionalQueryParams) + } + .build() + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is UsageGetParams && + endDate == other.endDate && + startDate == other.startDate && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = + Objects.hash(endDate, startDate, additionalHeaders, additionalQueryParams) + + override fun toString() = + "UsageGetParams{endDate=$endDate, startDate=$startDate, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/accounts/usage/UsageGetResponse.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/accounts/usage/UsageGetResponse.kt new file mode 100644 index 0000000..3239c0e --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/accounts/usage/UsageGetResponse.kt @@ -0,0 +1,359 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.accounts.usage + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.imagekit.api.core.ExcludeMissing +import com.imagekit.api.core.JsonField +import com.imagekit.api.core.JsonMissing +import com.imagekit.api.core.JsonValue +import com.imagekit.api.errors.ImageKitInvalidDataException +import java.util.Collections +import java.util.Objects +import java.util.Optional + +class UsageGetResponse +private constructor( + private val bandwidthBytes: JsonField, + private val extensionUnitsCount: JsonField, + private val mediaLibraryStorageBytes: JsonField, + private val originalCacheStorageBytes: JsonField, + private val videoProcessingUnitsCount: JsonField, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("bandwidthBytes") + @ExcludeMissing + bandwidthBytes: JsonField = JsonMissing.of(), + @JsonProperty("extensionUnitsCount") + @ExcludeMissing + extensionUnitsCount: JsonField = JsonMissing.of(), + @JsonProperty("mediaLibraryStorageBytes") + @ExcludeMissing + mediaLibraryStorageBytes: JsonField = JsonMissing.of(), + @JsonProperty("originalCacheStorageBytes") + @ExcludeMissing + originalCacheStorageBytes: JsonField = JsonMissing.of(), + @JsonProperty("videoProcessingUnitsCount") + @ExcludeMissing + videoProcessingUnitsCount: JsonField = JsonMissing.of(), + ) : this( + bandwidthBytes, + extensionUnitsCount, + mediaLibraryStorageBytes, + originalCacheStorageBytes, + videoProcessingUnitsCount, + mutableMapOf(), + ) + + /** + * Amount of bandwidth used in bytes. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun bandwidthBytes(): Optional = bandwidthBytes.getOptional("bandwidthBytes") + + /** + * Number of extension units used. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun extensionUnitsCount(): Optional = + extensionUnitsCount.getOptional("extensionUnitsCount") + + /** + * Storage used by media library in bytes. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun mediaLibraryStorageBytes(): Optional = + mediaLibraryStorageBytes.getOptional("mediaLibraryStorageBytes") + + /** + * Storage used by the original cache in bytes. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun originalCacheStorageBytes(): Optional = + originalCacheStorageBytes.getOptional("originalCacheStorageBytes") + + /** + * Number of video processing units used. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun videoProcessingUnitsCount(): Optional = + videoProcessingUnitsCount.getOptional("videoProcessingUnitsCount") + + /** + * Returns the raw JSON value of [bandwidthBytes]. + * + * Unlike [bandwidthBytes], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("bandwidthBytes") + @ExcludeMissing + fun _bandwidthBytes(): JsonField = bandwidthBytes + + /** + * Returns the raw JSON value of [extensionUnitsCount]. + * + * Unlike [extensionUnitsCount], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("extensionUnitsCount") + @ExcludeMissing + fun _extensionUnitsCount(): JsonField = extensionUnitsCount + + /** + * Returns the raw JSON value of [mediaLibraryStorageBytes]. + * + * Unlike [mediaLibraryStorageBytes], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("mediaLibraryStorageBytes") + @ExcludeMissing + fun _mediaLibraryStorageBytes(): JsonField = mediaLibraryStorageBytes + + /** + * Returns the raw JSON value of [originalCacheStorageBytes]. + * + * Unlike [originalCacheStorageBytes], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("originalCacheStorageBytes") + @ExcludeMissing + fun _originalCacheStorageBytes(): JsonField = originalCacheStorageBytes + + /** + * Returns the raw JSON value of [videoProcessingUnitsCount]. + * + * Unlike [videoProcessingUnitsCount], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("videoProcessingUnitsCount") + @ExcludeMissing + fun _videoProcessingUnitsCount(): JsonField = videoProcessingUnitsCount + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [UsageGetResponse]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [UsageGetResponse]. */ + class Builder internal constructor() { + + private var bandwidthBytes: JsonField = JsonMissing.of() + private var extensionUnitsCount: JsonField = JsonMissing.of() + private var mediaLibraryStorageBytes: JsonField = JsonMissing.of() + private var originalCacheStorageBytes: JsonField = JsonMissing.of() + private var videoProcessingUnitsCount: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(usageGetResponse: UsageGetResponse) = apply { + bandwidthBytes = usageGetResponse.bandwidthBytes + extensionUnitsCount = usageGetResponse.extensionUnitsCount + mediaLibraryStorageBytes = usageGetResponse.mediaLibraryStorageBytes + originalCacheStorageBytes = usageGetResponse.originalCacheStorageBytes + videoProcessingUnitsCount = usageGetResponse.videoProcessingUnitsCount + additionalProperties = usageGetResponse.additionalProperties.toMutableMap() + } + + /** Amount of bandwidth used in bytes. */ + fun bandwidthBytes(bandwidthBytes: Long) = bandwidthBytes(JsonField.of(bandwidthBytes)) + + /** + * Sets [Builder.bandwidthBytes] to an arbitrary JSON value. + * + * You should usually call [Builder.bandwidthBytes] with a well-typed [Long] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun bandwidthBytes(bandwidthBytes: JsonField) = apply { + this.bandwidthBytes = bandwidthBytes + } + + /** Number of extension units used. */ + fun extensionUnitsCount(extensionUnitsCount: Long) = + extensionUnitsCount(JsonField.of(extensionUnitsCount)) + + /** + * Sets [Builder.extensionUnitsCount] to an arbitrary JSON value. + * + * You should usually call [Builder.extensionUnitsCount] with a well-typed [Long] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun extensionUnitsCount(extensionUnitsCount: JsonField) = apply { + this.extensionUnitsCount = extensionUnitsCount + } + + /** Storage used by media library in bytes. */ + fun mediaLibraryStorageBytes(mediaLibraryStorageBytes: Long) = + mediaLibraryStorageBytes(JsonField.of(mediaLibraryStorageBytes)) + + /** + * Sets [Builder.mediaLibraryStorageBytes] to an arbitrary JSON value. + * + * You should usually call [Builder.mediaLibraryStorageBytes] with a well-typed [Long] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun mediaLibraryStorageBytes(mediaLibraryStorageBytes: JsonField) = apply { + this.mediaLibraryStorageBytes = mediaLibraryStorageBytes + } + + /** Storage used by the original cache in bytes. */ + fun originalCacheStorageBytes(originalCacheStorageBytes: Long) = + originalCacheStorageBytes(JsonField.of(originalCacheStorageBytes)) + + /** + * Sets [Builder.originalCacheStorageBytes] to an arbitrary JSON value. + * + * You should usually call [Builder.originalCacheStorageBytes] with a well-typed [Long] + * value instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun originalCacheStorageBytes(originalCacheStorageBytes: JsonField) = apply { + this.originalCacheStorageBytes = originalCacheStorageBytes + } + + /** Number of video processing units used. */ + fun videoProcessingUnitsCount(videoProcessingUnitsCount: Long) = + videoProcessingUnitsCount(JsonField.of(videoProcessingUnitsCount)) + + /** + * Sets [Builder.videoProcessingUnitsCount] to an arbitrary JSON value. + * + * You should usually call [Builder.videoProcessingUnitsCount] with a well-typed [Long] + * value instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun videoProcessingUnitsCount(videoProcessingUnitsCount: JsonField) = apply { + this.videoProcessingUnitsCount = videoProcessingUnitsCount + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [UsageGetResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): UsageGetResponse = + UsageGetResponse( + bandwidthBytes, + extensionUnitsCount, + mediaLibraryStorageBytes, + originalCacheStorageBytes, + videoProcessingUnitsCount, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): UsageGetResponse = apply { + if (validated) { + return@apply + } + + bandwidthBytes() + extensionUnitsCount() + mediaLibraryStorageBytes() + originalCacheStorageBytes() + videoProcessingUnitsCount() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (bandwidthBytes.asKnown().isPresent) 1 else 0) + + (if (extensionUnitsCount.asKnown().isPresent) 1 else 0) + + (if (mediaLibraryStorageBytes.asKnown().isPresent) 1 else 0) + + (if (originalCacheStorageBytes.asKnown().isPresent) 1 else 0) + + (if (videoProcessingUnitsCount.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is UsageGetResponse && + bandwidthBytes == other.bandwidthBytes && + extensionUnitsCount == other.extensionUnitsCount && + mediaLibraryStorageBytes == other.mediaLibraryStorageBytes && + originalCacheStorageBytes == other.originalCacheStorageBytes && + videoProcessingUnitsCount == other.videoProcessingUnitsCount && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + bandwidthBytes, + extensionUnitsCount, + mediaLibraryStorageBytes, + originalCacheStorageBytes, + videoProcessingUnitsCount, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "UsageGetResponse{bandwidthBytes=$bandwidthBytes, extensionUnitsCount=$extensionUnitsCount, mediaLibraryStorageBytes=$mediaLibraryStorageBytes, originalCacheStorageBytes=$originalCacheStorageBytes, videoProcessingUnitsCount=$videoProcessingUnitsCount, additionalProperties=$additionalProperties}" +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/assets/AssetListParams.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/assets/AssetListParams.kt new file mode 100644 index 0000000..78ed7c9 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/assets/AssetListParams.kt @@ -0,0 +1,865 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.assets + +import com.fasterxml.jackson.annotation.JsonCreator +import com.imagekit.api.core.Enum +import com.imagekit.api.core.JsonField +import com.imagekit.api.core.Params +import com.imagekit.api.core.http.Headers +import com.imagekit.api.core.http.QueryParams +import com.imagekit.api.errors.ImageKitInvalidDataException +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** + * This API can list all the uploaded files and folders in your ImageKit.io media library. In + * addition, you can fine-tune your query by specifying various filters by generating a query string + * in a Lucene-like syntax and provide this generated string as the value of the `searchQuery`. + */ +class AssetListParams +private constructor( + private val fileType: FileType?, + private val limit: Long?, + private val path: String?, + private val searchQuery: String?, + private val skip: Long?, + private val sort: Sort?, + private val type: Type?, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** + * Filter results by file type. + * - `all` — include all file types + * - `image` — include only image files + * - `non-image` — include only non-image files (e.g., JS, CSS, video) + */ + fun fileType(): Optional = Optional.ofNullable(fileType) + + /** The maximum number of results to return in response. */ + fun limit(): Optional = Optional.ofNullable(limit) + + /** + * Folder path if you want to limit the search within a specific folder. For example, + * `/sales-banner/` will only search in folder sales-banner. + * + * Note : If your use case involves searching within a folder as well as its subfolders, you can + * use `path` parameter in `searchQuery` with appropriate operator. Checkout + * [Supported parameters](/docs/api-reference/digital-asset-management-dam/list-and-search-assets#supported-parameters) + * for more information. + */ + fun path(): Optional = Optional.ofNullable(path) + + /** + * Query string in a Lucene-like query language e.g. `createdAt > "7d"`. + * + * Note : When the searchQuery parameter is present, the following query parameters will have no + * effect on the result: + * 1. `tags` + * 2. `type` + * 3. `name` + * + * [Learn + * more](/docs/api-reference/digital-asset-management-dam/list-and-search-assets#advanced-search-queries) + * from examples. + */ + fun searchQuery(): Optional = Optional.ofNullable(searchQuery) + + /** The number of results to skip before returning results. */ + fun skip(): Optional = Optional.ofNullable(skip) + + /** Sort the results by one of the supported fields in ascending or descending order. */ + fun sort(): Optional = Optional.ofNullable(sort) + + /** + * Filter results by asset type. + * - `file` — returns only files + * - `file-version` — returns specific file versions + * - `folder` — returns only folders + * - `all` — returns both files and folders (excludes `file-version`) + */ + fun type(): Optional = Optional.ofNullable(type) + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun none(): AssetListParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [AssetListParams]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [AssetListParams]. */ + class Builder internal constructor() { + + private var fileType: FileType? = null + private var limit: Long? = null + private var path: String? = null + private var searchQuery: String? = null + private var skip: Long? = null + private var sort: Sort? = null + private var type: Type? = null + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + + @JvmSynthetic + internal fun from(assetListParams: AssetListParams) = apply { + fileType = assetListParams.fileType + limit = assetListParams.limit + path = assetListParams.path + searchQuery = assetListParams.searchQuery + skip = assetListParams.skip + sort = assetListParams.sort + type = assetListParams.type + additionalHeaders = assetListParams.additionalHeaders.toBuilder() + additionalQueryParams = assetListParams.additionalQueryParams.toBuilder() + } + + /** + * Filter results by file type. + * - `all` — include all file types + * - `image` — include only image files + * - `non-image` — include only non-image files (e.g., JS, CSS, video) + */ + fun fileType(fileType: FileType?) = apply { this.fileType = fileType } + + /** Alias for calling [Builder.fileType] with `fileType.orElse(null)`. */ + fun fileType(fileType: Optional) = fileType(fileType.getOrNull()) + + /** The maximum number of results to return in response. */ + fun limit(limit: Long?) = apply { this.limit = limit } + + /** + * Alias for [Builder.limit]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun limit(limit: Long) = limit(limit as Long?) + + /** Alias for calling [Builder.limit] with `limit.orElse(null)`. */ + fun limit(limit: Optional) = limit(limit.getOrNull()) + + /** + * Folder path if you want to limit the search within a specific folder. For example, + * `/sales-banner/` will only search in folder sales-banner. + * + * Note : If your use case involves searching within a folder as well as its subfolders, you + * can use `path` parameter in `searchQuery` with appropriate operator. Checkout + * [Supported parameters](/docs/api-reference/digital-asset-management-dam/list-and-search-assets#supported-parameters) + * for more information. + */ + fun path(path: String?) = apply { this.path = path } + + /** Alias for calling [Builder.path] with `path.orElse(null)`. */ + fun path(path: Optional) = path(path.getOrNull()) + + /** + * Query string in a Lucene-like query language e.g. `createdAt > "7d"`. + * + * Note : When the searchQuery parameter is present, the following query parameters will + * have no effect on the result: + * 1. `tags` + * 2. `type` + * 3. `name` + * + * [Learn + * more](/docs/api-reference/digital-asset-management-dam/list-and-search-assets#advanced-search-queries) + * from examples. + */ + fun searchQuery(searchQuery: String?) = apply { this.searchQuery = searchQuery } + + /** Alias for calling [Builder.searchQuery] with `searchQuery.orElse(null)`. */ + fun searchQuery(searchQuery: Optional) = searchQuery(searchQuery.getOrNull()) + + /** The number of results to skip before returning results. */ + fun skip(skip: Long?) = apply { this.skip = skip } + + /** + * Alias for [Builder.skip]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun skip(skip: Long) = skip(skip as Long?) + + /** Alias for calling [Builder.skip] with `skip.orElse(null)`. */ + fun skip(skip: Optional) = skip(skip.getOrNull()) + + /** Sort the results by one of the supported fields in ascending or descending order. */ + fun sort(sort: Sort?) = apply { this.sort = sort } + + /** Alias for calling [Builder.sort] with `sort.orElse(null)`. */ + fun sort(sort: Optional) = sort(sort.getOrNull()) + + /** + * Filter results by asset type. + * - `file` — returns only files + * - `file-version` — returns specific file versions + * - `folder` — returns only folders + * - `all` — returns both files and folders (excludes `file-version`) + */ + fun type(type: Type?) = apply { this.type = type } + + /** Alias for calling [Builder.type] with `type.orElse(null)`. */ + fun type(type: Optional) = type(type.getOrNull()) + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + /** + * Returns an immutable instance of [AssetListParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): AssetListParams = + AssetListParams( + fileType, + limit, + path, + searchQuery, + skip, + sort, + type, + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = + QueryParams.builder() + .apply { + fileType?.let { put("fileType", it.toString()) } + limit?.let { put("limit", it.toString()) } + path?.let { put("path", it) } + searchQuery?.let { put("searchQuery", it) } + skip?.let { put("skip", it.toString()) } + sort?.let { put("sort", it.toString()) } + type?.let { put("type", it.toString()) } + putAll(additionalQueryParams) + } + .build() + + /** + * Filter results by file type. + * - `all` — include all file types + * - `image` — include only image files + * - `non-image` — include only non-image files (e.g., JS, CSS, video) + */ + class FileType @JsonCreator private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is on an + * older version than the API, then the API may respond with new members that the SDK is + * unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val ALL = of("all") + + @JvmField val IMAGE = of("image") + + @JvmField val NON_IMAGE = of("non-image") + + @JvmStatic fun of(value: String) = FileType(JsonField.of(value)) + } + + /** An enum containing [FileType]'s known values. */ + enum class Known { + ALL, + IMAGE, + NON_IMAGE, + } + + /** + * An enum containing [FileType]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [FileType] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if the + * SDK is on an older version than the API, then the API may respond with new members that + * the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + ALL, + IMAGE, + NON_IMAGE, + /** An enum member indicating that [FileType] was instantiated with an unknown value. */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] + * if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you want + * to throw for the unknown case. + */ + fun value(): Value = + when (this) { + ALL -> Value.ALL + IMAGE -> Value.IMAGE + NON_IMAGE -> Value.NON_IMAGE + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and don't + * want to throw for the unknown case. + * + * @throws ImageKitInvalidDataException if this class instance's value is a not a known + * member. + */ + fun known(): Known = + when (this) { + ALL -> Known.ALL + IMAGE -> Known.IMAGE + NON_IMAGE -> Known.NON_IMAGE + else -> throw ImageKitInvalidDataException("Unknown FileType: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for debugging + * and generally doesn't throw. + * + * @throws ImageKitInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + ImageKitInvalidDataException("Value is not a String") + } + + private var validated: Boolean = false + + fun validate(): FileType = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is FileType && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + /** Sort the results by one of the supported fields in ascending or descending order. */ + class Sort @JsonCreator private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is on an + * older version than the API, then the API may respond with new members that the SDK is + * unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val ASC_NAME = of("ASC_NAME") + + @JvmField val DESC_NAME = of("DESC_NAME") + + @JvmField val ASC_CREATED = of("ASC_CREATED") + + @JvmField val DESC_CREATED = of("DESC_CREATED") + + @JvmField val ASC_UPDATED = of("ASC_UPDATED") + + @JvmField val DESC_UPDATED = of("DESC_UPDATED") + + @JvmField val ASC_HEIGHT = of("ASC_HEIGHT") + + @JvmField val DESC_HEIGHT = of("DESC_HEIGHT") + + @JvmField val ASC_WIDTH = of("ASC_WIDTH") + + @JvmField val DESC_WIDTH = of("DESC_WIDTH") + + @JvmField val ASC_SIZE = of("ASC_SIZE") + + @JvmField val DESC_SIZE = of("DESC_SIZE") + + @JvmField val ASC_RELEVANCE = of("ASC_RELEVANCE") + + @JvmField val DESC_RELEVANCE = of("DESC_RELEVANCE") + + @JvmStatic fun of(value: String) = Sort(JsonField.of(value)) + } + + /** An enum containing [Sort]'s known values. */ + enum class Known { + ASC_NAME, + DESC_NAME, + ASC_CREATED, + DESC_CREATED, + ASC_UPDATED, + DESC_UPDATED, + ASC_HEIGHT, + DESC_HEIGHT, + ASC_WIDTH, + DESC_WIDTH, + ASC_SIZE, + DESC_SIZE, + ASC_RELEVANCE, + DESC_RELEVANCE, + } + + /** + * An enum containing [Sort]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [Sort] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if the + * SDK is on an older version than the API, then the API may respond with new members that + * the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + ASC_NAME, + DESC_NAME, + ASC_CREATED, + DESC_CREATED, + ASC_UPDATED, + DESC_UPDATED, + ASC_HEIGHT, + DESC_HEIGHT, + ASC_WIDTH, + DESC_WIDTH, + ASC_SIZE, + DESC_SIZE, + ASC_RELEVANCE, + DESC_RELEVANCE, + /** An enum member indicating that [Sort] was instantiated with an unknown value. */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] + * if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you want + * to throw for the unknown case. + */ + fun value(): Value = + when (this) { + ASC_NAME -> Value.ASC_NAME + DESC_NAME -> Value.DESC_NAME + ASC_CREATED -> Value.ASC_CREATED + DESC_CREATED -> Value.DESC_CREATED + ASC_UPDATED -> Value.ASC_UPDATED + DESC_UPDATED -> Value.DESC_UPDATED + ASC_HEIGHT -> Value.ASC_HEIGHT + DESC_HEIGHT -> Value.DESC_HEIGHT + ASC_WIDTH -> Value.ASC_WIDTH + DESC_WIDTH -> Value.DESC_WIDTH + ASC_SIZE -> Value.ASC_SIZE + DESC_SIZE -> Value.DESC_SIZE + ASC_RELEVANCE -> Value.ASC_RELEVANCE + DESC_RELEVANCE -> Value.DESC_RELEVANCE + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and don't + * want to throw for the unknown case. + * + * @throws ImageKitInvalidDataException if this class instance's value is a not a known + * member. + */ + fun known(): Known = + when (this) { + ASC_NAME -> Known.ASC_NAME + DESC_NAME -> Known.DESC_NAME + ASC_CREATED -> Known.ASC_CREATED + DESC_CREATED -> Known.DESC_CREATED + ASC_UPDATED -> Known.ASC_UPDATED + DESC_UPDATED -> Known.DESC_UPDATED + ASC_HEIGHT -> Known.ASC_HEIGHT + DESC_HEIGHT -> Known.DESC_HEIGHT + ASC_WIDTH -> Known.ASC_WIDTH + DESC_WIDTH -> Known.DESC_WIDTH + ASC_SIZE -> Known.ASC_SIZE + DESC_SIZE -> Known.DESC_SIZE + ASC_RELEVANCE -> Known.ASC_RELEVANCE + DESC_RELEVANCE -> Known.DESC_RELEVANCE + else -> throw ImageKitInvalidDataException("Unknown Sort: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for debugging + * and generally doesn't throw. + * + * @throws ImageKitInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + ImageKitInvalidDataException("Value is not a String") + } + + private var validated: Boolean = false + + fun validate(): Sort = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Sort && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + /** + * Filter results by asset type. + * - `file` — returns only files + * - `file-version` — returns specific file versions + * - `folder` — returns only folders + * - `all` — returns both files and folders (excludes `file-version`) + */ + class Type @JsonCreator private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is on an + * older version than the API, then the API may respond with new members that the SDK is + * unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val FILE = of("file") + + @JvmField val FILE_VERSION = of("file-version") + + @JvmField val FOLDER = of("folder") + + @JvmField val ALL = of("all") + + @JvmStatic fun of(value: String) = Type(JsonField.of(value)) + } + + /** An enum containing [Type]'s known values. */ + enum class Known { + FILE, + FILE_VERSION, + FOLDER, + ALL, + } + + /** + * An enum containing [Type]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [Type] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if the + * SDK is on an older version than the API, then the API may respond with new members that + * the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + FILE, + FILE_VERSION, + FOLDER, + ALL, + /** An enum member indicating that [Type] was instantiated with an unknown value. */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] + * if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you want + * to throw for the unknown case. + */ + fun value(): Value = + when (this) { + FILE -> Value.FILE + FILE_VERSION -> Value.FILE_VERSION + FOLDER -> Value.FOLDER + ALL -> Value.ALL + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and don't + * want to throw for the unknown case. + * + * @throws ImageKitInvalidDataException if this class instance's value is a not a known + * member. + */ + fun known(): Known = + when (this) { + FILE -> Known.FILE + FILE_VERSION -> Known.FILE_VERSION + FOLDER -> Known.FOLDER + ALL -> Known.ALL + else -> throw ImageKitInvalidDataException("Unknown Type: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for debugging + * and generally doesn't throw. + * + * @throws ImageKitInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + ImageKitInvalidDataException("Value is not a String") + } + + private var validated: Boolean = false + + fun validate(): Type = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Type && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is AssetListParams && + fileType == other.fileType && + limit == other.limit && + path == other.path && + searchQuery == other.searchQuery && + skip == other.skip && + sort == other.sort && + type == other.type && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = + Objects.hash( + fileType, + limit, + path, + searchQuery, + skip, + sort, + type, + additionalHeaders, + additionalQueryParams, + ) + + override fun toString() = + "AssetListParams{fileType=$fileType, limit=$limit, path=$path, searchQuery=$searchQuery, skip=$skip, sort=$sort, type=$type, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/assets/AssetListResponse.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/assets/AssetListResponse.kt new file mode 100644 index 0000000..8e1fbee --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/assets/AssetListResponse.kt @@ -0,0 +1,187 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.assets + +import com.fasterxml.jackson.core.JsonGenerator +import com.fasterxml.jackson.core.ObjectCodec +import com.fasterxml.jackson.databind.JsonNode +import com.fasterxml.jackson.databind.SerializerProvider +import com.fasterxml.jackson.databind.annotation.JsonDeserialize +import com.fasterxml.jackson.databind.annotation.JsonSerialize +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.imagekit.api.core.BaseDeserializer +import com.imagekit.api.core.BaseSerializer +import com.imagekit.api.core.JsonValue +import com.imagekit.api.core.getOrThrow +import com.imagekit.api.errors.ImageKitInvalidDataException +import com.imagekit.api.models.files.File +import com.imagekit.api.models.files.Folder +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** Object containing details of a file or file version. */ +@JsonDeserialize(using = AssetListResponse.Deserializer::class) +@JsonSerialize(using = AssetListResponse.Serializer::class) +class AssetListResponse +private constructor( + private val file: File? = null, + private val folder: Folder? = null, + private val _json: JsonValue? = null, +) { + + /** Object containing details of a file or file version. */ + fun file(): Optional = Optional.ofNullable(file) + + fun folder(): Optional = Optional.ofNullable(folder) + + fun isFile(): Boolean = file != null + + fun isFolder(): Boolean = folder != null + + /** Object containing details of a file or file version. */ + fun asFile(): File = file.getOrThrow("file") + + fun asFolder(): Folder = folder.getOrThrow("folder") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + file != null -> visitor.visitFile(file) + folder != null -> visitor.visitFolder(folder) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): AssetListResponse = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitFile(file: File) { + file.validate() + } + + override fun visitFolder(folder: Folder) { + folder.validate() + } + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitFile(file: File) = file.validity() + + override fun visitFolder(folder: Folder) = folder.validity() + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is AssetListResponse && file == other.file && folder == other.folder + } + + override fun hashCode(): Int = Objects.hash(file, folder) + + override fun toString(): String = + when { + file != null -> "AssetListResponse{file=$file}" + folder != null -> "AssetListResponse{folder=$folder}" + _json != null -> "AssetListResponse{_unknown=$_json}" + else -> throw IllegalStateException("Invalid AssetListResponse") + } + + companion object { + + /** Object containing details of a file or file version. */ + @JvmStatic fun ofFile(file: File) = AssetListResponse(file = file) + + @JvmStatic fun ofFolder(folder: Folder) = AssetListResponse(folder = folder) + } + + /** + * An interface that defines how to map each variant of [AssetListResponse] to a value of type + * [T]. + */ + interface Visitor { + + /** Object containing details of a file or file version. */ + fun visitFile(file: File): T + + fun visitFolder(folder: Folder): T + + /** + * Maps an unknown variant of [AssetListResponse] to a value of type [T]. + * + * An instance of [AssetListResponse] can contain an unknown variant if it was deserialized + * from data that doesn't match any known variant. For example, if the SDK is on an older + * version than the API, then the API may respond with new variants that the SDK is unaware + * of. + * + * @throws ImageKitInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw ImageKitInvalidDataException("Unknown AssetListResponse: $json") + } + } + + internal class Deserializer : BaseDeserializer(AssetListResponse::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): AssetListResponse { + val json = JsonValue.fromJsonNode(node) + val type = json.asObject().getOrNull()?.get("type")?.asString()?.getOrNull() + + if (type == "folder") { + return tryDeserialize(node, jacksonTypeRef())?.let { + AssetListResponse(folder = it, _json = json) + } ?: AssetListResponse(_json = json) + } + + return tryDeserialize(node, jacksonTypeRef())?.let { + AssetListResponse(file = it, _json = json) + } ?: AssetListResponse(_json = json) + } + } + + internal class Serializer : BaseSerializer(AssetListResponse::class) { + + override fun serialize( + value: AssetListResponse, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.file != null -> generator.writeObject(value.file) + value.folder != null -> generator.writeObject(value.folder) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid AssetListResponse") + } + } + } +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/beta/v2/files/FileUploadParams.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/beta/v2/files/FileUploadParams.kt new file mode 100644 index 0000000..9c220c9 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/beta/v2/files/FileUploadParams.kt @@ -0,0 +1,4945 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.beta.v2.files + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.fasterxml.jackson.core.JsonGenerator +import com.fasterxml.jackson.core.ObjectCodec +import com.fasterxml.jackson.databind.JsonNode +import com.fasterxml.jackson.databind.SerializerProvider +import com.fasterxml.jackson.databind.annotation.JsonDeserialize +import com.fasterxml.jackson.databind.annotation.JsonSerialize +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.imagekit.api.core.BaseDeserializer +import com.imagekit.api.core.BaseSerializer +import com.imagekit.api.core.Enum +import com.imagekit.api.core.ExcludeMissing +import com.imagekit.api.core.JsonField +import com.imagekit.api.core.JsonMissing +import com.imagekit.api.core.JsonValue +import com.imagekit.api.core.MultipartField +import com.imagekit.api.core.Params +import com.imagekit.api.core.checkKnown +import com.imagekit.api.core.checkRequired +import com.imagekit.api.core.getOrThrow +import com.imagekit.api.core.http.Headers +import com.imagekit.api.core.http.QueryParams +import com.imagekit.api.core.toImmutable +import com.imagekit.api.errors.ImageKitInvalidDataException +import com.imagekit.api.models.UnnamedSchemaWithArrayParent3 +import java.io.InputStream +import java.nio.file.Path +import java.util.Collections +import java.util.Objects +import java.util.Optional +import kotlin.io.path.inputStream +import kotlin.io.path.name +import kotlin.jvm.optionals.getOrNull + +/** + * The V2 API enhances security by verifying the entire payload using JWT. This API is in beta. + * + * ImageKit.io allows you to upload files directly from both the server and client sides. For + * server-side uploads, private API key authentication is used. For client-side uploads, generate a + * one-time `token` from your secure backend using private API. + * [Learn more](/docs/api-reference/upload-file/upload-file-v2#how-to-implement-secure-client-side-file-upload) + * about how to implement secure client-side file upload. + * + * **File size limit** \ On the free plan, the maximum upload file sizes are 20MB for images, audio, + * and raw files, and 100MB for videos. On the paid plan, these limits increase to 40MB for images, + * audio, and raw files, and 2GB for videos. These limits can be further increased with higher-tier + * plans. + * + * **Version limit** \ A file can have a maximum of 100 versions. + * + * **Demo applications** + * - A full-fledged [upload widget using Uppy](https://github.com/imagekit-samples/uppy-uploader), + * supporting file selections from local storage, URL, Dropbox, Google Drive, Instagram, and more. + * - [Quick start guides](/docs/quick-start-guides) for various frameworks and technologies. + */ +class FileUploadParams +private constructor( + private val body: Body, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** + * The API accepts any of the following: + * - **Binary data** – send the raw bytes as `multipart/form-data`. + * - **HTTP / HTTPS URL** – a publicly reachable URL that ImageKit’s servers can fetch. + * - **Base64 string** – the file encoded as a Base64 data URI or plain Base64. + * + * When supplying a URL, the server must receive the response headers within 8 seconds; + * otherwise the request fails with 400 Bad Request. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun file(): InputStream = body.file() + + /** + * The name with which the file has to be uploaded. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun fileName(): String = body.fileName() + + /** + * This is the client-generated JSON Web Token (JWT). The ImageKit.io server uses it to + * authenticate and check that the upload request parameters have not been tampered with after + * the token has been generated. Learn how to create the token on the page below. This field is + * only required for authentication when uploading a file from the client side. + * + * **Note**: Sending a JWT that has been used in the past will result in a validation error. + * Even if your previous request resulted in an error, you should always send a new token. + * + * **⚠️Warning**: JWT must be generated on the server-side because it is generated using your + * account's private API key. This field is required for authentication when uploading a file + * from the client-side. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun token(): Optional = body.token() + + /** + * Server-side checks to run on the asset. Read more about + * [Upload API checks](/docs/api-reference/upload-file/upload-file-v2#upload-api-checks). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun checks(): Optional = body.checks() + + /** + * Define an important area in the image. This is only relevant for image type files. + * - To be passed as a string with the x and y coordinates of the top-left corner, and width and + * height of the area of interest in the format `x,y,width,height`. For example - + * `10,10,100,100` + * - Can be used with fo-customtransformation. + * - If this field is not specified and the file is overwritten, then customCoordinates will be + * removed. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun customCoordinates(): Optional = body.customCoordinates() + + /** + * JSON key-value pairs to associate with the asset. Create the custom metadata fields before + * setting these values. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun customMetadata(): Optional = body.customMetadata() + + /** + * Optional text to describe the contents of the file. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun description(): Optional = body.description() + + /** + * Array of extensions to be applied to the asset. Each extension can be configured with + * specific parameters based on the extension type. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun extensions(): Optional> = body.extensions() + + /** + * The folder path in which the image has to be uploaded. If the folder(s) didn't exist before, + * a new folder(s) is created. Using multiple `/` creates a nested folder. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun folder(): Optional = body.folder() + + /** + * Whether to mark the file as private or not. + * + * If `true`, the file is marked as private and is accessible only using named transformation or + * signed URL. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun isPrivateFile(): Optional = body.isPrivateFile() + + /** + * Whether to upload file as published or not. + * + * If `false`, the file is marked as unpublished, which restricts access to the file only via + * the media library. Files in draft or unpublished state can only be publicly accessed after + * being published. + * + * The option to upload in draft state is only available in custom enterprise pricing plans. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun isPublished(): Optional = body.isPublished() + + /** + * If set to `true` and a file already exists at the exact location, its AITags will be removed. + * Set `overwriteAITags` to `false` to preserve AITags. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun overwriteAiTags(): Optional = body.overwriteAiTags() + + /** + * If the request does not have `customMetadata`, and a file already exists at the exact + * location, existing customMetadata will be removed. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun overwriteCustomMetadata(): Optional = body.overwriteCustomMetadata() + + /** + * If `false` and `useUniqueFileName` is also `false`, and a file already exists at the exact + * location, upload API will return an error immediately. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun overwriteFile(): Optional = body.overwriteFile() + + /** + * If the request does not have `tags`, and a file already exists at the exact location, + * existing tags will be removed. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun overwriteTags(): Optional = body.overwriteTags() + + /** + * Array of response field keys to include in the API response body. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun responseFields(): Optional> = body.responseFields() + + /** + * Set the tags while uploading the file. Provide an array of tag strings (e.g. `["tag1", + * "tag2", "tag3"]`). The combined length of all tag characters must not exceed 500, and the `%` + * character is not allowed. If this field is not specified and the file is overwritten, the + * existing tags will be removed. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun tags(): Optional> = body.tags() + + /** + * Configure pre-processing (`pre`) and post-processing (`post`) transformations. + * - `pre` — applied before the file is uploaded to the Media Library. Useful for reducing file + * size or applying basic optimizations upfront (e.g., resize, compress). + * - `post` — applied immediately after upload. Ideal for generating transformed versions (like + * video encodes or thumbnails) in advance, so they're ready for delivery without delay. + * + * You can mix and match any combination of post-processing types. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun transformation(): Optional = body.transformation() + + /** + * Whether to use a unique filename for this file or not. + * + * If `true`, ImageKit.io will add a unique suffix to the filename parameter to get a unique + * filename. + * + * If `false`, then the image is uploaded with the provided filename parameter, and any existing + * file with the same name is replaced. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun useUniqueFileName(): Optional = body.useUniqueFileName() + + /** + * The final status of extensions after they have completed execution will be delivered to this + * endpoint as a POST request. + * [Learn more](/docs/api-reference/digital-asset-management-dam/managing-assets/update-file-details#webhook-payload-structure) + * about the webhook payload structure. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun webhookUrl(): Optional = body.webhookUrl() + + /** + * Returns the raw multipart value of [file]. + * + * Unlike [file], this method doesn't throw if the multipart field has an unexpected type. + */ + fun _file(): MultipartField = body._file() + + /** + * Returns the raw multipart value of [fileName]. + * + * Unlike [fileName], this method doesn't throw if the multipart field has an unexpected type. + */ + fun _fileName(): MultipartField = body._fileName() + + /** + * Returns the raw multipart value of [token]. + * + * Unlike [token], this method doesn't throw if the multipart field has an unexpected type. + */ + fun _token(): MultipartField = body._token() + + /** + * Returns the raw multipart value of [checks]. + * + * Unlike [checks], this method doesn't throw if the multipart field has an unexpected type. + */ + fun _checks(): MultipartField = body._checks() + + /** + * Returns the raw multipart value of [customCoordinates]. + * + * Unlike [customCoordinates], this method doesn't throw if the multipart field has an + * unexpected type. + */ + fun _customCoordinates(): MultipartField = body._customCoordinates() + + /** + * Returns the raw multipart value of [customMetadata]. + * + * Unlike [customMetadata], this method doesn't throw if the multipart field has an unexpected + * type. + */ + fun _customMetadata(): MultipartField = body._customMetadata() + + /** + * Returns the raw multipart value of [description]. + * + * Unlike [description], this method doesn't throw if the multipart field has an unexpected + * type. + */ + fun _description(): MultipartField = body._description() + + /** + * Returns the raw multipart value of [extensions]. + * + * Unlike [extensions], this method doesn't throw if the multipart field has an unexpected type. + */ + fun _extensions(): MultipartField> = body._extensions() + + /** + * Returns the raw multipart value of [folder]. + * + * Unlike [folder], this method doesn't throw if the multipart field has an unexpected type. + */ + fun _folder(): MultipartField = body._folder() + + /** + * Returns the raw multipart value of [isPrivateFile]. + * + * Unlike [isPrivateFile], this method doesn't throw if the multipart field has an unexpected + * type. + */ + fun _isPrivateFile(): MultipartField = body._isPrivateFile() + + /** + * Returns the raw multipart value of [isPublished]. + * + * Unlike [isPublished], this method doesn't throw if the multipart field has an unexpected + * type. + */ + fun _isPublished(): MultipartField = body._isPublished() + + /** + * Returns the raw multipart value of [overwriteAiTags]. + * + * Unlike [overwriteAiTags], this method doesn't throw if the multipart field has an unexpected + * type. + */ + fun _overwriteAiTags(): MultipartField = body._overwriteAiTags() + + /** + * Returns the raw multipart value of [overwriteCustomMetadata]. + * + * Unlike [overwriteCustomMetadata], this method doesn't throw if the multipart field has an + * unexpected type. + */ + fun _overwriteCustomMetadata(): MultipartField = body._overwriteCustomMetadata() + + /** + * Returns the raw multipart value of [overwriteFile]. + * + * Unlike [overwriteFile], this method doesn't throw if the multipart field has an unexpected + * type. + */ + fun _overwriteFile(): MultipartField = body._overwriteFile() + + /** + * Returns the raw multipart value of [overwriteTags]. + * + * Unlike [overwriteTags], this method doesn't throw if the multipart field has an unexpected + * type. + */ + fun _overwriteTags(): MultipartField = body._overwriteTags() + + /** + * Returns the raw multipart value of [responseFields]. + * + * Unlike [responseFields], this method doesn't throw if the multipart field has an unexpected + * type. + */ + fun _responseFields(): MultipartField> = body._responseFields() + + /** + * Returns the raw multipart value of [tags]. + * + * Unlike [tags], this method doesn't throw if the multipart field has an unexpected type. + */ + fun _tags(): MultipartField> = body._tags() + + /** + * Returns the raw multipart value of [transformation]. + * + * Unlike [transformation], this method doesn't throw if the multipart field has an unexpected + * type. + */ + fun _transformation(): MultipartField = body._transformation() + + /** + * Returns the raw multipart value of [useUniqueFileName]. + * + * Unlike [useUniqueFileName], this method doesn't throw if the multipart field has an + * unexpected type. + */ + fun _useUniqueFileName(): MultipartField = body._useUniqueFileName() + + /** + * Returns the raw multipart value of [webhookUrl]. + * + * Unlike [webhookUrl], this method doesn't throw if the multipart field has an unexpected type. + */ + fun _webhookUrl(): MultipartField = body._webhookUrl() + + fun _additionalBodyProperties(): Map = body._additionalProperties() + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [FileUploadParams]. + * + * The following fields are required: + * ```java + * .file() + * .fileName() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [FileUploadParams]. */ + class Builder internal constructor() { + + private var body: Body.Builder = Body.builder() + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + + @JvmSynthetic + internal fun from(fileUploadParams: FileUploadParams) = apply { + body = fileUploadParams.body.toBuilder() + additionalHeaders = fileUploadParams.additionalHeaders.toBuilder() + additionalQueryParams = fileUploadParams.additionalQueryParams.toBuilder() + } + + /** + * Sets the entire request body. + * + * This is generally only useful if you are already constructing the body separately. + * Otherwise, it's more convenient to use the top-level setters instead: + * - [file] + * - [fileName] + * - [token] + * - [checks] + * - [customCoordinates] + * - etc. + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } + + /** + * The API accepts any of the following: + * - **Binary data** – send the raw bytes as `multipart/form-data`. + * - **HTTP / HTTPS URL** – a publicly reachable URL that ImageKit’s servers can fetch. + * - **Base64 string** – the file encoded as a Base64 data URI or plain Base64. + * + * When supplying a URL, the server must receive the response headers within 8 seconds; + * otherwise the request fails with 400 Bad Request. + */ + fun file(file: InputStream) = apply { body.file(file) } + + /** + * Sets [Builder.file] to an arbitrary multipart value. + * + * You should usually call [Builder.file] with a well-typed [InputStream] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun file(file: MultipartField) = apply { body.file(file) } + + /** + * The API accepts any of the following: + * - **Binary data** – send the raw bytes as `multipart/form-data`. + * - **HTTP / HTTPS URL** – a publicly reachable URL that ImageKit’s servers can fetch. + * - **Base64 string** – the file encoded as a Base64 data URI or plain Base64. + * + * When supplying a URL, the server must receive the response headers within 8 seconds; + * otherwise the request fails with 400 Bad Request. + */ + fun file(file: ByteArray) = apply { body.file(file) } + + /** + * The API accepts any of the following: + * - **Binary data** – send the raw bytes as `multipart/form-data`. + * - **HTTP / HTTPS URL** – a publicly reachable URL that ImageKit’s servers can fetch. + * - **Base64 string** – the file encoded as a Base64 data URI or plain Base64. + * + * When supplying a URL, the server must receive the response headers within 8 seconds; + * otherwise the request fails with 400 Bad Request. + */ + fun file(path: Path) = apply { body.file(path) } + + /** The name with which the file has to be uploaded. */ + fun fileName(fileName: String) = apply { body.fileName(fileName) } + + /** + * Sets [Builder.fileName] to an arbitrary multipart value. + * + * You should usually call [Builder.fileName] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun fileName(fileName: MultipartField) = apply { body.fileName(fileName) } + + /** + * This is the client-generated JSON Web Token (JWT). The ImageKit.io server uses it to + * authenticate and check that the upload request parameters have not been tampered with + * after the token has been generated. Learn how to create the token on the page below. This + * field is only required for authentication when uploading a file from the client side. + * + * **Note**: Sending a JWT that has been used in the past will result in a validation error. + * Even if your previous request resulted in an error, you should always send a new token. + * + * **⚠️Warning**: JWT must be generated on the server-side because it is generated using + * your account's private API key. This field is required for authentication when uploading + * a file from the client-side. + */ + fun token(token: String) = apply { body.token(token) } + + /** + * Sets [Builder.token] to an arbitrary multipart value. + * + * You should usually call [Builder.token] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun token(token: MultipartField) = apply { body.token(token) } + + /** + * Server-side checks to run on the asset. Read more about + * [Upload API checks](/docs/api-reference/upload-file/upload-file-v2#upload-api-checks). + */ + fun checks(checks: String) = apply { body.checks(checks) } + + /** + * Sets [Builder.checks] to an arbitrary multipart value. + * + * You should usually call [Builder.checks] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun checks(checks: MultipartField) = apply { body.checks(checks) } + + /** + * Define an important area in the image. This is only relevant for image type files. + * - To be passed as a string with the x and y coordinates of the top-left corner, and width + * and height of the area of interest in the format `x,y,width,height`. For example - + * `10,10,100,100` + * - Can be used with fo-customtransformation. + * - If this field is not specified and the file is overwritten, then customCoordinates will + * be removed. + */ + fun customCoordinates(customCoordinates: String) = apply { + body.customCoordinates(customCoordinates) + } + + /** + * Sets [Builder.customCoordinates] to an arbitrary multipart value. + * + * You should usually call [Builder.customCoordinates] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun customCoordinates(customCoordinates: MultipartField) = apply { + body.customCoordinates(customCoordinates) + } + + /** + * JSON key-value pairs to associate with the asset. Create the custom metadata fields + * before setting these values. + */ + fun customMetadata(customMetadata: CustomMetadata) = apply { + body.customMetadata(customMetadata) + } + + /** + * Sets [Builder.customMetadata] to an arbitrary multipart value. + * + * You should usually call [Builder.customMetadata] with a well-typed [CustomMetadata] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun customMetadata(customMetadata: MultipartField) = apply { + body.customMetadata(customMetadata) + } + + /** Optional text to describe the contents of the file. */ + fun description(description: String) = apply { body.description(description) } + + /** + * Sets [Builder.description] to an arbitrary multipart value. + * + * You should usually call [Builder.description] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun description(description: MultipartField) = apply { + body.description(description) + } + + /** + * Array of extensions to be applied to the asset. Each extension can be configured with + * specific parameters based on the extension type. + */ + fun extensions(extensions: List) = apply { + body.extensions(extensions) + } + + /** + * Sets [Builder.extensions] to an arbitrary multipart value. + * + * You should usually call [Builder.extensions] with a well-typed + * `List` value instead. This method is primarily for setting + * the field to an undocumented or not yet supported value. + */ + fun extensions(extensions: MultipartField>) = apply { + body.extensions(extensions) + } + + /** + * Adds a single [UnnamedSchemaWithArrayParent3] to [extensions]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addExtension(extension: UnnamedSchemaWithArrayParent3) = apply { + body.addExtension(extension) + } + + /** + * Alias for calling [addExtension] with + * `UnnamedSchemaWithArrayParent3.ofRemoveBg(removeBg)`. + */ + fun addExtension(removeBg: UnnamedSchemaWithArrayParent3.RemoveBg) = apply { + body.addExtension(removeBg) + } + + /** + * Alias for calling [addExtension] with + * `UnnamedSchemaWithArrayParent3.ofAutoTaggingExtension(autoTaggingExtension)`. + */ + fun addExtension(autoTaggingExtension: UnnamedSchemaWithArrayParent3.AutoTaggingExtension) = + apply { + body.addExtension(autoTaggingExtension) + } + + /** + * Alias for calling [addExtension] with + * `UnnamedSchemaWithArrayParent3.ofAiAutoDescription()`. + */ + fun addExtensionAiAutoDescription() = apply { body.addExtensionAiAutoDescription() } + + /** + * The folder path in which the image has to be uploaded. If the folder(s) didn't exist + * before, a new folder(s) is created. Using multiple `/` creates a nested folder. + */ + fun folder(folder: String) = apply { body.folder(folder) } + + /** + * Sets [Builder.folder] to an arbitrary multipart value. + * + * You should usually call [Builder.folder] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun folder(folder: MultipartField) = apply { body.folder(folder) } + + /** + * Whether to mark the file as private or not. + * + * If `true`, the file is marked as private and is accessible only using named + * transformation or signed URL. + */ + fun isPrivateFile(isPrivateFile: Boolean) = apply { body.isPrivateFile(isPrivateFile) } + + /** + * Sets [Builder.isPrivateFile] to an arbitrary multipart value. + * + * You should usually call [Builder.isPrivateFile] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun isPrivateFile(isPrivateFile: MultipartField) = apply { + body.isPrivateFile(isPrivateFile) + } + + /** + * Whether to upload file as published or not. + * + * If `false`, the file is marked as unpublished, which restricts access to the file only + * via the media library. Files in draft or unpublished state can only be publicly accessed + * after being published. + * + * The option to upload in draft state is only available in custom enterprise pricing plans. + */ + fun isPublished(isPublished: Boolean) = apply { body.isPublished(isPublished) } + + /** + * Sets [Builder.isPublished] to an arbitrary multipart value. + * + * You should usually call [Builder.isPublished] with a well-typed [Boolean] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun isPublished(isPublished: MultipartField) = apply { + body.isPublished(isPublished) + } + + /** + * If set to `true` and a file already exists at the exact location, its AITags will be + * removed. Set `overwriteAITags` to `false` to preserve AITags. + */ + fun overwriteAiTags(overwriteAiTags: Boolean) = apply { + body.overwriteAiTags(overwriteAiTags) + } + + /** + * Sets [Builder.overwriteAiTags] to an arbitrary multipart value. + * + * You should usually call [Builder.overwriteAiTags] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun overwriteAiTags(overwriteAiTags: MultipartField) = apply { + body.overwriteAiTags(overwriteAiTags) + } + + /** + * If the request does not have `customMetadata`, and a file already exists at the exact + * location, existing customMetadata will be removed. + */ + fun overwriteCustomMetadata(overwriteCustomMetadata: Boolean) = apply { + body.overwriteCustomMetadata(overwriteCustomMetadata) + } + + /** + * Sets [Builder.overwriteCustomMetadata] to an arbitrary multipart value. + * + * You should usually call [Builder.overwriteCustomMetadata] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun overwriteCustomMetadata(overwriteCustomMetadata: MultipartField) = apply { + body.overwriteCustomMetadata(overwriteCustomMetadata) + } + + /** + * If `false` and `useUniqueFileName` is also `false`, and a file already exists at the + * exact location, upload API will return an error immediately. + */ + fun overwriteFile(overwriteFile: Boolean) = apply { body.overwriteFile(overwriteFile) } + + /** + * Sets [Builder.overwriteFile] to an arbitrary multipart value. + * + * You should usually call [Builder.overwriteFile] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun overwriteFile(overwriteFile: MultipartField) = apply { + body.overwriteFile(overwriteFile) + } + + /** + * If the request does not have `tags`, and a file already exists at the exact location, + * existing tags will be removed. + */ + fun overwriteTags(overwriteTags: Boolean) = apply { body.overwriteTags(overwriteTags) } + + /** + * Sets [Builder.overwriteTags] to an arbitrary multipart value. + * + * You should usually call [Builder.overwriteTags] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun overwriteTags(overwriteTags: MultipartField) = apply { + body.overwriteTags(overwriteTags) + } + + /** Array of response field keys to include in the API response body. */ + fun responseFields(responseFields: List) = apply { + body.responseFields(responseFields) + } + + /** + * Sets [Builder.responseFields] to an arbitrary multipart value. + * + * You should usually call [Builder.responseFields] with a well-typed `List` + * value instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun responseFields(responseFields: MultipartField>) = apply { + body.responseFields(responseFields) + } + + /** + * Adds a single [ResponseField] to [responseFields]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addResponseField(responseField: ResponseField) = apply { + body.addResponseField(responseField) + } + + /** + * Set the tags while uploading the file. Provide an array of tag strings (e.g. `["tag1", + * "tag2", "tag3"]`). The combined length of all tag characters must not exceed 500, and the + * `%` character is not allowed. If this field is not specified and the file is overwritten, + * the existing tags will be removed. + */ + fun tags(tags: List) = apply { body.tags(tags) } + + /** + * Sets [Builder.tags] to an arbitrary multipart value. + * + * You should usually call [Builder.tags] with a well-typed `List` value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun tags(tags: MultipartField>) = apply { body.tags(tags) } + + /** + * Adds a single [String] to [tags]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addTag(tag: String) = apply { body.addTag(tag) } + + /** + * Configure pre-processing (`pre`) and post-processing (`post`) transformations. + * - `pre` — applied before the file is uploaded to the Media Library. Useful for reducing + * file size or applying basic optimizations upfront (e.g., resize, compress). + * - `post` — applied immediately after upload. Ideal for generating transformed versions + * (like video encodes or thumbnails) in advance, so they're ready for delivery without + * delay. + * + * You can mix and match any combination of post-processing types. + */ + fun transformation(transformation: Transformation) = apply { + body.transformation(transformation) + } + + /** + * Sets [Builder.transformation] to an arbitrary multipart value. + * + * You should usually call [Builder.transformation] with a well-typed [Transformation] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun transformation(transformation: MultipartField) = apply { + body.transformation(transformation) + } + + /** + * Whether to use a unique filename for this file or not. + * + * If `true`, ImageKit.io will add a unique suffix to the filename parameter to get a unique + * filename. + * + * If `false`, then the image is uploaded with the provided filename parameter, and any + * existing file with the same name is replaced. + */ + fun useUniqueFileName(useUniqueFileName: Boolean) = apply { + body.useUniqueFileName(useUniqueFileName) + } + + /** + * Sets [Builder.useUniqueFileName] to an arbitrary multipart value. + * + * You should usually call [Builder.useUniqueFileName] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun useUniqueFileName(useUniqueFileName: MultipartField) = apply { + body.useUniqueFileName(useUniqueFileName) + } + + /** + * The final status of extensions after they have completed execution will be delivered to + * this endpoint as a POST request. + * [Learn more](/docs/api-reference/digital-asset-management-dam/managing-assets/update-file-details#webhook-payload-structure) + * about the webhook payload structure. + */ + fun webhookUrl(webhookUrl: String) = apply { body.webhookUrl(webhookUrl) } + + /** + * Sets [Builder.webhookUrl] to an arbitrary multipart value. + * + * You should usually call [Builder.webhookUrl] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun webhookUrl(webhookUrl: MultipartField) = apply { body.webhookUrl(webhookUrl) } + + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + body.additionalProperties(additionalBodyProperties) + } + + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + body.putAdditionalProperty(key, value) + } + + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + body.putAllAdditionalProperties(additionalBodyProperties) + } + + fun removeAdditionalBodyProperty(key: String) = apply { body.removeAdditionalProperty(key) } + + fun removeAllAdditionalBodyProperties(keys: Set) = apply { + body.removeAllAdditionalProperties(keys) + } + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + /** + * Returns an immutable instance of [FileUploadParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .file() + * .fileName() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): FileUploadParams = + FileUploadParams(body.build(), additionalHeaders.build(), additionalQueryParams.build()) + } + + fun _body(): Map> = + (mapOf( + "file" to _file(), + "fileName" to _fileName(), + "token" to _token(), + "checks" to _checks(), + "customCoordinates" to _customCoordinates(), + "customMetadata" to _customMetadata(), + "description" to _description(), + "extensions" to _extensions(), + "folder" to _folder(), + "isPrivateFile" to _isPrivateFile(), + "isPublished" to _isPublished(), + "overwriteAITags" to _overwriteAiTags(), + "overwriteCustomMetadata" to _overwriteCustomMetadata(), + "overwriteFile" to _overwriteFile(), + "overwriteTags" to _overwriteTags(), + "responseFields" to _responseFields(), + "tags" to _tags(), + "transformation" to _transformation(), + "useUniqueFileName" to _useUniqueFileName(), + "webhookUrl" to _webhookUrl(), + ) + _additionalBodyProperties().mapValues { (_, value) -> MultipartField.of(value) }) + .toImmutable() + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + class Body + private constructor( + private val file: MultipartField, + private val fileName: MultipartField, + private val token: MultipartField, + private val checks: MultipartField, + private val customCoordinates: MultipartField, + private val customMetadata: MultipartField, + private val description: MultipartField, + private val extensions: MultipartField>, + private val folder: MultipartField, + private val isPrivateFile: MultipartField, + private val isPublished: MultipartField, + private val overwriteAiTags: MultipartField, + private val overwriteCustomMetadata: MultipartField, + private val overwriteFile: MultipartField, + private val overwriteTags: MultipartField, + private val responseFields: MultipartField>, + private val tags: MultipartField>, + private val transformation: MultipartField, + private val useUniqueFileName: MultipartField, + private val webhookUrl: MultipartField, + private val additionalProperties: MutableMap, + ) { + + /** + * The API accepts any of the following: + * - **Binary data** – send the raw bytes as `multipart/form-data`. + * - **HTTP / HTTPS URL** – a publicly reachable URL that ImageKit’s servers can fetch. + * - **Base64 string** – the file encoded as a Base64 data URI or plain Base64. + * + * When supplying a URL, the server must receive the response headers within 8 seconds; + * otherwise the request fails with 400 Bad Request. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun file(): InputStream = file.value.getRequired("file") + + /** + * The name with which the file has to be uploaded. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun fileName(): String = fileName.value.getRequired("fileName") + + /** + * This is the client-generated JSON Web Token (JWT). The ImageKit.io server uses it to + * authenticate and check that the upload request parameters have not been tampered with + * after the token has been generated. Learn how to create the token on the page below. This + * field is only required for authentication when uploading a file from the client side. + * + * **Note**: Sending a JWT that has been used in the past will result in a validation error. + * Even if your previous request resulted in an error, you should always send a new token. + * + * **⚠️Warning**: JWT must be generated on the server-side because it is generated using + * your account's private API key. This field is required for authentication when uploading + * a file from the client-side. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun token(): Optional = token.value.getOptional("token") + + /** + * Server-side checks to run on the asset. Read more about + * [Upload API checks](/docs/api-reference/upload-file/upload-file-v2#upload-api-checks). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun checks(): Optional = checks.value.getOptional("checks") + + /** + * Define an important area in the image. This is only relevant for image type files. + * - To be passed as a string with the x and y coordinates of the top-left corner, and width + * and height of the area of interest in the format `x,y,width,height`. For example - + * `10,10,100,100` + * - Can be used with fo-customtransformation. + * - If this field is not specified and the file is overwritten, then customCoordinates will + * be removed. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun customCoordinates(): Optional = + customCoordinates.value.getOptional("customCoordinates") + + /** + * JSON key-value pairs to associate with the asset. Create the custom metadata fields + * before setting these values. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun customMetadata(): Optional = + customMetadata.value.getOptional("customMetadata") + + /** + * Optional text to describe the contents of the file. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun description(): Optional = description.value.getOptional("description") + + /** + * Array of extensions to be applied to the asset. Each extension can be configured with + * specific parameters based on the extension type. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun extensions(): Optional> = + extensions.value.getOptional("extensions") + + /** + * The folder path in which the image has to be uploaded. If the folder(s) didn't exist + * before, a new folder(s) is created. Using multiple `/` creates a nested folder. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun folder(): Optional = folder.value.getOptional("folder") + + /** + * Whether to mark the file as private or not. + * + * If `true`, the file is marked as private and is accessible only using named + * transformation or signed URL. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun isPrivateFile(): Optional = isPrivateFile.value.getOptional("isPrivateFile") + + /** + * Whether to upload file as published or not. + * + * If `false`, the file is marked as unpublished, which restricts access to the file only + * via the media library. Files in draft or unpublished state can only be publicly accessed + * after being published. + * + * The option to upload in draft state is only available in custom enterprise pricing plans. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun isPublished(): Optional = isPublished.value.getOptional("isPublished") + + /** + * If set to `true` and a file already exists at the exact location, its AITags will be + * removed. Set `overwriteAITags` to `false` to preserve AITags. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun overwriteAiTags(): Optional = + overwriteAiTags.value.getOptional("overwriteAITags") + + /** + * If the request does not have `customMetadata`, and a file already exists at the exact + * location, existing customMetadata will be removed. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun overwriteCustomMetadata(): Optional = + overwriteCustomMetadata.value.getOptional("overwriteCustomMetadata") + + /** + * If `false` and `useUniqueFileName` is also `false`, and a file already exists at the + * exact location, upload API will return an error immediately. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun overwriteFile(): Optional = overwriteFile.value.getOptional("overwriteFile") + + /** + * If the request does not have `tags`, and a file already exists at the exact location, + * existing tags will be removed. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun overwriteTags(): Optional = overwriteTags.value.getOptional("overwriteTags") + + /** + * Array of response field keys to include in the API response body. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun responseFields(): Optional> = + responseFields.value.getOptional("responseFields") + + /** + * Set the tags while uploading the file. Provide an array of tag strings (e.g. `["tag1", + * "tag2", "tag3"]`). The combined length of all tag characters must not exceed 500, and the + * `%` character is not allowed. If this field is not specified and the file is overwritten, + * the existing tags will be removed. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun tags(): Optional> = tags.value.getOptional("tags") + + /** + * Configure pre-processing (`pre`) and post-processing (`post`) transformations. + * - `pre` — applied before the file is uploaded to the Media Library. Useful for reducing + * file size or applying basic optimizations upfront (e.g., resize, compress). + * - `post` — applied immediately after upload. Ideal for generating transformed versions + * (like video encodes or thumbnails) in advance, so they're ready for delivery without + * delay. + * + * You can mix and match any combination of post-processing types. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun transformation(): Optional = + transformation.value.getOptional("transformation") + + /** + * Whether to use a unique filename for this file or not. + * + * If `true`, ImageKit.io will add a unique suffix to the filename parameter to get a unique + * filename. + * + * If `false`, then the image is uploaded with the provided filename parameter, and any + * existing file with the same name is replaced. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun useUniqueFileName(): Optional = + useUniqueFileName.value.getOptional("useUniqueFileName") + + /** + * The final status of extensions after they have completed execution will be delivered to + * this endpoint as a POST request. + * [Learn more](/docs/api-reference/digital-asset-management-dam/managing-assets/update-file-details#webhook-payload-structure) + * about the webhook payload structure. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun webhookUrl(): Optional = webhookUrl.value.getOptional("webhookUrl") + + /** + * Returns the raw multipart value of [file]. + * + * Unlike [file], this method doesn't throw if the multipart field has an unexpected type. + */ + @JsonProperty("file") @ExcludeMissing fun _file(): MultipartField = file + + /** + * Returns the raw multipart value of [fileName]. + * + * Unlike [fileName], this method doesn't throw if the multipart field has an unexpected + * type. + */ + @JsonProperty("fileName") @ExcludeMissing fun _fileName(): MultipartField = fileName + + /** + * Returns the raw multipart value of [token]. + * + * Unlike [token], this method doesn't throw if the multipart field has an unexpected type. + */ + @JsonProperty("token") @ExcludeMissing fun _token(): MultipartField = token + + /** + * Returns the raw multipart value of [checks]. + * + * Unlike [checks], this method doesn't throw if the multipart field has an unexpected type. + */ + @JsonProperty("checks") @ExcludeMissing fun _checks(): MultipartField = checks + + /** + * Returns the raw multipart value of [customCoordinates]. + * + * Unlike [customCoordinates], this method doesn't throw if the multipart field has an + * unexpected type. + */ + @JsonProperty("customCoordinates") + @ExcludeMissing + fun _customCoordinates(): MultipartField = customCoordinates + + /** + * Returns the raw multipart value of [customMetadata]. + * + * Unlike [customMetadata], this method doesn't throw if the multipart field has an + * unexpected type. + */ + @JsonProperty("customMetadata") + @ExcludeMissing + fun _customMetadata(): MultipartField = customMetadata + + /** + * Returns the raw multipart value of [description]. + * + * Unlike [description], this method doesn't throw if the multipart field has an unexpected + * type. + */ + @JsonProperty("description") + @ExcludeMissing + fun _description(): MultipartField = description + + /** + * Returns the raw multipart value of [extensions]. + * + * Unlike [extensions], this method doesn't throw if the multipart field has an unexpected + * type. + */ + @JsonProperty("extensions") + @ExcludeMissing + fun _extensions(): MultipartField> = extensions + + /** + * Returns the raw multipart value of [folder]. + * + * Unlike [folder], this method doesn't throw if the multipart field has an unexpected type. + */ + @JsonProperty("folder") @ExcludeMissing fun _folder(): MultipartField = folder + + /** + * Returns the raw multipart value of [isPrivateFile]. + * + * Unlike [isPrivateFile], this method doesn't throw if the multipart field has an + * unexpected type. + */ + @JsonProperty("isPrivateFile") + @ExcludeMissing + fun _isPrivateFile(): MultipartField = isPrivateFile + + /** + * Returns the raw multipart value of [isPublished]. + * + * Unlike [isPublished], this method doesn't throw if the multipart field has an unexpected + * type. + */ + @JsonProperty("isPublished") + @ExcludeMissing + fun _isPublished(): MultipartField = isPublished + + /** + * Returns the raw multipart value of [overwriteAiTags]. + * + * Unlike [overwriteAiTags], this method doesn't throw if the multipart field has an + * unexpected type. + */ + @JsonProperty("overwriteAITags") + @ExcludeMissing + fun _overwriteAiTags(): MultipartField = overwriteAiTags + + /** + * Returns the raw multipart value of [overwriteCustomMetadata]. + * + * Unlike [overwriteCustomMetadata], this method doesn't throw if the multipart field has an + * unexpected type. + */ + @JsonProperty("overwriteCustomMetadata") + @ExcludeMissing + fun _overwriteCustomMetadata(): MultipartField = overwriteCustomMetadata + + /** + * Returns the raw multipart value of [overwriteFile]. + * + * Unlike [overwriteFile], this method doesn't throw if the multipart field has an + * unexpected type. + */ + @JsonProperty("overwriteFile") + @ExcludeMissing + fun _overwriteFile(): MultipartField = overwriteFile + + /** + * Returns the raw multipart value of [overwriteTags]. + * + * Unlike [overwriteTags], this method doesn't throw if the multipart field has an + * unexpected type. + */ + @JsonProperty("overwriteTags") + @ExcludeMissing + fun _overwriteTags(): MultipartField = overwriteTags + + /** + * Returns the raw multipart value of [responseFields]. + * + * Unlike [responseFields], this method doesn't throw if the multipart field has an + * unexpected type. + */ + @JsonProperty("responseFields") + @ExcludeMissing + fun _responseFields(): MultipartField> = responseFields + + /** + * Returns the raw multipart value of [tags]. + * + * Unlike [tags], this method doesn't throw if the multipart field has an unexpected type. + */ + @JsonProperty("tags") @ExcludeMissing fun _tags(): MultipartField> = tags + + /** + * Returns the raw multipart value of [transformation]. + * + * Unlike [transformation], this method doesn't throw if the multipart field has an + * unexpected type. + */ + @JsonProperty("transformation") + @ExcludeMissing + fun _transformation(): MultipartField = transformation + + /** + * Returns the raw multipart value of [useUniqueFileName]. + * + * Unlike [useUniqueFileName], this method doesn't throw if the multipart field has an + * unexpected type. + */ + @JsonProperty("useUniqueFileName") + @ExcludeMissing + fun _useUniqueFileName(): MultipartField = useUniqueFileName + + /** + * Returns the raw multipart value of [webhookUrl]. + * + * Unlike [webhookUrl], this method doesn't throw if the multipart field has an unexpected + * type. + */ + @JsonProperty("webhookUrl") + @ExcludeMissing + fun _webhookUrl(): MultipartField = webhookUrl + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Body]. + * + * The following fields are required: + * ```java + * .file() + * .fileName() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Body]. */ + class Builder internal constructor() { + + private var file: MultipartField? = null + private var fileName: MultipartField? = null + private var token: MultipartField = MultipartField.of(null) + private var checks: MultipartField = MultipartField.of(null) + private var customCoordinates: MultipartField = MultipartField.of(null) + private var customMetadata: MultipartField = MultipartField.of(null) + private var description: MultipartField = MultipartField.of(null) + private var extensions: MultipartField>? = + null + private var folder: MultipartField = MultipartField.of(null) + private var isPrivateFile: MultipartField = MultipartField.of(null) + private var isPublished: MultipartField = MultipartField.of(null) + private var overwriteAiTags: MultipartField = MultipartField.of(null) + private var overwriteCustomMetadata: MultipartField = MultipartField.of(null) + private var overwriteFile: MultipartField = MultipartField.of(null) + private var overwriteTags: MultipartField = MultipartField.of(null) + private var responseFields: MultipartField>? = null + private var tags: MultipartField>? = null + private var transformation: MultipartField = MultipartField.of(null) + private var useUniqueFileName: MultipartField = MultipartField.of(null) + private var webhookUrl: MultipartField = MultipartField.of(null) + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(body: Body) = apply { + file = body.file + fileName = body.fileName + token = body.token + checks = body.checks + customCoordinates = body.customCoordinates + customMetadata = body.customMetadata + description = body.description + extensions = body.extensions.map { it.toMutableList() } + folder = body.folder + isPrivateFile = body.isPrivateFile + isPublished = body.isPublished + overwriteAiTags = body.overwriteAiTags + overwriteCustomMetadata = body.overwriteCustomMetadata + overwriteFile = body.overwriteFile + overwriteTags = body.overwriteTags + responseFields = body.responseFields.map { it.toMutableList() } + tags = body.tags.map { it.toMutableList() } + transformation = body.transformation + useUniqueFileName = body.useUniqueFileName + webhookUrl = body.webhookUrl + additionalProperties = body.additionalProperties.toMutableMap() + } + + /** + * The API accepts any of the following: + * - **Binary data** – send the raw bytes as `multipart/form-data`. + * - **HTTP / HTTPS URL** – a publicly reachable URL that ImageKit’s servers can fetch. + * - **Base64 string** – the file encoded as a Base64 data URI or plain Base64. + * + * When supplying a URL, the server must receive the response headers within 8 seconds; + * otherwise the request fails with 400 Bad Request. + */ + fun file(file: InputStream) = file(MultipartField.of(file)) + + /** + * Sets [Builder.file] to an arbitrary multipart value. + * + * You should usually call [Builder.file] with a well-typed [InputStream] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun file(file: MultipartField) = apply { this.file = file } + + /** + * The API accepts any of the following: + * - **Binary data** – send the raw bytes as `multipart/form-data`. + * - **HTTP / HTTPS URL** – a publicly reachable URL that ImageKit’s servers can fetch. + * - **Base64 string** – the file encoded as a Base64 data URI or plain Base64. + * + * When supplying a URL, the server must receive the response headers within 8 seconds; + * otherwise the request fails with 400 Bad Request. + */ + fun file(file: ByteArray) = file(file.inputStream()) + + /** + * The API accepts any of the following: + * - **Binary data** – send the raw bytes as `multipart/form-data`. + * - **HTTP / HTTPS URL** – a publicly reachable URL that ImageKit’s servers can fetch. + * - **Base64 string** – the file encoded as a Base64 data URI or plain Base64. + * + * When supplying a URL, the server must receive the response headers within 8 seconds; + * otherwise the request fails with 400 Bad Request. + */ + fun file(path: Path) = + file( + MultipartField.builder() + .value(path.inputStream()) + .filename(path.name) + .build() + ) + + /** The name with which the file has to be uploaded. */ + fun fileName(fileName: String) = fileName(MultipartField.of(fileName)) + + /** + * Sets [Builder.fileName] to an arbitrary multipart value. + * + * You should usually call [Builder.fileName] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun fileName(fileName: MultipartField) = apply { this.fileName = fileName } + + /** + * This is the client-generated JSON Web Token (JWT). The ImageKit.io server uses it to + * authenticate and check that the upload request parameters have not been tampered with + * after the token has been generated. Learn how to create the token on the page below. + * This field is only required for authentication when uploading a file from the client + * side. + * + * **Note**: Sending a JWT that has been used in the past will result in a validation + * error. Even if your previous request resulted in an error, you should always send a + * new token. + * + * **⚠️Warning**: JWT must be generated on the server-side because it is generated using + * your account's private API key. This field is required for authentication when + * uploading a file from the client-side. + */ + fun token(token: String) = token(MultipartField.of(token)) + + /** + * Sets [Builder.token] to an arbitrary multipart value. + * + * You should usually call [Builder.token] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun token(token: MultipartField) = apply { this.token = token } + + /** + * Server-side checks to run on the asset. Read more about + * [Upload API checks](/docs/api-reference/upload-file/upload-file-v2#upload-api-checks). + */ + fun checks(checks: String) = checks(MultipartField.of(checks)) + + /** + * Sets [Builder.checks] to an arbitrary multipart value. + * + * You should usually call [Builder.checks] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun checks(checks: MultipartField) = apply { this.checks = checks } + + /** + * Define an important area in the image. This is only relevant for image type files. + * - To be passed as a string with the x and y coordinates of the top-left corner, and + * width and height of the area of interest in the format `x,y,width,height`. For + * example - `10,10,100,100` + * - Can be used with fo-customtransformation. + * - If this field is not specified and the file is overwritten, then customCoordinates + * will be removed. + */ + fun customCoordinates(customCoordinates: String) = + customCoordinates(MultipartField.of(customCoordinates)) + + /** + * Sets [Builder.customCoordinates] to an arbitrary multipart value. + * + * You should usually call [Builder.customCoordinates] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun customCoordinates(customCoordinates: MultipartField) = apply { + this.customCoordinates = customCoordinates + } + + /** + * JSON key-value pairs to associate with the asset. Create the custom metadata fields + * before setting these values. + */ + fun customMetadata(customMetadata: CustomMetadata) = + customMetadata(MultipartField.of(customMetadata)) + + /** + * Sets [Builder.customMetadata] to an arbitrary multipart value. + * + * You should usually call [Builder.customMetadata] with a well-typed [CustomMetadata] + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun customMetadata(customMetadata: MultipartField) = apply { + this.customMetadata = customMetadata + } + + /** Optional text to describe the contents of the file. */ + fun description(description: String) = description(MultipartField.of(description)) + + /** + * Sets [Builder.description] to an arbitrary multipart value. + * + * You should usually call [Builder.description] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun description(description: MultipartField) = apply { + this.description = description + } + + /** + * Array of extensions to be applied to the asset. Each extension can be configured with + * specific parameters based on the extension type. + */ + fun extensions(extensions: List) = + extensions(MultipartField.of(extensions)) + + /** + * Sets [Builder.extensions] to an arbitrary multipart value. + * + * You should usually call [Builder.extensions] with a well-typed + * `List` value instead. This method is primarily for + * setting the field to an undocumented or not yet supported value. + */ + fun extensions(extensions: MultipartField>) = + apply { + this.extensions = extensions.map { it.toMutableList() } + } + + /** + * Adds a single [UnnamedSchemaWithArrayParent3] to [extensions]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addExtension(extension: UnnamedSchemaWithArrayParent3) = apply { + extensions = + (extensions ?: MultipartField.of(mutableListOf())).also { + checkKnown("extensions", it).add(extension) + } + } + + /** + * Alias for calling [addExtension] with + * `UnnamedSchemaWithArrayParent3.ofRemoveBg(removeBg)`. + */ + fun addExtension(removeBg: UnnamedSchemaWithArrayParent3.RemoveBg) = + addExtension(UnnamedSchemaWithArrayParent3.ofRemoveBg(removeBg)) + + /** + * Alias for calling [addExtension] with + * `UnnamedSchemaWithArrayParent3.ofAutoTaggingExtension(autoTaggingExtension)`. + */ + fun addExtension( + autoTaggingExtension: UnnamedSchemaWithArrayParent3.AutoTaggingExtension + ) = + addExtension( + UnnamedSchemaWithArrayParent3.ofAutoTaggingExtension(autoTaggingExtension) + ) + + /** + * Alias for calling [addExtension] with + * `UnnamedSchemaWithArrayParent3.ofAiAutoDescription()`. + */ + fun addExtensionAiAutoDescription() = + addExtension(UnnamedSchemaWithArrayParent3.ofAiAutoDescription()) + + /** + * The folder path in which the image has to be uploaded. If the folder(s) didn't exist + * before, a new folder(s) is created. Using multiple `/` creates a nested folder. + */ + fun folder(folder: String) = folder(MultipartField.of(folder)) + + /** + * Sets [Builder.folder] to an arbitrary multipart value. + * + * You should usually call [Builder.folder] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun folder(folder: MultipartField) = apply { this.folder = folder } + + /** + * Whether to mark the file as private or not. + * + * If `true`, the file is marked as private and is accessible only using named + * transformation or signed URL. + */ + fun isPrivateFile(isPrivateFile: Boolean) = + isPrivateFile(MultipartField.of(isPrivateFile)) + + /** + * Sets [Builder.isPrivateFile] to an arbitrary multipart value. + * + * You should usually call [Builder.isPrivateFile] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun isPrivateFile(isPrivateFile: MultipartField) = apply { + this.isPrivateFile = isPrivateFile + } + + /** + * Whether to upload file as published or not. + * + * If `false`, the file is marked as unpublished, which restricts access to the file + * only via the media library. Files in draft or unpublished state can only be publicly + * accessed after being published. + * + * The option to upload in draft state is only available in custom enterprise pricing + * plans. + */ + fun isPublished(isPublished: Boolean) = isPublished(MultipartField.of(isPublished)) + + /** + * Sets [Builder.isPublished] to an arbitrary multipart value. + * + * You should usually call [Builder.isPublished] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun isPublished(isPublished: MultipartField) = apply { + this.isPublished = isPublished + } + + /** + * If set to `true` and a file already exists at the exact location, its AITags will be + * removed. Set `overwriteAITags` to `false` to preserve AITags. + */ + fun overwriteAiTags(overwriteAiTags: Boolean) = + overwriteAiTags(MultipartField.of(overwriteAiTags)) + + /** + * Sets [Builder.overwriteAiTags] to an arbitrary multipart value. + * + * You should usually call [Builder.overwriteAiTags] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun overwriteAiTags(overwriteAiTags: MultipartField) = apply { + this.overwriteAiTags = overwriteAiTags + } + + /** + * If the request does not have `customMetadata`, and a file already exists at the exact + * location, existing customMetadata will be removed. + */ + fun overwriteCustomMetadata(overwriteCustomMetadata: Boolean) = + overwriteCustomMetadata(MultipartField.of(overwriteCustomMetadata)) + + /** + * Sets [Builder.overwriteCustomMetadata] to an arbitrary multipart value. + * + * You should usually call [Builder.overwriteCustomMetadata] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun overwriteCustomMetadata(overwriteCustomMetadata: MultipartField) = apply { + this.overwriteCustomMetadata = overwriteCustomMetadata + } + + /** + * If `false` and `useUniqueFileName` is also `false`, and a file already exists at the + * exact location, upload API will return an error immediately. + */ + fun overwriteFile(overwriteFile: Boolean) = + overwriteFile(MultipartField.of(overwriteFile)) + + /** + * Sets [Builder.overwriteFile] to an arbitrary multipart value. + * + * You should usually call [Builder.overwriteFile] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun overwriteFile(overwriteFile: MultipartField) = apply { + this.overwriteFile = overwriteFile + } + + /** + * If the request does not have `tags`, and a file already exists at the exact location, + * existing tags will be removed. + */ + fun overwriteTags(overwriteTags: Boolean) = + overwriteTags(MultipartField.of(overwriteTags)) + + /** + * Sets [Builder.overwriteTags] to an arbitrary multipart value. + * + * You should usually call [Builder.overwriteTags] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun overwriteTags(overwriteTags: MultipartField) = apply { + this.overwriteTags = overwriteTags + } + + /** Array of response field keys to include in the API response body. */ + fun responseFields(responseFields: List) = + responseFields(MultipartField.of(responseFields)) + + /** + * Sets [Builder.responseFields] to an arbitrary multipart value. + * + * You should usually call [Builder.responseFields] with a well-typed + * `List` value instead. This method is primarily for setting the field + * to an undocumented or not yet supported value. + */ + fun responseFields(responseFields: MultipartField>) = apply { + this.responseFields = responseFields.map { it.toMutableList() } + } + + /** + * Adds a single [ResponseField] to [responseFields]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addResponseField(responseField: ResponseField) = apply { + responseFields = + (responseFields ?: MultipartField.of(mutableListOf())).also { + checkKnown("responseFields", it).add(responseField) + } + } + + /** + * Set the tags while uploading the file. Provide an array of tag strings (e.g. + * `["tag1", "tag2", "tag3"]`). The combined length of all tag characters must not + * exceed 500, and the `%` character is not allowed. If this field is not specified and + * the file is overwritten, the existing tags will be removed. + */ + fun tags(tags: List) = tags(MultipartField.of(tags)) + + /** + * Sets [Builder.tags] to an arbitrary multipart value. + * + * You should usually call [Builder.tags] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun tags(tags: MultipartField>) = apply { + this.tags = tags.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [tags]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addTag(tag: String) = apply { + tags = + (tags ?: MultipartField.of(mutableListOf())).also { + checkKnown("tags", it).add(tag) + } + } + + /** + * Configure pre-processing (`pre`) and post-processing (`post`) transformations. + * - `pre` — applied before the file is uploaded to the Media Library. Useful for + * reducing file size or applying basic optimizations upfront (e.g., resize, + * compress). + * - `post` — applied immediately after upload. Ideal for generating transformed + * versions (like video encodes or thumbnails) in advance, so they're ready for + * delivery without delay. + * + * You can mix and match any combination of post-processing types. + */ + fun transformation(transformation: Transformation) = + transformation(MultipartField.of(transformation)) + + /** + * Sets [Builder.transformation] to an arbitrary multipart value. + * + * You should usually call [Builder.transformation] with a well-typed [Transformation] + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun transformation(transformation: MultipartField) = apply { + this.transformation = transformation + } + + /** + * Whether to use a unique filename for this file or not. + * + * If `true`, ImageKit.io will add a unique suffix to the filename parameter to get a + * unique filename. + * + * If `false`, then the image is uploaded with the provided filename parameter, and any + * existing file with the same name is replaced. + */ + fun useUniqueFileName(useUniqueFileName: Boolean) = + useUniqueFileName(MultipartField.of(useUniqueFileName)) + + /** + * Sets [Builder.useUniqueFileName] to an arbitrary multipart value. + * + * You should usually call [Builder.useUniqueFileName] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun useUniqueFileName(useUniqueFileName: MultipartField) = apply { + this.useUniqueFileName = useUniqueFileName + } + + /** + * The final status of extensions after they have completed execution will be delivered + * to this endpoint as a POST request. + * [Learn more](/docs/api-reference/digital-asset-management-dam/managing-assets/update-file-details#webhook-payload-structure) + * about the webhook payload structure. + */ + fun webhookUrl(webhookUrl: String) = webhookUrl(MultipartField.of(webhookUrl)) + + /** + * Sets [Builder.webhookUrl] to an arbitrary multipart value. + * + * You should usually call [Builder.webhookUrl] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun webhookUrl(webhookUrl: MultipartField) = apply { + this.webhookUrl = webhookUrl + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Body]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .file() + * .fileName() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Body = + Body( + checkRequired("file", file), + checkRequired("fileName", fileName), + token, + checks, + customCoordinates, + customMetadata, + description, + (extensions ?: MultipartField.of(null)).map { it.toImmutable() }, + folder, + isPrivateFile, + isPublished, + overwriteAiTags, + overwriteCustomMetadata, + overwriteFile, + overwriteTags, + (responseFields ?: MultipartField.of(null)).map { it.toImmutable() }, + (tags ?: MultipartField.of(null)).map { it.toImmutable() }, + transformation, + useUniqueFileName, + webhookUrl, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Body = apply { + if (validated) { + return@apply + } + + file() + fileName() + token() + checks() + customCoordinates() + customMetadata().ifPresent { it.validate() } + description() + extensions().ifPresent { it.forEach { it.validate() } } + folder() + isPrivateFile() + isPublished() + overwriteAiTags() + overwriteCustomMetadata() + overwriteFile() + overwriteTags() + responseFields().ifPresent { it.forEach { it.validate() } } + tags() + transformation().ifPresent { it.validate() } + useUniqueFileName() + webhookUrl() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Body && + file == other.file && + fileName == other.fileName && + token == other.token && + checks == other.checks && + customCoordinates == other.customCoordinates && + customMetadata == other.customMetadata && + description == other.description && + extensions == other.extensions && + folder == other.folder && + isPrivateFile == other.isPrivateFile && + isPublished == other.isPublished && + overwriteAiTags == other.overwriteAiTags && + overwriteCustomMetadata == other.overwriteCustomMetadata && + overwriteFile == other.overwriteFile && + overwriteTags == other.overwriteTags && + responseFields == other.responseFields && + tags == other.tags && + transformation == other.transformation && + useUniqueFileName == other.useUniqueFileName && + webhookUrl == other.webhookUrl && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + file, + fileName, + token, + checks, + customCoordinates, + customMetadata, + description, + extensions, + folder, + isPrivateFile, + isPublished, + overwriteAiTags, + overwriteCustomMetadata, + overwriteFile, + overwriteTags, + responseFields, + tags, + transformation, + useUniqueFileName, + webhookUrl, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Body{file=$file, fileName=$fileName, token=$token, checks=$checks, customCoordinates=$customCoordinates, customMetadata=$customMetadata, description=$description, extensions=$extensions, folder=$folder, isPrivateFile=$isPrivateFile, isPublished=$isPublished, overwriteAiTags=$overwriteAiTags, overwriteCustomMetadata=$overwriteCustomMetadata, overwriteFile=$overwriteFile, overwriteTags=$overwriteTags, responseFields=$responseFields, tags=$tags, transformation=$transformation, useUniqueFileName=$useUniqueFileName, webhookUrl=$webhookUrl, additionalProperties=$additionalProperties}" + } + + /** + * JSON key-value pairs to associate with the asset. Create the custom metadata fields before + * setting these values. + */ + class CustomMetadata + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [CustomMetadata]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [CustomMetadata]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(customMetadata: CustomMetadata) = apply { + additionalProperties = customMetadata.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [CustomMetadata]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): CustomMetadata = CustomMetadata(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): CustomMetadata = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is CustomMetadata && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "CustomMetadata{additionalProperties=$additionalProperties}" + } + + @JsonDeserialize(using = UnnamedSchemaWithArrayParent3.Deserializer::class) + @JsonSerialize(using = UnnamedSchemaWithArrayParent3.Serializer::class) + class UnnamedSchemaWithArrayParent3 + private constructor( + private val removeBg: RemoveBg? = null, + private val autoTaggingExtension: AutoTaggingExtension? = null, + private val aiAutoDescription: JsonValue? = null, + private val _json: JsonValue? = null, + ) { + + fun removeBg(): Optional = Optional.ofNullable(removeBg) + + fun autoTaggingExtension(): Optional = + Optional.ofNullable(autoTaggingExtension) + + fun aiAutoDescription(): Optional = Optional.ofNullable(aiAutoDescription) + + fun isRemoveBg(): Boolean = removeBg != null + + fun isAutoTaggingExtension(): Boolean = autoTaggingExtension != null + + fun isAiAutoDescription(): Boolean = aiAutoDescription != null + + fun asRemoveBg(): RemoveBg = removeBg.getOrThrow("removeBg") + + fun asAutoTaggingExtension(): AutoTaggingExtension = + autoTaggingExtension.getOrThrow("autoTaggingExtension") + + fun asAiAutoDescription(): JsonValue = aiAutoDescription.getOrThrow("aiAutoDescription") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + removeBg != null -> visitor.visitRemoveBg(removeBg) + autoTaggingExtension != null -> + visitor.visitAutoTaggingExtension(autoTaggingExtension) + aiAutoDescription != null -> visitor.visitAiAutoDescription(aiAutoDescription) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): UnnamedSchemaWithArrayParent3 = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitRemoveBg(removeBg: RemoveBg) { + removeBg.validate() + } + + override fun visitAutoTaggingExtension( + autoTaggingExtension: AutoTaggingExtension + ) { + autoTaggingExtension.validate() + } + + override fun visitAiAutoDescription(aiAutoDescription: JsonValue) { + aiAutoDescription.let { + if (it != JsonValue.from(mapOf("name" to "ai-auto-description"))) { + throw ImageKitInvalidDataException( + "'aiAutoDescription' is invalid, received $it" + ) + } + } + } + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitRemoveBg(removeBg: RemoveBg) = removeBg.validity() + + override fun visitAutoTaggingExtension( + autoTaggingExtension: AutoTaggingExtension + ) = autoTaggingExtension.validity() + + override fun visitAiAutoDescription(aiAutoDescription: JsonValue) = + aiAutoDescription.let { + if (it == JsonValue.from(mapOf("name" to "ai-auto-description"))) 1 + else 0 + } + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is UnnamedSchemaWithArrayParent3 && + removeBg == other.removeBg && + autoTaggingExtension == other.autoTaggingExtension && + aiAutoDescription == other.aiAutoDescription + } + + override fun hashCode(): Int = + Objects.hash(removeBg, autoTaggingExtension, aiAutoDescription) + + override fun toString(): String = + when { + removeBg != null -> "UnnamedSchemaWithArrayParent3{removeBg=$removeBg}" + autoTaggingExtension != null -> + "UnnamedSchemaWithArrayParent3{autoTaggingExtension=$autoTaggingExtension}" + aiAutoDescription != null -> + "UnnamedSchemaWithArrayParent3{aiAutoDescription=$aiAutoDescription}" + _json != null -> "UnnamedSchemaWithArrayParent3{_unknown=$_json}" + else -> throw IllegalStateException("Invalid UnnamedSchemaWithArrayParent3") + } + + companion object { + + @JvmStatic + fun ofRemoveBg(removeBg: RemoveBg) = UnnamedSchemaWithArrayParent3(removeBg = removeBg) + + @JvmStatic + fun ofAutoTaggingExtension(autoTaggingExtension: AutoTaggingExtension) = + UnnamedSchemaWithArrayParent3(autoTaggingExtension = autoTaggingExtension) + + @JvmStatic + fun ofAiAutoDescription() = + UnnamedSchemaWithArrayParent3( + aiAutoDescription = JsonValue.from(mapOf("name" to "ai-auto-description")) + ) + } + + /** + * An interface that defines how to map each variant of [UnnamedSchemaWithArrayParent3] to a + * value of type [T]. + */ + interface Visitor { + + fun visitRemoveBg(removeBg: RemoveBg): T + + fun visitAutoTaggingExtension(autoTaggingExtension: AutoTaggingExtension): T + + fun visitAiAutoDescription(aiAutoDescription: JsonValue): T + + /** + * Maps an unknown variant of [UnnamedSchemaWithArrayParent3] to a value of type [T]. + * + * An instance of [UnnamedSchemaWithArrayParent3] can contain an unknown variant if it + * was deserialized from data that doesn't match any known variant. For example, if the + * SDK is on an older version than the API, then the API may respond with new variants + * that the SDK is unaware of. + * + * @throws ImageKitInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw ImageKitInvalidDataException("Unknown UnnamedSchemaWithArrayParent3: $json") + } + } + + internal class Deserializer : + BaseDeserializer(UnnamedSchemaWithArrayParent3::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): UnnamedSchemaWithArrayParent3 { + val json = JsonValue.fromJsonNode(node) + val name = json.asObject().getOrNull()?.get("name")?.asString()?.getOrNull() + + when (name) { + "remove-bg" -> { + return tryDeserialize(node, jacksonTypeRef())?.let { + UnnamedSchemaWithArrayParent3(removeBg = it, _json = json) + } ?: UnnamedSchemaWithArrayParent3(_json = json) + } + "ai-auto-description" -> { + return tryDeserialize(node, jacksonTypeRef()) + ?.let { + UnnamedSchemaWithArrayParent3(aiAutoDescription = it, _json = json) + } + ?.takeIf { it.isValid() } ?: UnnamedSchemaWithArrayParent3(_json = json) + } + } + + return tryDeserialize(node, jacksonTypeRef())?.let { + UnnamedSchemaWithArrayParent3(autoTaggingExtension = it, _json = json) + } ?: UnnamedSchemaWithArrayParent3(_json = json) + } + } + + internal class Serializer : + BaseSerializer(UnnamedSchemaWithArrayParent3::class) { + + override fun serialize( + value: UnnamedSchemaWithArrayParent3, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.removeBg != null -> generator.writeObject(value.removeBg) + value.autoTaggingExtension != null -> + generator.writeObject(value.autoTaggingExtension) + value.aiAutoDescription != null -> + generator.writeObject(value.aiAutoDescription) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid UnnamedSchemaWithArrayParent3") + } + } + } + + class RemoveBg + private constructor( + private val name: JsonValue, + private val options: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("name") @ExcludeMissing name: JsonValue = JsonMissing.of(), + @JsonProperty("options") + @ExcludeMissing + options: JsonField = JsonMissing.of(), + ) : this(name, options, mutableMapOf()) + + /** + * Specifies the background removal extension. + * + * Expected to always return the following: + * ```java + * JsonValue.from("remove-bg") + * ``` + * + * However, this method can be useful for debugging and logging (e.g. if the server + * responded with an unexpected value). + */ + @JsonProperty("name") @ExcludeMissing fun _name(): JsonValue = name + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun options(): Optional = options.getOptional("options") + + /** + * Returns the raw JSON value of [options]. + * + * Unlike [options], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("options") @ExcludeMissing fun _options(): JsonField = options + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [RemoveBg]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [RemoveBg]. */ + class Builder internal constructor() { + + private var name: JsonValue = JsonValue.from("remove-bg") + private var options: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(removeBg: RemoveBg) = apply { + name = removeBg.name + options = removeBg.options + additionalProperties = removeBg.additionalProperties.toMutableMap() + } + + /** + * Sets the field to an arbitrary JSON value. + * + * It is usually unnecessary to call this method because the field defaults to the + * following: + * ```java + * JsonValue.from("remove-bg") + * ``` + * + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun name(name: JsonValue) = apply { this.name = name } + + fun options(options: Options) = options(JsonField.of(options)) + + /** + * Sets [Builder.options] to an arbitrary JSON value. + * + * You should usually call [Builder.options] with a well-typed [Options] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun options(options: JsonField) = apply { this.options = options } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [RemoveBg]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): RemoveBg = RemoveBg(name, options, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): RemoveBg = apply { + if (validated) { + return@apply + } + + _name().let { + if (it != JsonValue.from("remove-bg")) { + throw ImageKitInvalidDataException("'name' is invalid, received $it") + } + } + options().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + name.let { if (it == JsonValue.from("remove-bg")) 1 else 0 } + + (options.asKnown().getOrNull()?.validity() ?: 0) + + class Options + private constructor( + private val addShadow: JsonField, + private val bgColor: JsonField, + private val bgImageUrl: JsonField, + private val semitransparency: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("add_shadow") + @ExcludeMissing + addShadow: JsonField = JsonMissing.of(), + @JsonProperty("bg_color") + @ExcludeMissing + bgColor: JsonField = JsonMissing.of(), + @JsonProperty("bg_image_url") + @ExcludeMissing + bgImageUrl: JsonField = JsonMissing.of(), + @JsonProperty("semitransparency") + @ExcludeMissing + semitransparency: JsonField = JsonMissing.of(), + ) : this(addShadow, bgColor, bgImageUrl, semitransparency, mutableMapOf()) + + /** + * Whether to add an artificial shadow to the result. Default is false. Note: Adding + * shadows is currently only supported for car photos. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun addShadow(): Optional = addShadow.getOptional("add_shadow") + + /** + * Specifies a solid color background using hex code (e.g., "81d4fa", "fff") or + * color name (e.g., "green"). If this parameter is set, `bg_image_url` must be + * empty. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun bgColor(): Optional = bgColor.getOptional("bg_color") + + /** + * Sets a background image from a URL. If this parameter is set, `bg_color` must be + * empty. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun bgImageUrl(): Optional = bgImageUrl.getOptional("bg_image_url") + + /** + * Allows semi-transparent regions in the result. Default is true. Note: + * Semitransparency is currently only supported for car windows. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun semitransparency(): Optional = + semitransparency.getOptional("semitransparency") + + /** + * Returns the raw JSON value of [addShadow]. + * + * Unlike [addShadow], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("add_shadow") + @ExcludeMissing + fun _addShadow(): JsonField = addShadow + + /** + * Returns the raw JSON value of [bgColor]. + * + * Unlike [bgColor], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("bg_color") + @ExcludeMissing + fun _bgColor(): JsonField = bgColor + + /** + * Returns the raw JSON value of [bgImageUrl]. + * + * Unlike [bgImageUrl], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("bg_image_url") + @ExcludeMissing + fun _bgImageUrl(): JsonField = bgImageUrl + + /** + * Returns the raw JSON value of [semitransparency]. + * + * Unlike [semitransparency], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("semitransparency") + @ExcludeMissing + fun _semitransparency(): JsonField = semitransparency + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Options]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Options]. */ + class Builder internal constructor() { + + private var addShadow: JsonField = JsonMissing.of() + private var bgColor: JsonField = JsonMissing.of() + private var bgImageUrl: JsonField = JsonMissing.of() + private var semitransparency: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(options: Options) = apply { + addShadow = options.addShadow + bgColor = options.bgColor + bgImageUrl = options.bgImageUrl + semitransparency = options.semitransparency + additionalProperties = options.additionalProperties.toMutableMap() + } + + /** + * Whether to add an artificial shadow to the result. Default is false. Note: + * Adding shadows is currently only supported for car photos. + */ + fun addShadow(addShadow: Boolean) = addShadow(JsonField.of(addShadow)) + + /** + * Sets [Builder.addShadow] to an arbitrary JSON value. + * + * You should usually call [Builder.addShadow] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun addShadow(addShadow: JsonField) = apply { + this.addShadow = addShadow + } + + /** + * Specifies a solid color background using hex code (e.g., "81d4fa", "fff") or + * color name (e.g., "green"). If this parameter is set, `bg_image_url` must be + * empty. + */ + fun bgColor(bgColor: String) = bgColor(JsonField.of(bgColor)) + + /** + * Sets [Builder.bgColor] to an arbitrary JSON value. + * + * You should usually call [Builder.bgColor] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun bgColor(bgColor: JsonField) = apply { this.bgColor = bgColor } + + /** + * Sets a background image from a URL. If this parameter is set, `bg_color` must + * be empty. + */ + fun bgImageUrl(bgImageUrl: String) = bgImageUrl(JsonField.of(bgImageUrl)) + + /** + * Sets [Builder.bgImageUrl] to an arbitrary JSON value. + * + * You should usually call [Builder.bgImageUrl] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun bgImageUrl(bgImageUrl: JsonField) = apply { + this.bgImageUrl = bgImageUrl + } + + /** + * Allows semi-transparent regions in the result. Default is true. Note: + * Semitransparency is currently only supported for car windows. + */ + fun semitransparency(semitransparency: Boolean) = + semitransparency(JsonField.of(semitransparency)) + + /** + * Sets [Builder.semitransparency] to an arbitrary JSON value. + * + * You should usually call [Builder.semitransparency] with a well-typed + * [Boolean] value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun semitransparency(semitransparency: JsonField) = apply { + this.semitransparency = semitransparency + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Options]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Options = + Options( + addShadow, + bgColor, + bgImageUrl, + semitransparency, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Options = apply { + if (validated) { + return@apply + } + + addShadow() + bgColor() + bgImageUrl() + semitransparency() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (addShadow.asKnown().isPresent) 1 else 0) + + (if (bgColor.asKnown().isPresent) 1 else 0) + + (if (bgImageUrl.asKnown().isPresent) 1 else 0) + + (if (semitransparency.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Options && + addShadow == other.addShadow && + bgColor == other.bgColor && + bgImageUrl == other.bgImageUrl && + semitransparency == other.semitransparency && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + addShadow, + bgColor, + bgImageUrl, + semitransparency, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Options{addShadow=$addShadow, bgColor=$bgColor, bgImageUrl=$bgImageUrl, semitransparency=$semitransparency, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is RemoveBg && + name == other.name && + options == other.options && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(name, options, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "RemoveBg{name=$name, options=$options, additionalProperties=$additionalProperties}" + } + + class AutoTaggingExtension + private constructor( + private val maxTags: JsonField, + private val minConfidence: JsonField, + private val name: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("maxTags") + @ExcludeMissing + maxTags: JsonField = JsonMissing.of(), + @JsonProperty("minConfidence") + @ExcludeMissing + minConfidence: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + ) : this(maxTags, minConfidence, name, mutableMapOf()) + + /** + * Maximum number of tags to attach to the asset. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected + * value). + */ + fun maxTags(): Long = maxTags.getRequired("maxTags") + + /** + * Minimum confidence level for tags to be considered valid. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected + * value). + */ + fun minConfidence(): Long = minConfidence.getRequired("minConfidence") + + /** + * Specifies the auto-tagging extension used. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected + * value). + */ + fun name(): Name = name.getRequired("name") + + /** + * Returns the raw JSON value of [maxTags]. + * + * Unlike [maxTags], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("maxTags") @ExcludeMissing fun _maxTags(): JsonField = maxTags + + /** + * Returns the raw JSON value of [minConfidence]. + * + * Unlike [minConfidence], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("minConfidence") + @ExcludeMissing + fun _minConfidence(): JsonField = minConfidence + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [AutoTaggingExtension]. + * + * The following fields are required: + * ```java + * .maxTags() + * .minConfidence() + * .name() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [AutoTaggingExtension]. */ + class Builder internal constructor() { + + private var maxTags: JsonField? = null + private var minConfidence: JsonField? = null + private var name: JsonField? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(autoTaggingExtension: AutoTaggingExtension) = apply { + maxTags = autoTaggingExtension.maxTags + minConfidence = autoTaggingExtension.minConfidence + name = autoTaggingExtension.name + additionalProperties = autoTaggingExtension.additionalProperties.toMutableMap() + } + + /** Maximum number of tags to attach to the asset. */ + fun maxTags(maxTags: Long) = maxTags(JsonField.of(maxTags)) + + /** + * Sets [Builder.maxTags] to an arbitrary JSON value. + * + * You should usually call [Builder.maxTags] with a well-typed [Long] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun maxTags(maxTags: JsonField) = apply { this.maxTags = maxTags } + + /** Minimum confidence level for tags to be considered valid. */ + fun minConfidence(minConfidence: Long) = minConfidence(JsonField.of(minConfidence)) + + /** + * Sets [Builder.minConfidence] to an arbitrary JSON value. + * + * You should usually call [Builder.minConfidence] with a well-typed [Long] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun minConfidence(minConfidence: JsonField) = apply { + this.minConfidence = minConfidence + } + + /** Specifies the auto-tagging extension used. */ + fun name(name: Name) = name(JsonField.of(name)) + + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [Name] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun name(name: JsonField) = apply { this.name = name } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [AutoTaggingExtension]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .maxTags() + * .minConfidence() + * .name() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): AutoTaggingExtension = + AutoTaggingExtension( + checkRequired("maxTags", maxTags), + checkRequired("minConfidence", minConfidence), + checkRequired("name", name), + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): AutoTaggingExtension = apply { + if (validated) { + return@apply + } + + maxTags() + minConfidence() + name().validate() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (maxTags.asKnown().isPresent) 1 else 0) + + (if (minConfidence.asKnown().isPresent) 1 else 0) + + (name.asKnown().getOrNull()?.validity() ?: 0) + + /** Specifies the auto-tagging extension used. */ + class Name @JsonCreator private constructor(private val value: JsonField) : + Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that + * doesn't match any known member, and you want to know that value. For example, if + * the SDK is on an older version than the API, then the API may respond with new + * members that the SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val GOOGLE_AUTO_TAGGING = of("google-auto-tagging") + + @JvmField val AWS_AUTO_TAGGING = of("aws-auto-tagging") + + @JvmStatic fun of(value: String) = Name(JsonField.of(value)) + } + + /** An enum containing [Name]'s known values. */ + enum class Known { + GOOGLE_AUTO_TAGGING, + AWS_AUTO_TAGGING, + } + + /** + * An enum containing [Name]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [Name] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, + * if the SDK is on an older version than the API, then the API may respond with + * new members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + GOOGLE_AUTO_TAGGING, + AWS_AUTO_TAGGING, + /** + * An enum member indicating that [Name] was instantiated with an unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if + * you want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + GOOGLE_AUTO_TAGGING -> Value.GOOGLE_AUTO_TAGGING + AWS_AUTO_TAGGING -> Value.AWS_AUTO_TAGGING + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and + * don't want to throw for the unknown case. + * + * @throws ImageKitInvalidDataException if this class instance's value is a not a + * known member. + */ + fun known(): Known = + when (this) { + GOOGLE_AUTO_TAGGING -> Known.GOOGLE_AUTO_TAGGING + AWS_AUTO_TAGGING -> Known.AWS_AUTO_TAGGING + else -> throw ImageKitInvalidDataException("Unknown Name: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for + * debugging and generally doesn't throw. + * + * @throws ImageKitInvalidDataException if this class instance's value does not have + * the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + ImageKitInvalidDataException("Value is not a String") + } + + private var validated: Boolean = false + + fun validate(): Name = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Name && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is AutoTaggingExtension && + maxTags == other.maxTags && + minConfidence == other.minConfidence && + name == other.name && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(maxTags, minConfidence, name, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "AutoTaggingExtension{maxTags=$maxTags, minConfidence=$minConfidence, name=$name, additionalProperties=$additionalProperties}" + } + } + + class ResponseField @JsonCreator private constructor(private val value: JsonField) : + Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is on an + * older version than the API, then the API may respond with new members that the SDK is + * unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val TAGS = of("tags") + + @JvmField val CUSTOM_COORDINATES = of("customCoordinates") + + @JvmField val IS_PRIVATE_FILE = of("isPrivateFile") + + @JvmField val EMBEDDED_METADATA = of("embeddedMetadata") + + @JvmField val IS_PUBLISHED = of("isPublished") + + @JvmField val CUSTOM_METADATA = of("customMetadata") + + @JvmField val METADATA = of("metadata") + + @JvmStatic fun of(value: String) = ResponseField(JsonField.of(value)) + } + + /** An enum containing [ResponseField]'s known values. */ + enum class Known { + TAGS, + CUSTOM_COORDINATES, + IS_PRIVATE_FILE, + EMBEDDED_METADATA, + IS_PUBLISHED, + CUSTOM_METADATA, + METADATA, + } + + /** + * An enum containing [ResponseField]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [ResponseField] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if the + * SDK is on an older version than the API, then the API may respond with new members that + * the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + TAGS, + CUSTOM_COORDINATES, + IS_PRIVATE_FILE, + EMBEDDED_METADATA, + IS_PUBLISHED, + CUSTOM_METADATA, + METADATA, + /** + * An enum member indicating that [ResponseField] was instantiated with an unknown + * value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] + * if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you want + * to throw for the unknown case. + */ + fun value(): Value = + when (this) { + TAGS -> Value.TAGS + CUSTOM_COORDINATES -> Value.CUSTOM_COORDINATES + IS_PRIVATE_FILE -> Value.IS_PRIVATE_FILE + EMBEDDED_METADATA -> Value.EMBEDDED_METADATA + IS_PUBLISHED -> Value.IS_PUBLISHED + CUSTOM_METADATA -> Value.CUSTOM_METADATA + METADATA -> Value.METADATA + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and don't + * want to throw for the unknown case. + * + * @throws ImageKitInvalidDataException if this class instance's value is a not a known + * member. + */ + fun known(): Known = + when (this) { + TAGS -> Known.TAGS + CUSTOM_COORDINATES -> Known.CUSTOM_COORDINATES + IS_PRIVATE_FILE -> Known.IS_PRIVATE_FILE + EMBEDDED_METADATA -> Known.EMBEDDED_METADATA + IS_PUBLISHED -> Known.IS_PUBLISHED + CUSTOM_METADATA -> Known.CUSTOM_METADATA + METADATA -> Known.METADATA + else -> throw ImageKitInvalidDataException("Unknown ResponseField: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for debugging + * and generally doesn't throw. + * + * @throws ImageKitInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + ImageKitInvalidDataException("Value is not a String") + } + + private var validated: Boolean = false + + fun validate(): ResponseField = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ResponseField && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + /** + * Configure pre-processing (`pre`) and post-processing (`post`) transformations. + * - `pre` — applied before the file is uploaded to the Media Library. Useful for reducing file + * size or applying basic optimizations upfront (e.g., resize, compress). + * - `post` — applied immediately after upload. Ideal for generating transformed versions (like + * video encodes or thumbnails) in advance, so they're ready for delivery without delay. + * + * You can mix and match any combination of post-processing types. + */ + class Transformation + private constructor( + private val post: MultipartField>, + private val pre: MultipartField, + private val additionalProperties: MutableMap, + ) { + + /** + * List of transformations to apply _after_ the file is uploaded. Each item must match one + * of the following types: `transformation`, `gif-to-video`, `thumbnail`, `abs`. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun post(): Optional> = post.value.getOptional("post") + + /** + * Transformation string to apply before uploading the file to the Media Library. Useful for + * optimizing files at ingestion. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun pre(): Optional = pre.value.getOptional("pre") + + /** + * Returns the raw multipart value of [post]. + * + * Unlike [post], this method doesn't throw if the multipart field has an unexpected type. + */ + @JsonProperty("post") @ExcludeMissing fun _post(): MultipartField> = post + + /** + * Returns the raw multipart value of [pre]. + * + * Unlike [pre], this method doesn't throw if the multipart field has an unexpected type. + */ + @JsonProperty("pre") @ExcludeMissing fun _pre(): MultipartField = pre + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Transformation]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Transformation]. */ + class Builder internal constructor() { + + private var post: MultipartField>? = null + private var pre: MultipartField = MultipartField.of(null) + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(transformation: Transformation) = apply { + post = transformation.post.map { it.toMutableList() } + pre = transformation.pre + additionalProperties = transformation.additionalProperties.toMutableMap() + } + + /** + * List of transformations to apply _after_ the file is uploaded. Each item must match + * one of the following types: `transformation`, `gif-to-video`, `thumbnail`, `abs`. + */ + fun post(post: List) = post(MultipartField.of(post)) + + /** + * Sets [Builder.post] to an arbitrary multipart value. + * + * You should usually call [Builder.post] with a well-typed `List` value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun post(post: MultipartField>) = apply { + this.post = post.map { it.toMutableList() } + } + + /** + * Adds a single [Post] to [Builder.post]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addPost(post: Post) = apply { + this.post = + (this.post ?: MultipartField.of(mutableListOf())).also { + checkKnown("post", it).add(post) + } + } + + /** Alias for calling [addPost] with `Post.ofTransformation(transformation)`. */ + fun addPost(transformation: Post.InnerTransformation) = + addPost(Post.ofTransformation(transformation)) + + /** + * Alias for calling [addPost] with the following: + * ```java + * Post.InnerTransformation.builder() + * .value(value) + * .build() + * ``` + */ + fun addTransformationPost(value: String) = + addPost(Post.InnerTransformation.builder().value(value).build()) + + /** Alias for calling [addPost] with `Post.ofGifToVideo(gifToVideo)`. */ + fun addPost(gifToVideo: Post.GifToVideo) = addPost(Post.ofGifToVideo(gifToVideo)) + + /** Alias for calling [addPost] with `Post.ofThumbnail(thumbnail)`. */ + fun addPost(thumbnail: Post.Thumbnail) = addPost(Post.ofThumbnail(thumbnail)) + + /** Alias for calling [addPost] with `Post.ofAbs(abs)`. */ + fun addPost(abs: Post.Abs) = addPost(Post.ofAbs(abs)) + + /** + * Transformation string to apply before uploading the file to the Media Library. Useful + * for optimizing files at ingestion. + */ + fun pre(pre: String) = pre(MultipartField.of(pre)) + + /** + * Sets [Builder.pre] to an arbitrary multipart value. + * + * You should usually call [Builder.pre] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun pre(pre: MultipartField) = apply { this.pre = pre } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Transformation]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Transformation = + Transformation( + (post ?: MultipartField.of(null)).map { it.toImmutable() }, + pre, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Transformation = apply { + if (validated) { + return@apply + } + + post().ifPresent { it.forEach { it.validate() } } + pre() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + @JsonDeserialize(using = Post.Deserializer::class) + @JsonSerialize(using = Post.Serializer::class) + class Post + private constructor( + private val transformation: InnerTransformation? = null, + private val gifToVideo: GifToVideo? = null, + private val thumbnail: Thumbnail? = null, + private val abs: Abs? = null, + private val _json: JsonValue? = null, + ) { + + fun transformation(): Optional = + Optional.ofNullable(transformation) + + fun gifToVideo(): Optional = Optional.ofNullable(gifToVideo) + + fun thumbnail(): Optional = Optional.ofNullable(thumbnail) + + fun abs(): Optional = Optional.ofNullable(abs) + + fun isTransformation(): Boolean = transformation != null + + fun isGifToVideo(): Boolean = gifToVideo != null + + fun isThumbnail(): Boolean = thumbnail != null + + fun isAbs(): Boolean = abs != null + + fun asTransformation(): InnerTransformation = + transformation.getOrThrow("transformation") + + fun asGifToVideo(): GifToVideo = gifToVideo.getOrThrow("gifToVideo") + + fun asThumbnail(): Thumbnail = thumbnail.getOrThrow("thumbnail") + + fun asAbs(): Abs = abs.getOrThrow("abs") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + transformation != null -> visitor.visitTransformation(transformation) + gifToVideo != null -> visitor.visitGifToVideo(gifToVideo) + thumbnail != null -> visitor.visitThumbnail(thumbnail) + abs != null -> visitor.visitAbs(abs) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): Post = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitTransformation(transformation: InnerTransformation) { + transformation.validate() + } + + override fun visitGifToVideo(gifToVideo: GifToVideo) { + gifToVideo.validate() + } + + override fun visitThumbnail(thumbnail: Thumbnail) { + thumbnail.validate() + } + + override fun visitAbs(abs: Abs) { + abs.validate() + } + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitTransformation(transformation: InnerTransformation) = + transformation.validity() + + override fun visitGifToVideo(gifToVideo: GifToVideo) = gifToVideo.validity() + + override fun visitThumbnail(thumbnail: Thumbnail) = thumbnail.validity() + + override fun visitAbs(abs: Abs) = abs.validity() + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Post && + transformation == other.transformation && + gifToVideo == other.gifToVideo && + thumbnail == other.thumbnail && + abs == other.abs + } + + override fun hashCode(): Int = Objects.hash(transformation, gifToVideo, thumbnail, abs) + + override fun toString(): String = + when { + transformation != null -> "Post{transformation=$transformation}" + gifToVideo != null -> "Post{gifToVideo=$gifToVideo}" + thumbnail != null -> "Post{thumbnail=$thumbnail}" + abs != null -> "Post{abs=$abs}" + _json != null -> "Post{_unknown=$_json}" + else -> throw IllegalStateException("Invalid Post") + } + + companion object { + + @JvmStatic + fun ofTransformation(transformation: InnerTransformation) = + Post(transformation = transformation) + + @JvmStatic fun ofGifToVideo(gifToVideo: GifToVideo) = Post(gifToVideo = gifToVideo) + + @JvmStatic fun ofThumbnail(thumbnail: Thumbnail) = Post(thumbnail = thumbnail) + + @JvmStatic fun ofAbs(abs: Abs) = Post(abs = abs) + } + + /** + * An interface that defines how to map each variant of [Post] to a value of type [T]. + */ + interface Visitor { + + fun visitTransformation(transformation: InnerTransformation): T + + fun visitGifToVideo(gifToVideo: GifToVideo): T + + fun visitThumbnail(thumbnail: Thumbnail): T + + fun visitAbs(abs: Abs): T + + /** + * Maps an unknown variant of [Post] to a value of type [T]. + * + * An instance of [Post] can contain an unknown variant if it was deserialized from + * data that doesn't match any known variant. For example, if the SDK is on an older + * version than the API, then the API may respond with new variants that the SDK is + * unaware of. + * + * @throws ImageKitInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw ImageKitInvalidDataException("Unknown Post: $json") + } + } + + internal class Deserializer : BaseDeserializer(Post::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): Post { + val json = JsonValue.fromJsonNode(node) + val type = json.asObject().getOrNull()?.get("type")?.asString()?.getOrNull() + + when (type) { + "transformation" -> { + return tryDeserialize(node, jacksonTypeRef()) + ?.let { Post(transformation = it, _json = json) } + ?: Post(_json = json) + } + "gif-to-video" -> { + return tryDeserialize(node, jacksonTypeRef())?.let { + Post(gifToVideo = it, _json = json) + } ?: Post(_json = json) + } + "thumbnail" -> { + return tryDeserialize(node, jacksonTypeRef())?.let { + Post(thumbnail = it, _json = json) + } ?: Post(_json = json) + } + "abs" -> { + return tryDeserialize(node, jacksonTypeRef())?.let { + Post(abs = it, _json = json) + } ?: Post(_json = json) + } + } + + return Post(_json = json) + } + } + + internal class Serializer : BaseSerializer(Post::class) { + + override fun serialize( + value: Post, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.transformation != null -> generator.writeObject(value.transformation) + value.gifToVideo != null -> generator.writeObject(value.gifToVideo) + value.thumbnail != null -> generator.writeObject(value.thumbnail) + value.abs != null -> generator.writeObject(value.abs) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid Post") + } + } + } + + class InnerTransformation + private constructor( + private val type: JsonValue, + private val value: MultipartField, + private val additionalProperties: MutableMap, + ) { + + /** + * Transformation type. + * + * Expected to always return the following: + * ```java + * JsonValue.from("transformation") + * ``` + * + * However, this method can be useful for debugging and logging (e.g. if the server + * responded with an unexpected value). + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type + + /** + * Transformation string (e.g. `w-200,h-200`). Same syntax as ImageKit URL-based + * transformations. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or + * is unexpectedly missing or null (e.g. if the server responded with an + * unexpected value). + */ + fun value(): String = value.value.getRequired("value") + + /** + * Returns the raw multipart value of [value]. + * + * Unlike [value], this method doesn't throw if the multipart field has an + * unexpected type. + */ + @JsonProperty("value") @ExcludeMissing fun _value(): MultipartField = value + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [InnerTransformation]. + * + * The following fields are required: + * ```java + * .value() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [InnerTransformation]. */ + class Builder internal constructor() { + + private var type: JsonValue = JsonValue.from("transformation") + private var value: MultipartField? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(innerTransformation: InnerTransformation) = apply { + type = innerTransformation.type + value = innerTransformation.value + additionalProperties = + innerTransformation.additionalProperties.toMutableMap() + } + + /** + * Sets the field to an arbitrary JSON value. + * + * It is usually unnecessary to call this method because the field defaults to + * the following: + * ```java + * JsonValue.from("transformation") + * ``` + * + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun type(type: JsonValue) = apply { this.type = type } + + /** + * Transformation string (e.g. `w-200,h-200`). Same syntax as ImageKit URL-based + * transformations. + */ + fun value(value: String) = value(MultipartField.of(value)) + + /** + * Sets [Builder.value] to an arbitrary multipart value. + * + * You should usually call [Builder.value] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun value(value: MultipartField) = apply { this.value = value } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [InnerTransformation]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .value() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): InnerTransformation = + InnerTransformation( + type, + checkRequired("value", value), + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): InnerTransformation = apply { + if (validated) { + return@apply + } + + _type().let { + if (it != JsonValue.from("transformation")) { + throw ImageKitInvalidDataException("'type' is invalid, received $it") + } + } + value() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is InnerTransformation && + type == other.type && + value == other.value && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(type, value, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "InnerTransformation{type=$type, value=$value, additionalProperties=$additionalProperties}" + } + + class GifToVideo + private constructor( + private val type: JsonValue, + private val value: MultipartField, + private val additionalProperties: MutableMap, + ) { + + /** + * Converts an animated GIF into an MP4. + * + * Expected to always return the following: + * ```java + * JsonValue.from("gif-to-video") + * ``` + * + * However, this method can be useful for debugging and logging (e.g. if the server + * responded with an unexpected value). + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type + + /** + * Optional transformation string to apply to the output video. **Example**: `q-80` + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun value(): Optional = value.value.getOptional("value") + + /** + * Returns the raw multipart value of [value]. + * + * Unlike [value], this method doesn't throw if the multipart field has an + * unexpected type. + */ + @JsonProperty("value") @ExcludeMissing fun _value(): MultipartField = value + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [GifToVideo]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [GifToVideo]. */ + class Builder internal constructor() { + + private var type: JsonValue = JsonValue.from("gif-to-video") + private var value: MultipartField = MultipartField.of(null) + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(gifToVideo: GifToVideo) = apply { + type = gifToVideo.type + value = gifToVideo.value + additionalProperties = gifToVideo.additionalProperties.toMutableMap() + } + + /** + * Sets the field to an arbitrary JSON value. + * + * It is usually unnecessary to call this method because the field defaults to + * the following: + * ```java + * JsonValue.from("gif-to-video") + * ``` + * + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun type(type: JsonValue) = apply { this.type = type } + + /** + * Optional transformation string to apply to the output video. **Example**: + * `q-80` + */ + fun value(value: String) = value(MultipartField.of(value)) + + /** + * Sets [Builder.value] to an arbitrary multipart value. + * + * You should usually call [Builder.value] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun value(value: MultipartField) = apply { this.value = value } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [GifToVideo]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): GifToVideo = + GifToVideo(type, value, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): GifToVideo = apply { + if (validated) { + return@apply + } + + _type().let { + if (it != JsonValue.from("gif-to-video")) { + throw ImageKitInvalidDataException("'type' is invalid, received $it") + } + } + value() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is GifToVideo && + type == other.type && + value == other.value && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(type, value, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "GifToVideo{type=$type, value=$value, additionalProperties=$additionalProperties}" + } + + class Thumbnail + private constructor( + private val type: JsonValue, + private val value: MultipartField, + private val additionalProperties: MutableMap, + ) { + + /** + * Generates a thumbnail image. + * + * Expected to always return the following: + * ```java + * JsonValue.from("thumbnail") + * ``` + * + * However, this method can be useful for debugging and logging (e.g. if the server + * responded with an unexpected value). + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type + + /** + * Optional transformation string. **Example**: `w-150,h-150` + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun value(): Optional = value.value.getOptional("value") + + /** + * Returns the raw multipart value of [value]. + * + * Unlike [value], this method doesn't throw if the multipart field has an + * unexpected type. + */ + @JsonProperty("value") @ExcludeMissing fun _value(): MultipartField = value + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Thumbnail]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Thumbnail]. */ + class Builder internal constructor() { + + private var type: JsonValue = JsonValue.from("thumbnail") + private var value: MultipartField = MultipartField.of(null) + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(thumbnail: Thumbnail) = apply { + type = thumbnail.type + value = thumbnail.value + additionalProperties = thumbnail.additionalProperties.toMutableMap() + } + + /** + * Sets the field to an arbitrary JSON value. + * + * It is usually unnecessary to call this method because the field defaults to + * the following: + * ```java + * JsonValue.from("thumbnail") + * ``` + * + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun type(type: JsonValue) = apply { this.type = type } + + /** Optional transformation string. **Example**: `w-150,h-150` */ + fun value(value: String) = value(MultipartField.of(value)) + + /** + * Sets [Builder.value] to an arbitrary multipart value. + * + * You should usually call [Builder.value] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun value(value: MultipartField) = apply { this.value = value } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Thumbnail]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Thumbnail = + Thumbnail(type, value, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Thumbnail = apply { + if (validated) { + return@apply + } + + _type().let { + if (it != JsonValue.from("thumbnail")) { + throw ImageKitInvalidDataException("'type' is invalid, received $it") + } + } + value() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Thumbnail && + type == other.type && + value == other.value && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(type, value, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Thumbnail{type=$type, value=$value, additionalProperties=$additionalProperties}" + } + + class Abs + private constructor( + private val protocol: MultipartField, + private val type: JsonValue, + private val value: MultipartField, + private val additionalProperties: MutableMap, + ) { + + /** + * Streaming protocol to use (`hls` or `dash`). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or + * is unexpectedly missing or null (e.g. if the server responded with an + * unexpected value). + */ + fun protocol(): Protocol = protocol.value.getRequired("protocol") + + /** + * Adaptive Bitrate Streaming (ABS) setup. + * + * Expected to always return the following: + * ```java + * JsonValue.from("abs") + * ``` + * + * However, this method can be useful for debugging and logging (e.g. if the server + * responded with an unexpected value). + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type + + /** + * List of different representations you want to create separated by an underscore. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or + * is unexpectedly missing or null (e.g. if the server responded with an + * unexpected value). + */ + fun value(): String = value.value.getRequired("value") + + /** + * Returns the raw multipart value of [protocol]. + * + * Unlike [protocol], this method doesn't throw if the multipart field has an + * unexpected type. + */ + @JsonProperty("protocol") + @ExcludeMissing + fun _protocol(): MultipartField = protocol + + /** + * Returns the raw multipart value of [value]. + * + * Unlike [value], this method doesn't throw if the multipart field has an + * unexpected type. + */ + @JsonProperty("value") @ExcludeMissing fun _value(): MultipartField = value + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Abs]. + * + * The following fields are required: + * ```java + * .protocol() + * .value() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Abs]. */ + class Builder internal constructor() { + + private var protocol: MultipartField? = null + private var type: JsonValue = JsonValue.from("abs") + private var value: MultipartField? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(abs: Abs) = apply { + protocol = abs.protocol + type = abs.type + value = abs.value + additionalProperties = abs.additionalProperties.toMutableMap() + } + + /** Streaming protocol to use (`hls` or `dash`). */ + fun protocol(protocol: Protocol) = protocol(MultipartField.of(protocol)) + + /** + * Sets [Builder.protocol] to an arbitrary multipart value. + * + * You should usually call [Builder.protocol] with a well-typed [Protocol] value + * instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun protocol(protocol: MultipartField) = apply { + this.protocol = protocol + } + + /** + * Sets the field to an arbitrary JSON value. + * + * It is usually unnecessary to call this method because the field defaults to + * the following: + * ```java + * JsonValue.from("abs") + * ``` + * + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun type(type: JsonValue) = apply { this.type = type } + + /** + * List of different representations you want to create separated by an + * underscore. + */ + fun value(value: String) = value(MultipartField.of(value)) + + /** + * Sets [Builder.value] to an arbitrary multipart value. + * + * You should usually call [Builder.value] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun value(value: MultipartField) = apply { this.value = value } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Abs]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .protocol() + * .value() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Abs = + Abs( + checkRequired("protocol", protocol), + type, + checkRequired("value", value), + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Abs = apply { + if (validated) { + return@apply + } + + protocol().validate() + _type().let { + if (it != JsonValue.from("abs")) { + throw ImageKitInvalidDataException("'type' is invalid, received $it") + } + } + value() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** Streaming protocol to use (`hls` or `dash`). */ + class Protocol + @JsonCreator + private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that + * doesn't match any known member, and you want to know that value. For example, + * if the SDK is on an older version than the API, then the API may respond with + * new members that the SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue + fun _value(): JsonField = value + + companion object { + + @JvmField val HLS = of("hls") + + @JvmField val DASH = of("dash") + + @JvmStatic fun of(value: String) = Protocol(JsonField.of(value)) + } + + /** An enum containing [Protocol]'s known values. */ + enum class Known { + HLS, + DASH, + } + + /** + * An enum containing [Protocol]'s known values, as well as an [_UNKNOWN] + * member. + * + * An instance of [Protocol] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For + * example, if the SDK is on an older version than the API, then the API may + * respond with new members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + HLS, + DASH, + /** + * An enum member indicating that [Protocol] was instantiated with an + * unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or + * if you want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + HLS -> Value.HLS + DASH -> Value.DASH + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known + * and don't want to throw for the unknown case. + * + * @throws ImageKitInvalidDataException if this class instance's value is a not + * a known member. + */ + fun known(): Known = + when (this) { + HLS -> Known.HLS + DASH -> Known.DASH + else -> throw ImageKitInvalidDataException("Unknown Protocol: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for + * debugging and generally doesn't throw. + * + * @throws ImageKitInvalidDataException if this class instance's value does not + * have the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + ImageKitInvalidDataException("Value is not a String") + } + + private var validated: Boolean = false + + fun validate(): Protocol = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Protocol && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Abs && + protocol == other.protocol && + type == other.type && + value == other.value && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(protocol, type, value, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Abs{protocol=$protocol, type=$type, value=$value, additionalProperties=$additionalProperties}" + } + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Transformation && + post == other.post && + pre == other.pre && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(post, pre, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Transformation{post=$post, pre=$pre, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is FileUploadParams && + body == other.body && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = Objects.hash(body, additionalHeaders, additionalQueryParams) + + override fun toString() = + "FileUploadParams{body=$body, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/beta/v2/files/FileUploadResponse.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/beta/v2/files/FileUploadResponse.kt new file mode 100644 index 0000000..2b6fd59 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/beta/v2/files/FileUploadResponse.kt @@ -0,0 +1,2620 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.beta.v2.files + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.imagekit.api.core.Enum +import com.imagekit.api.core.ExcludeMissing +import com.imagekit.api.core.JsonField +import com.imagekit.api.core.JsonMissing +import com.imagekit.api.core.JsonValue +import com.imagekit.api.core.checkKnown +import com.imagekit.api.core.toImmutable +import com.imagekit.api.errors.ImageKitInvalidDataException +import com.imagekit.api.models.files.Metadata +import java.util.Collections +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** Object containing details of a successful upload. */ +class FileUploadResponse +private constructor( + private val aiTags: JsonField>, + private val audioCodec: JsonField, + private val bitRate: JsonField, + private val customCoordinates: JsonField, + private val customMetadata: JsonField, + private val description: JsonField, + private val duration: JsonField, + private val embeddedMetadata: JsonField, + private val extensionStatus: JsonField, + private val fileId: JsonField, + private val filePath: JsonField, + private val fileType: JsonField, + private val height: JsonField, + private val isPrivateFile: JsonField, + private val isPublished: JsonField, + private val metadata: JsonField, + private val name: JsonField, + private val size: JsonField, + private val tags: JsonField>, + private val thumbnailUrl: JsonField, + private val url: JsonField, + private val versionInfo: JsonField, + private val videoCodec: JsonField, + private val width: JsonField, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("AITags") @ExcludeMissing aiTags: JsonField> = JsonMissing.of(), + @JsonProperty("audioCodec") + @ExcludeMissing + audioCodec: JsonField = JsonMissing.of(), + @JsonProperty("bitRate") @ExcludeMissing bitRate: JsonField = JsonMissing.of(), + @JsonProperty("customCoordinates") + @ExcludeMissing + customCoordinates: JsonField = JsonMissing.of(), + @JsonProperty("customMetadata") + @ExcludeMissing + customMetadata: JsonField = JsonMissing.of(), + @JsonProperty("description") + @ExcludeMissing + description: JsonField = JsonMissing.of(), + @JsonProperty("duration") @ExcludeMissing duration: JsonField = JsonMissing.of(), + @JsonProperty("embeddedMetadata") + @ExcludeMissing + embeddedMetadata: JsonField = JsonMissing.of(), + @JsonProperty("extensionStatus") + @ExcludeMissing + extensionStatus: JsonField = JsonMissing.of(), + @JsonProperty("fileId") @ExcludeMissing fileId: JsonField = JsonMissing.of(), + @JsonProperty("filePath") @ExcludeMissing filePath: JsonField = JsonMissing.of(), + @JsonProperty("fileType") @ExcludeMissing fileType: JsonField = JsonMissing.of(), + @JsonProperty("height") @ExcludeMissing height: JsonField = JsonMissing.of(), + @JsonProperty("isPrivateFile") + @ExcludeMissing + isPrivateFile: JsonField = JsonMissing.of(), + @JsonProperty("isPublished") + @ExcludeMissing + isPublished: JsonField = JsonMissing.of(), + @JsonProperty("metadata") @ExcludeMissing metadata: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("size") @ExcludeMissing size: JsonField = JsonMissing.of(), + @JsonProperty("tags") @ExcludeMissing tags: JsonField> = JsonMissing.of(), + @JsonProperty("thumbnailUrl") + @ExcludeMissing + thumbnailUrl: JsonField = JsonMissing.of(), + @JsonProperty("url") @ExcludeMissing url: JsonField = JsonMissing.of(), + @JsonProperty("versionInfo") + @ExcludeMissing + versionInfo: JsonField = JsonMissing.of(), + @JsonProperty("videoCodec") + @ExcludeMissing + videoCodec: JsonField = JsonMissing.of(), + @JsonProperty("width") @ExcludeMissing width: JsonField = JsonMissing.of(), + ) : this( + aiTags, + audioCodec, + bitRate, + customCoordinates, + customMetadata, + description, + duration, + embeddedMetadata, + extensionStatus, + fileId, + filePath, + fileType, + height, + isPrivateFile, + isPublished, + metadata, + name, + size, + tags, + thumbnailUrl, + url, + versionInfo, + videoCodec, + width, + mutableMapOf(), + ) + + /** + * An array of tags assigned to the uploaded file by auto tagging. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun aiTags(): Optional> = aiTags.getOptional("AITags") + + /** + * The audio codec used in the video (only for video). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun audioCodec(): Optional = audioCodec.getOptional("audioCodec") + + /** + * The bit rate of the video in kbps (only for video). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun bitRate(): Optional = bitRate.getOptional("bitRate") + + /** + * Value of custom coordinates associated with the image in the format `x,y,width,height`. If + * `customCoordinates` are not defined, then it is `null`. Send `customCoordinates` in + * `responseFields` in API request to get the value of this field. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun customCoordinates(): Optional = customCoordinates.getOptional("customCoordinates") + + /** + * A key-value data associated with the asset. Use `responseField` in API request to get + * `customMetadata` in the upload API response. Before setting any custom metadata on an asset, + * you have to create the field using custom metadata fields API. Send `customMetadata` in + * `responseFields` in API request to get the value of this field. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun customMetadata(): Optional = customMetadata.getOptional("customMetadata") + + /** + * Optional text to describe the contents of the file. Can be set by the user or the + * ai-auto-description extension. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun description(): Optional = description.getOptional("description") + + /** + * The duration of the video in seconds (only for video). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun duration(): Optional = duration.getOptional("duration") + + /** + * Consolidated embedded metadata associated with the file. It includes exif, iptc, and xmp + * data. Send `embeddedMetadata` in `responseFields` in API request to get embeddedMetadata in + * the upload API response. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun embeddedMetadata(): Optional = + embeddedMetadata.getOptional("embeddedMetadata") + + /** + * Extension names with their processing status at the time of completion of the request. It + * could have one of the following status values: + * + * `success`: The extension has been successfully applied. `failed`: The extension has failed + * and will not be retried. `pending`: The extension will finish processing in some time. On + * completion, the final status (success / failed) will be sent to the `webhookUrl` provided. + * + * If no extension was requested, then this parameter is not returned. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun extensionStatus(): Optional = + extensionStatus.getOptional("extensionStatus") + + /** + * Unique fileId. Store this fileld in your database, as this will be used to perform update + * action on this file. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun fileId(): Optional = fileId.getOptional("fileId") + + /** + * The relative path of the file in the media library e.g. `/marketing-assets/new-banner.jpg`. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun filePath(): Optional = filePath.getOptional("filePath") + + /** + * Type of the uploaded file. Possible values are `image`, `non-image`. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun fileType(): Optional = fileType.getOptional("fileType") + + /** + * Height of the image in pixels (Only for images) + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun height(): Optional = height.getOptional("height") + + /** + * Is the file marked as private. It can be either `true` or `false`. Send `isPrivateFile` in + * `responseFields` in API request to get the value of this field. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun isPrivateFile(): Optional = isPrivateFile.getOptional("isPrivateFile") + + /** + * Is the file published or in draft state. It can be either `true` or `false`. Send + * `isPublished` in `responseFields` in API request to get the value of this field. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun isPublished(): Optional = isPublished.getOptional("isPublished") + + /** + * Legacy metadata. Send `metadata` in `responseFields` in API request to get metadata in the + * upload API response. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun metadata(): Optional = metadata.getOptional("metadata") + + /** + * Name of the asset. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun name(): Optional = name.getOptional("name") + + /** + * Size of the image file in Bytes. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun size(): Optional = size.getOptional("size") + + /** + * The array of tags associated with the asset. If no tags are set, it will be `null`. Send + * `tags` in `responseFields` in API request to get the value of this field. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun tags(): Optional> = tags.getOptional("tags") + + /** + * In the case of an image, a small thumbnail URL. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun thumbnailUrl(): Optional = thumbnailUrl.getOptional("thumbnailUrl") + + /** + * A publicly accessible URL of the file. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun url(): Optional = url.getOptional("url") + + /** + * An object containing the file or file version's `id` (versionId) and `name`. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun versionInfo(): Optional = versionInfo.getOptional("versionInfo") + + /** + * The video codec used in the video (only for video). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun videoCodec(): Optional = videoCodec.getOptional("videoCodec") + + /** + * Width of the image in pixels (Only for Images) + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun width(): Optional = width.getOptional("width") + + /** + * Returns the raw JSON value of [aiTags]. + * + * Unlike [aiTags], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("AITags") @ExcludeMissing fun _aiTags(): JsonField> = aiTags + + /** + * Returns the raw JSON value of [audioCodec]. + * + * Unlike [audioCodec], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("audioCodec") @ExcludeMissing fun _audioCodec(): JsonField = audioCodec + + /** + * Returns the raw JSON value of [bitRate]. + * + * Unlike [bitRate], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("bitRate") @ExcludeMissing fun _bitRate(): JsonField = bitRate + + /** + * Returns the raw JSON value of [customCoordinates]. + * + * Unlike [customCoordinates], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("customCoordinates") + @ExcludeMissing + fun _customCoordinates(): JsonField = customCoordinates + + /** + * Returns the raw JSON value of [customMetadata]. + * + * Unlike [customMetadata], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("customMetadata") + @ExcludeMissing + fun _customMetadata(): JsonField = customMetadata + + /** + * Returns the raw JSON value of [description]. + * + * Unlike [description], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("description") @ExcludeMissing fun _description(): JsonField = description + + /** + * Returns the raw JSON value of [duration]. + * + * Unlike [duration], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("duration") @ExcludeMissing fun _duration(): JsonField = duration + + /** + * Returns the raw JSON value of [embeddedMetadata]. + * + * Unlike [embeddedMetadata], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("embeddedMetadata") + @ExcludeMissing + fun _embeddedMetadata(): JsonField = embeddedMetadata + + /** + * Returns the raw JSON value of [extensionStatus]. + * + * Unlike [extensionStatus], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("extensionStatus") + @ExcludeMissing + fun _extensionStatus(): JsonField = extensionStatus + + /** + * Returns the raw JSON value of [fileId]. + * + * Unlike [fileId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("fileId") @ExcludeMissing fun _fileId(): JsonField = fileId + + /** + * Returns the raw JSON value of [filePath]. + * + * Unlike [filePath], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("filePath") @ExcludeMissing fun _filePath(): JsonField = filePath + + /** + * Returns the raw JSON value of [fileType]. + * + * Unlike [fileType], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("fileType") @ExcludeMissing fun _fileType(): JsonField = fileType + + /** + * Returns the raw JSON value of [height]. + * + * Unlike [height], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("height") @ExcludeMissing fun _height(): JsonField = height + + /** + * Returns the raw JSON value of [isPrivateFile]. + * + * Unlike [isPrivateFile], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("isPrivateFile") + @ExcludeMissing + fun _isPrivateFile(): JsonField = isPrivateFile + + /** + * Returns the raw JSON value of [isPublished]. + * + * Unlike [isPublished], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("isPublished") + @ExcludeMissing + fun _isPublished(): JsonField = isPublished + + /** + * Returns the raw JSON value of [metadata]. + * + * Unlike [metadata], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("metadata") @ExcludeMissing fun _metadata(): JsonField = metadata + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + + /** + * Returns the raw JSON value of [size]. + * + * Unlike [size], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("size") @ExcludeMissing fun _size(): JsonField = size + + /** + * Returns the raw JSON value of [tags]. + * + * Unlike [tags], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("tags") @ExcludeMissing fun _tags(): JsonField> = tags + + /** + * Returns the raw JSON value of [thumbnailUrl]. + * + * Unlike [thumbnailUrl], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("thumbnailUrl") + @ExcludeMissing + fun _thumbnailUrl(): JsonField = thumbnailUrl + + /** + * Returns the raw JSON value of [url]. + * + * Unlike [url], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("url") @ExcludeMissing fun _url(): JsonField = url + + /** + * Returns the raw JSON value of [versionInfo]. + * + * Unlike [versionInfo], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("versionInfo") + @ExcludeMissing + fun _versionInfo(): JsonField = versionInfo + + /** + * Returns the raw JSON value of [videoCodec]. + * + * Unlike [videoCodec], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("videoCodec") @ExcludeMissing fun _videoCodec(): JsonField = videoCodec + + /** + * Returns the raw JSON value of [width]. + * + * Unlike [width], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("width") @ExcludeMissing fun _width(): JsonField = width + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [FileUploadResponse]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [FileUploadResponse]. */ + class Builder internal constructor() { + + private var aiTags: JsonField>? = null + private var audioCodec: JsonField = JsonMissing.of() + private var bitRate: JsonField = JsonMissing.of() + private var customCoordinates: JsonField = JsonMissing.of() + private var customMetadata: JsonField = JsonMissing.of() + private var description: JsonField = JsonMissing.of() + private var duration: JsonField = JsonMissing.of() + private var embeddedMetadata: JsonField = JsonMissing.of() + private var extensionStatus: JsonField = JsonMissing.of() + private var fileId: JsonField = JsonMissing.of() + private var filePath: JsonField = JsonMissing.of() + private var fileType: JsonField = JsonMissing.of() + private var height: JsonField = JsonMissing.of() + private var isPrivateFile: JsonField = JsonMissing.of() + private var isPublished: JsonField = JsonMissing.of() + private var metadata: JsonField = JsonMissing.of() + private var name: JsonField = JsonMissing.of() + private var size: JsonField = JsonMissing.of() + private var tags: JsonField>? = null + private var thumbnailUrl: JsonField = JsonMissing.of() + private var url: JsonField = JsonMissing.of() + private var versionInfo: JsonField = JsonMissing.of() + private var videoCodec: JsonField = JsonMissing.of() + private var width: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(fileUploadResponse: FileUploadResponse) = apply { + aiTags = fileUploadResponse.aiTags.map { it.toMutableList() } + audioCodec = fileUploadResponse.audioCodec + bitRate = fileUploadResponse.bitRate + customCoordinates = fileUploadResponse.customCoordinates + customMetadata = fileUploadResponse.customMetadata + description = fileUploadResponse.description + duration = fileUploadResponse.duration + embeddedMetadata = fileUploadResponse.embeddedMetadata + extensionStatus = fileUploadResponse.extensionStatus + fileId = fileUploadResponse.fileId + filePath = fileUploadResponse.filePath + fileType = fileUploadResponse.fileType + height = fileUploadResponse.height + isPrivateFile = fileUploadResponse.isPrivateFile + isPublished = fileUploadResponse.isPublished + metadata = fileUploadResponse.metadata + name = fileUploadResponse.name + size = fileUploadResponse.size + tags = fileUploadResponse.tags.map { it.toMutableList() } + thumbnailUrl = fileUploadResponse.thumbnailUrl + url = fileUploadResponse.url + versionInfo = fileUploadResponse.versionInfo + videoCodec = fileUploadResponse.videoCodec + width = fileUploadResponse.width + additionalProperties = fileUploadResponse.additionalProperties.toMutableMap() + } + + /** An array of tags assigned to the uploaded file by auto tagging. */ + fun aiTags(aiTags: List?) = aiTags(JsonField.ofNullable(aiTags)) + + /** Alias for calling [Builder.aiTags] with `aiTags.orElse(null)`. */ + fun aiTags(aiTags: Optional>) = aiTags(aiTags.getOrNull()) + + /** + * Sets [Builder.aiTags] to an arbitrary JSON value. + * + * You should usually call [Builder.aiTags] with a well-typed `List` value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun aiTags(aiTags: JsonField>) = apply { + this.aiTags = aiTags.map { it.toMutableList() } + } + + /** + * Adds a single [AiTag] to [aiTags]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addAiTag(aiTag: AiTag) = apply { + aiTags = + (aiTags ?: JsonField.of(mutableListOf())).also { + checkKnown("aiTags", it).add(aiTag) + } + } + + /** The audio codec used in the video (only for video). */ + fun audioCodec(audioCodec: String) = audioCodec(JsonField.of(audioCodec)) + + /** + * Sets [Builder.audioCodec] to an arbitrary JSON value. + * + * You should usually call [Builder.audioCodec] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun audioCodec(audioCodec: JsonField) = apply { this.audioCodec = audioCodec } + + /** The bit rate of the video in kbps (only for video). */ + fun bitRate(bitRate: Long) = bitRate(JsonField.of(bitRate)) + + /** + * Sets [Builder.bitRate] to an arbitrary JSON value. + * + * You should usually call [Builder.bitRate] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun bitRate(bitRate: JsonField) = apply { this.bitRate = bitRate } + + /** + * Value of custom coordinates associated with the image in the format `x,y,width,height`. + * If `customCoordinates` are not defined, then it is `null`. Send `customCoordinates` in + * `responseFields` in API request to get the value of this field. + */ + fun customCoordinates(customCoordinates: String?) = + customCoordinates(JsonField.ofNullable(customCoordinates)) + + /** Alias for calling [Builder.customCoordinates] with `customCoordinates.orElse(null)`. */ + fun customCoordinates(customCoordinates: Optional) = + customCoordinates(customCoordinates.getOrNull()) + + /** + * Sets [Builder.customCoordinates] to an arbitrary JSON value. + * + * You should usually call [Builder.customCoordinates] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun customCoordinates(customCoordinates: JsonField) = apply { + this.customCoordinates = customCoordinates + } + + /** + * A key-value data associated with the asset. Use `responseField` in API request to get + * `customMetadata` in the upload API response. Before setting any custom metadata on an + * asset, you have to create the field using custom metadata fields API. Send + * `customMetadata` in `responseFields` in API request to get the value of this field. + */ + fun customMetadata(customMetadata: CustomMetadata) = + customMetadata(JsonField.of(customMetadata)) + + /** + * Sets [Builder.customMetadata] to an arbitrary JSON value. + * + * You should usually call [Builder.customMetadata] with a well-typed [CustomMetadata] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun customMetadata(customMetadata: JsonField) = apply { + this.customMetadata = customMetadata + } + + /** + * Optional text to describe the contents of the file. Can be set by the user or the + * ai-auto-description extension. + */ + fun description(description: String) = description(JsonField.of(description)) + + /** + * Sets [Builder.description] to an arbitrary JSON value. + * + * You should usually call [Builder.description] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun description(description: JsonField) = apply { this.description = description } + + /** The duration of the video in seconds (only for video). */ + fun duration(duration: Long) = duration(JsonField.of(duration)) + + /** + * Sets [Builder.duration] to an arbitrary JSON value. + * + * You should usually call [Builder.duration] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun duration(duration: JsonField) = apply { this.duration = duration } + + /** + * Consolidated embedded metadata associated with the file. It includes exif, iptc, and xmp + * data. Send `embeddedMetadata` in `responseFields` in API request to get embeddedMetadata + * in the upload API response. + */ + fun embeddedMetadata(embeddedMetadata: EmbeddedMetadata) = + embeddedMetadata(JsonField.of(embeddedMetadata)) + + /** + * Sets [Builder.embeddedMetadata] to an arbitrary JSON value. + * + * You should usually call [Builder.embeddedMetadata] with a well-typed [EmbeddedMetadata] + * value instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun embeddedMetadata(embeddedMetadata: JsonField) = apply { + this.embeddedMetadata = embeddedMetadata + } + + /** + * Extension names with their processing status at the time of completion of the request. It + * could have one of the following status values: + * + * `success`: The extension has been successfully applied. `failed`: The extension has + * failed and will not be retried. `pending`: The extension will finish processing in some + * time. On completion, the final status (success / failed) will be sent to the `webhookUrl` + * provided. + * + * If no extension was requested, then this parameter is not returned. + */ + fun extensionStatus(extensionStatus: ExtensionStatus) = + extensionStatus(JsonField.of(extensionStatus)) + + /** + * Sets [Builder.extensionStatus] to an arbitrary JSON value. + * + * You should usually call [Builder.extensionStatus] with a well-typed [ExtensionStatus] + * value instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun extensionStatus(extensionStatus: JsonField) = apply { + this.extensionStatus = extensionStatus + } + + /** + * Unique fileId. Store this fileld in your database, as this will be used to perform update + * action on this file. + */ + fun fileId(fileId: String) = fileId(JsonField.of(fileId)) + + /** + * Sets [Builder.fileId] to an arbitrary JSON value. + * + * You should usually call [Builder.fileId] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun fileId(fileId: JsonField) = apply { this.fileId = fileId } + + /** + * The relative path of the file in the media library e.g. + * `/marketing-assets/new-banner.jpg`. + */ + fun filePath(filePath: String) = filePath(JsonField.of(filePath)) + + /** + * Sets [Builder.filePath] to an arbitrary JSON value. + * + * You should usually call [Builder.filePath] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun filePath(filePath: JsonField) = apply { this.filePath = filePath } + + /** Type of the uploaded file. Possible values are `image`, `non-image`. */ + fun fileType(fileType: String) = fileType(JsonField.of(fileType)) + + /** + * Sets [Builder.fileType] to an arbitrary JSON value. + * + * You should usually call [Builder.fileType] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun fileType(fileType: JsonField) = apply { this.fileType = fileType } + + /** Height of the image in pixels (Only for images) */ + fun height(height: Double) = height(JsonField.of(height)) + + /** + * Sets [Builder.height] to an arbitrary JSON value. + * + * You should usually call [Builder.height] with a well-typed [Double] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun height(height: JsonField) = apply { this.height = height } + + /** + * Is the file marked as private. It can be either `true` or `false`. Send `isPrivateFile` + * in `responseFields` in API request to get the value of this field. + */ + fun isPrivateFile(isPrivateFile: Boolean) = isPrivateFile(JsonField.of(isPrivateFile)) + + /** + * Sets [Builder.isPrivateFile] to an arbitrary JSON value. + * + * You should usually call [Builder.isPrivateFile] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun isPrivateFile(isPrivateFile: JsonField) = apply { + this.isPrivateFile = isPrivateFile + } + + /** + * Is the file published or in draft state. It can be either `true` or `false`. Send + * `isPublished` in `responseFields` in API request to get the value of this field. + */ + fun isPublished(isPublished: Boolean) = isPublished(JsonField.of(isPublished)) + + /** + * Sets [Builder.isPublished] to an arbitrary JSON value. + * + * You should usually call [Builder.isPublished] with a well-typed [Boolean] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun isPublished(isPublished: JsonField) = apply { this.isPublished = isPublished } + + /** + * Legacy metadata. Send `metadata` in `responseFields` in API request to get metadata in + * the upload API response. + */ + fun metadata(metadata: Metadata) = metadata(JsonField.of(metadata)) + + /** + * Sets [Builder.metadata] to an arbitrary JSON value. + * + * You should usually call [Builder.metadata] with a well-typed [Metadata] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun metadata(metadata: JsonField) = apply { this.metadata = metadata } + + /** Name of the asset. */ + fun name(name: String) = name(JsonField.of(name)) + + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun name(name: JsonField) = apply { this.name = name } + + /** Size of the image file in Bytes. */ + fun size(size: Double) = size(JsonField.of(size)) + + /** + * Sets [Builder.size] to an arbitrary JSON value. + * + * You should usually call [Builder.size] with a well-typed [Double] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun size(size: JsonField) = apply { this.size = size } + + /** + * The array of tags associated with the asset. If no tags are set, it will be `null`. Send + * `tags` in `responseFields` in API request to get the value of this field. + */ + fun tags(tags: List?) = tags(JsonField.ofNullable(tags)) + + /** Alias for calling [Builder.tags] with `tags.orElse(null)`. */ + fun tags(tags: Optional>) = tags(tags.getOrNull()) + + /** + * Sets [Builder.tags] to an arbitrary JSON value. + * + * You should usually call [Builder.tags] with a well-typed `List` value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun tags(tags: JsonField>) = apply { + this.tags = tags.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [tags]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addTag(tag: String) = apply { + tags = (tags ?: JsonField.of(mutableListOf())).also { checkKnown("tags", it).add(tag) } + } + + /** In the case of an image, a small thumbnail URL. */ + fun thumbnailUrl(thumbnailUrl: String) = thumbnailUrl(JsonField.of(thumbnailUrl)) + + /** + * Sets [Builder.thumbnailUrl] to an arbitrary JSON value. + * + * You should usually call [Builder.thumbnailUrl] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun thumbnailUrl(thumbnailUrl: JsonField) = apply { + this.thumbnailUrl = thumbnailUrl + } + + /** A publicly accessible URL of the file. */ + fun url(url: String) = url(JsonField.of(url)) + + /** + * Sets [Builder.url] to an arbitrary JSON value. + * + * You should usually call [Builder.url] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun url(url: JsonField) = apply { this.url = url } + + /** An object containing the file or file version's `id` (versionId) and `name`. */ + fun versionInfo(versionInfo: VersionInfo) = versionInfo(JsonField.of(versionInfo)) + + /** + * Sets [Builder.versionInfo] to an arbitrary JSON value. + * + * You should usually call [Builder.versionInfo] with a well-typed [VersionInfo] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun versionInfo(versionInfo: JsonField) = apply { + this.versionInfo = versionInfo + } + + /** The video codec used in the video (only for video). */ + fun videoCodec(videoCodec: String) = videoCodec(JsonField.of(videoCodec)) + + /** + * Sets [Builder.videoCodec] to an arbitrary JSON value. + * + * You should usually call [Builder.videoCodec] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun videoCodec(videoCodec: JsonField) = apply { this.videoCodec = videoCodec } + + /** Width of the image in pixels (Only for Images) */ + fun width(width: Double) = width(JsonField.of(width)) + + /** + * Sets [Builder.width] to an arbitrary JSON value. + * + * You should usually call [Builder.width] with a well-typed [Double] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun width(width: JsonField) = apply { this.width = width } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [FileUploadResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): FileUploadResponse = + FileUploadResponse( + (aiTags ?: JsonMissing.of()).map { it.toImmutable() }, + audioCodec, + bitRate, + customCoordinates, + customMetadata, + description, + duration, + embeddedMetadata, + extensionStatus, + fileId, + filePath, + fileType, + height, + isPrivateFile, + isPublished, + metadata, + name, + size, + (tags ?: JsonMissing.of()).map { it.toImmutable() }, + thumbnailUrl, + url, + versionInfo, + videoCodec, + width, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): FileUploadResponse = apply { + if (validated) { + return@apply + } + + aiTags().ifPresent { it.forEach { it.validate() } } + audioCodec() + bitRate() + customCoordinates() + customMetadata().ifPresent { it.validate() } + description() + duration() + embeddedMetadata().ifPresent { it.validate() } + extensionStatus().ifPresent { it.validate() } + fileId() + filePath() + fileType() + height() + isPrivateFile() + isPublished() + metadata().ifPresent { it.validate() } + name() + size() + tags() + thumbnailUrl() + url() + versionInfo().ifPresent { it.validate() } + videoCodec() + width() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (aiTags.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + (if (audioCodec.asKnown().isPresent) 1 else 0) + + (if (bitRate.asKnown().isPresent) 1 else 0) + + (if (customCoordinates.asKnown().isPresent) 1 else 0) + + (customMetadata.asKnown().getOrNull()?.validity() ?: 0) + + (if (description.asKnown().isPresent) 1 else 0) + + (if (duration.asKnown().isPresent) 1 else 0) + + (embeddedMetadata.asKnown().getOrNull()?.validity() ?: 0) + + (extensionStatus.asKnown().getOrNull()?.validity() ?: 0) + + (if (fileId.asKnown().isPresent) 1 else 0) + + (if (filePath.asKnown().isPresent) 1 else 0) + + (if (fileType.asKnown().isPresent) 1 else 0) + + (if (height.asKnown().isPresent) 1 else 0) + + (if (isPrivateFile.asKnown().isPresent) 1 else 0) + + (if (isPublished.asKnown().isPresent) 1 else 0) + + (metadata.asKnown().getOrNull()?.validity() ?: 0) + + (if (name.asKnown().isPresent) 1 else 0) + + (if (size.asKnown().isPresent) 1 else 0) + + (tags.asKnown().getOrNull()?.size ?: 0) + + (if (thumbnailUrl.asKnown().isPresent) 1 else 0) + + (if (url.asKnown().isPresent) 1 else 0) + + (versionInfo.asKnown().getOrNull()?.validity() ?: 0) + + (if (videoCodec.asKnown().isPresent) 1 else 0) + + (if (width.asKnown().isPresent) 1 else 0) + + class AiTag + private constructor( + private val confidence: JsonField, + private val name: JsonField, + private val source: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("confidence") + @ExcludeMissing + confidence: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("source") @ExcludeMissing source: JsonField = JsonMissing.of(), + ) : this(confidence, name, source, mutableMapOf()) + + /** + * Confidence score of the tag. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun confidence(): Optional = confidence.getOptional("confidence") + + /** + * Name of the tag. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun name(): Optional = name.getOptional("name") + + /** + * Array of `AITags` associated with the image. If no `AITags` are set, it will be null. + * These tags can be added using the `google-auto-tagging` or `aws-auto-tagging` extensions. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun source(): Optional = source.getOptional("source") + + /** + * Returns the raw JSON value of [confidence]. + * + * Unlike [confidence], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("confidence") + @ExcludeMissing + fun _confidence(): JsonField = confidence + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + + /** + * Returns the raw JSON value of [source]. + * + * Unlike [source], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("source") @ExcludeMissing fun _source(): JsonField = source + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [AiTag]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [AiTag]. */ + class Builder internal constructor() { + + private var confidence: JsonField = JsonMissing.of() + private var name: JsonField = JsonMissing.of() + private var source: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(aiTag: AiTag) = apply { + confidence = aiTag.confidence + name = aiTag.name + source = aiTag.source + additionalProperties = aiTag.additionalProperties.toMutableMap() + } + + /** Confidence score of the tag. */ + fun confidence(confidence: Double) = confidence(JsonField.of(confidence)) + + /** + * Sets [Builder.confidence] to an arbitrary JSON value. + * + * You should usually call [Builder.confidence] with a well-typed [Double] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun confidence(confidence: JsonField) = apply { this.confidence = confidence } + + /** Name of the tag. */ + fun name(name: String) = name(JsonField.of(name)) + + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun name(name: JsonField) = apply { this.name = name } + + /** + * Array of `AITags` associated with the image. If no `AITags` are set, it will be null. + * These tags can be added using the `google-auto-tagging` or `aws-auto-tagging` + * extensions. + */ + fun source(source: String) = source(JsonField.of(source)) + + /** + * Sets [Builder.source] to an arbitrary JSON value. + * + * You should usually call [Builder.source] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun source(source: JsonField) = apply { this.source = source } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [AiTag]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): AiTag = + AiTag(confidence, name, source, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): AiTag = apply { + if (validated) { + return@apply + } + + confidence() + name() + source() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (confidence.asKnown().isPresent) 1 else 0) + + (if (name.asKnown().isPresent) 1 else 0) + + (if (source.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is AiTag && + confidence == other.confidence && + name == other.name && + source == other.source && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(confidence, name, source, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "AiTag{confidence=$confidence, name=$name, source=$source, additionalProperties=$additionalProperties}" + } + + /** + * A key-value data associated with the asset. Use `responseField` in API request to get + * `customMetadata` in the upload API response. Before setting any custom metadata on an asset, + * you have to create the field using custom metadata fields API. Send `customMetadata` in + * `responseFields` in API request to get the value of this field. + */ + class CustomMetadata + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [CustomMetadata]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [CustomMetadata]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(customMetadata: CustomMetadata) = apply { + additionalProperties = customMetadata.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [CustomMetadata]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): CustomMetadata = CustomMetadata(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): CustomMetadata = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is CustomMetadata && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "CustomMetadata{additionalProperties=$additionalProperties}" + } + + /** + * Consolidated embedded metadata associated with the file. It includes exif, iptc, and xmp + * data. Send `embeddedMetadata` in `responseFields` in API request to get embeddedMetadata in + * the upload API response. + */ + class EmbeddedMetadata + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [EmbeddedMetadata]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [EmbeddedMetadata]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(embeddedMetadata: EmbeddedMetadata) = apply { + additionalProperties = embeddedMetadata.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [EmbeddedMetadata]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): EmbeddedMetadata = EmbeddedMetadata(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): EmbeddedMetadata = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is EmbeddedMetadata && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "EmbeddedMetadata{additionalProperties=$additionalProperties}" + } + + /** + * Extension names with their processing status at the time of completion of the request. It + * could have one of the following status values: + * + * `success`: The extension has been successfully applied. `failed`: The extension has failed + * and will not be retried. `pending`: The extension will finish processing in some time. On + * completion, the final status (success / failed) will be sent to the `webhookUrl` provided. + * + * If no extension was requested, then this parameter is not returned. + */ + class ExtensionStatus + private constructor( + private val aiAutoDescription: JsonField, + private val awsAutoTagging: JsonField, + private val googleAutoTagging: JsonField, + private val removeBg: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("ai-auto-description") + @ExcludeMissing + aiAutoDescription: JsonField = JsonMissing.of(), + @JsonProperty("aws-auto-tagging") + @ExcludeMissing + awsAutoTagging: JsonField = JsonMissing.of(), + @JsonProperty("google-auto-tagging") + @ExcludeMissing + googleAutoTagging: JsonField = JsonMissing.of(), + @JsonProperty("remove-bg") + @ExcludeMissing + removeBg: JsonField = JsonMissing.of(), + ) : this(aiAutoDescription, awsAutoTagging, googleAutoTagging, removeBg, mutableMapOf()) + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun aiAutoDescription(): Optional = + aiAutoDescription.getOptional("ai-auto-description") + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun awsAutoTagging(): Optional = + awsAutoTagging.getOptional("aws-auto-tagging") + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun googleAutoTagging(): Optional = + googleAutoTagging.getOptional("google-auto-tagging") + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun removeBg(): Optional = removeBg.getOptional("remove-bg") + + /** + * Returns the raw JSON value of [aiAutoDescription]. + * + * Unlike [aiAutoDescription], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("ai-auto-description") + @ExcludeMissing + fun _aiAutoDescription(): JsonField = aiAutoDescription + + /** + * Returns the raw JSON value of [awsAutoTagging]. + * + * Unlike [awsAutoTagging], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("aws-auto-tagging") + @ExcludeMissing + fun _awsAutoTagging(): JsonField = awsAutoTagging + + /** + * Returns the raw JSON value of [googleAutoTagging]. + * + * Unlike [googleAutoTagging], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("google-auto-tagging") + @ExcludeMissing + fun _googleAutoTagging(): JsonField = googleAutoTagging + + /** + * Returns the raw JSON value of [removeBg]. + * + * Unlike [removeBg], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("remove-bg") @ExcludeMissing fun _removeBg(): JsonField = removeBg + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [ExtensionStatus]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ExtensionStatus]. */ + class Builder internal constructor() { + + private var aiAutoDescription: JsonField = JsonMissing.of() + private var awsAutoTagging: JsonField = JsonMissing.of() + private var googleAutoTagging: JsonField = JsonMissing.of() + private var removeBg: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(extensionStatus: ExtensionStatus) = apply { + aiAutoDescription = extensionStatus.aiAutoDescription + awsAutoTagging = extensionStatus.awsAutoTagging + googleAutoTagging = extensionStatus.googleAutoTagging + removeBg = extensionStatus.removeBg + additionalProperties = extensionStatus.additionalProperties.toMutableMap() + } + + fun aiAutoDescription(aiAutoDescription: AiAutoDescription) = + aiAutoDescription(JsonField.of(aiAutoDescription)) + + /** + * Sets [Builder.aiAutoDescription] to an arbitrary JSON value. + * + * You should usually call [Builder.aiAutoDescription] with a well-typed + * [AiAutoDescription] value instead. This method is primarily for setting the field to + * an undocumented or not yet supported value. + */ + fun aiAutoDescription(aiAutoDescription: JsonField) = apply { + this.aiAutoDescription = aiAutoDescription + } + + fun awsAutoTagging(awsAutoTagging: AwsAutoTagging) = + awsAutoTagging(JsonField.of(awsAutoTagging)) + + /** + * Sets [Builder.awsAutoTagging] to an arbitrary JSON value. + * + * You should usually call [Builder.awsAutoTagging] with a well-typed [AwsAutoTagging] + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun awsAutoTagging(awsAutoTagging: JsonField) = apply { + this.awsAutoTagging = awsAutoTagging + } + + fun googleAutoTagging(googleAutoTagging: GoogleAutoTagging) = + googleAutoTagging(JsonField.of(googleAutoTagging)) + + /** + * Sets [Builder.googleAutoTagging] to an arbitrary JSON value. + * + * You should usually call [Builder.googleAutoTagging] with a well-typed + * [GoogleAutoTagging] value instead. This method is primarily for setting the field to + * an undocumented or not yet supported value. + */ + fun googleAutoTagging(googleAutoTagging: JsonField) = apply { + this.googleAutoTagging = googleAutoTagging + } + + fun removeBg(removeBg: RemoveBg) = removeBg(JsonField.of(removeBg)) + + /** + * Sets [Builder.removeBg] to an arbitrary JSON value. + * + * You should usually call [Builder.removeBg] with a well-typed [RemoveBg] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun removeBg(removeBg: JsonField) = apply { this.removeBg = removeBg } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ExtensionStatus]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): ExtensionStatus = + ExtensionStatus( + aiAutoDescription, + awsAutoTagging, + googleAutoTagging, + removeBg, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): ExtensionStatus = apply { + if (validated) { + return@apply + } + + aiAutoDescription().ifPresent { it.validate() } + awsAutoTagging().ifPresent { it.validate() } + googleAutoTagging().ifPresent { it.validate() } + removeBg().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (aiAutoDescription.asKnown().getOrNull()?.validity() ?: 0) + + (awsAutoTagging.asKnown().getOrNull()?.validity() ?: 0) + + (googleAutoTagging.asKnown().getOrNull()?.validity() ?: 0) + + (removeBg.asKnown().getOrNull()?.validity() ?: 0) + + class AiAutoDescription + @JsonCreator + private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is + * on an older version than the API, then the API may respond with new members that the + * SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val SUCCESS = of("success") + + @JvmField val PENDING = of("pending") + + @JvmField val FAILED = of("failed") + + @JvmStatic fun of(value: String) = AiAutoDescription(JsonField.of(value)) + } + + /** An enum containing [AiAutoDescription]'s known values. */ + enum class Known { + SUCCESS, + PENDING, + FAILED, + } + + /** + * An enum containing [AiAutoDescription]'s known values, as well as an [_UNKNOWN] + * member. + * + * An instance of [AiAutoDescription] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if + * the SDK is on an older version than the API, then the API may respond with new + * members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + SUCCESS, + PENDING, + FAILED, + /** + * An enum member indicating that [AiAutoDescription] was instantiated with an + * unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you + * want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + SUCCESS -> Value.SUCCESS + PENDING -> Value.PENDING + FAILED -> Value.FAILED + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and + * don't want to throw for the unknown case. + * + * @throws ImageKitInvalidDataException if this class instance's value is a not a known + * member. + */ + fun known(): Known = + when (this) { + SUCCESS -> Known.SUCCESS + PENDING -> Known.PENDING + FAILED -> Known.FAILED + else -> throw ImageKitInvalidDataException("Unknown AiAutoDescription: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for + * debugging and generally doesn't throw. + * + * @throws ImageKitInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + ImageKitInvalidDataException("Value is not a String") + } + + private var validated: Boolean = false + + fun validate(): AiAutoDescription = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is AiAutoDescription && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + class AwsAutoTagging + @JsonCreator + private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is + * on an older version than the API, then the API may respond with new members that the + * SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val SUCCESS = of("success") + + @JvmField val PENDING = of("pending") + + @JvmField val FAILED = of("failed") + + @JvmStatic fun of(value: String) = AwsAutoTagging(JsonField.of(value)) + } + + /** An enum containing [AwsAutoTagging]'s known values. */ + enum class Known { + SUCCESS, + PENDING, + FAILED, + } + + /** + * An enum containing [AwsAutoTagging]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [AwsAutoTagging] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if + * the SDK is on an older version than the API, then the API may respond with new + * members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + SUCCESS, + PENDING, + FAILED, + /** + * An enum member indicating that [AwsAutoTagging] was instantiated with an unknown + * value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you + * want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + SUCCESS -> Value.SUCCESS + PENDING -> Value.PENDING + FAILED -> Value.FAILED + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and + * don't want to throw for the unknown case. + * + * @throws ImageKitInvalidDataException if this class instance's value is a not a known + * member. + */ + fun known(): Known = + when (this) { + SUCCESS -> Known.SUCCESS + PENDING -> Known.PENDING + FAILED -> Known.FAILED + else -> throw ImageKitInvalidDataException("Unknown AwsAutoTagging: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for + * debugging and generally doesn't throw. + * + * @throws ImageKitInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + ImageKitInvalidDataException("Value is not a String") + } + + private var validated: Boolean = false + + fun validate(): AwsAutoTagging = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is AwsAutoTagging && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + class GoogleAutoTagging + @JsonCreator + private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is + * on an older version than the API, then the API may respond with new members that the + * SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val SUCCESS = of("success") + + @JvmField val PENDING = of("pending") + + @JvmField val FAILED = of("failed") + + @JvmStatic fun of(value: String) = GoogleAutoTagging(JsonField.of(value)) + } + + /** An enum containing [GoogleAutoTagging]'s known values. */ + enum class Known { + SUCCESS, + PENDING, + FAILED, + } + + /** + * An enum containing [GoogleAutoTagging]'s known values, as well as an [_UNKNOWN] + * member. + * + * An instance of [GoogleAutoTagging] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if + * the SDK is on an older version than the API, then the API may respond with new + * members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + SUCCESS, + PENDING, + FAILED, + /** + * An enum member indicating that [GoogleAutoTagging] was instantiated with an + * unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you + * want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + SUCCESS -> Value.SUCCESS + PENDING -> Value.PENDING + FAILED -> Value.FAILED + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and + * don't want to throw for the unknown case. + * + * @throws ImageKitInvalidDataException if this class instance's value is a not a known + * member. + */ + fun known(): Known = + when (this) { + SUCCESS -> Known.SUCCESS + PENDING -> Known.PENDING + FAILED -> Known.FAILED + else -> throw ImageKitInvalidDataException("Unknown GoogleAutoTagging: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for + * debugging and generally doesn't throw. + * + * @throws ImageKitInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + ImageKitInvalidDataException("Value is not a String") + } + + private var validated: Boolean = false + + fun validate(): GoogleAutoTagging = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is GoogleAutoTagging && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + class RemoveBg @JsonCreator private constructor(private val value: JsonField) : + Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is + * on an older version than the API, then the API may respond with new members that the + * SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val SUCCESS = of("success") + + @JvmField val PENDING = of("pending") + + @JvmField val FAILED = of("failed") + + @JvmStatic fun of(value: String) = RemoveBg(JsonField.of(value)) + } + + /** An enum containing [RemoveBg]'s known values. */ + enum class Known { + SUCCESS, + PENDING, + FAILED, + } + + /** + * An enum containing [RemoveBg]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [RemoveBg] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if + * the SDK is on an older version than the API, then the API may respond with new + * members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + SUCCESS, + PENDING, + FAILED, + /** + * An enum member indicating that [RemoveBg] was instantiated with an unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you + * want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + SUCCESS -> Value.SUCCESS + PENDING -> Value.PENDING + FAILED -> Value.FAILED + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and + * don't want to throw for the unknown case. + * + * @throws ImageKitInvalidDataException if this class instance's value is a not a known + * member. + */ + fun known(): Known = + when (this) { + SUCCESS -> Known.SUCCESS + PENDING -> Known.PENDING + FAILED -> Known.FAILED + else -> throw ImageKitInvalidDataException("Unknown RemoveBg: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for + * debugging and generally doesn't throw. + * + * @throws ImageKitInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + ImageKitInvalidDataException("Value is not a String") + } + + private var validated: Boolean = false + + fun validate(): RemoveBg = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is RemoveBg && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ExtensionStatus && + aiAutoDescription == other.aiAutoDescription && + awsAutoTagging == other.awsAutoTagging && + googleAutoTagging == other.googleAutoTagging && + removeBg == other.removeBg && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + aiAutoDescription, + awsAutoTagging, + googleAutoTagging, + removeBg, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ExtensionStatus{aiAutoDescription=$aiAutoDescription, awsAutoTagging=$awsAutoTagging, googleAutoTagging=$googleAutoTagging, removeBg=$removeBg, additionalProperties=$additionalProperties}" + } + + /** An object containing the file or file version's `id` (versionId) and `name`. */ + class VersionInfo + private constructor( + private val id: JsonField, + private val name: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + ) : this(id, name, mutableMapOf()) + + /** + * Unique identifier of the file version. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun id(): Optional = id.getOptional("id") + + /** + * Name of the file version. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun name(): Optional = name.getOptional("name") + + /** + * Returns the raw JSON value of [id]. + * + * Unlike [id], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [VersionInfo]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [VersionInfo]. */ + class Builder internal constructor() { + + private var id: JsonField = JsonMissing.of() + private var name: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(versionInfo: VersionInfo) = apply { + id = versionInfo.id + name = versionInfo.name + additionalProperties = versionInfo.additionalProperties.toMutableMap() + } + + /** Unique identifier of the file version. */ + fun id(id: String) = id(JsonField.of(id)) + + /** + * Sets [Builder.id] to an arbitrary JSON value. + * + * You should usually call [Builder.id] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun id(id: JsonField) = apply { this.id = id } + + /** Name of the file version. */ + fun name(name: String) = name(JsonField.of(name)) + + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun name(name: JsonField) = apply { this.name = name } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [VersionInfo]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): VersionInfo = VersionInfo(id, name, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): VersionInfo = apply { + if (validated) { + return@apply + } + + id() + name() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (id.asKnown().isPresent) 1 else 0) + (if (name.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is VersionInfo && + id == other.id && + name == other.name && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(id, name, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "VersionInfo{id=$id, name=$name, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is FileUploadResponse && + aiTags == other.aiTags && + audioCodec == other.audioCodec && + bitRate == other.bitRate && + customCoordinates == other.customCoordinates && + customMetadata == other.customMetadata && + description == other.description && + duration == other.duration && + embeddedMetadata == other.embeddedMetadata && + extensionStatus == other.extensionStatus && + fileId == other.fileId && + filePath == other.filePath && + fileType == other.fileType && + height == other.height && + isPrivateFile == other.isPrivateFile && + isPublished == other.isPublished && + metadata == other.metadata && + name == other.name && + size == other.size && + tags == other.tags && + thumbnailUrl == other.thumbnailUrl && + url == other.url && + versionInfo == other.versionInfo && + videoCodec == other.videoCodec && + width == other.width && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + aiTags, + audioCodec, + bitRate, + customCoordinates, + customMetadata, + description, + duration, + embeddedMetadata, + extensionStatus, + fileId, + filePath, + fileType, + height, + isPrivateFile, + isPublished, + metadata, + name, + size, + tags, + thumbnailUrl, + url, + versionInfo, + videoCodec, + width, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "FileUploadResponse{aiTags=$aiTags, audioCodec=$audioCodec, bitRate=$bitRate, customCoordinates=$customCoordinates, customMetadata=$customMetadata, description=$description, duration=$duration, embeddedMetadata=$embeddedMetadata, extensionStatus=$extensionStatus, fileId=$fileId, filePath=$filePath, fileType=$fileType, height=$height, isPrivateFile=$isPrivateFile, isPublished=$isPublished, metadata=$metadata, name=$name, size=$size, tags=$tags, thumbnailUrl=$thumbnailUrl, url=$url, versionInfo=$versionInfo, videoCodec=$videoCodec, width=$width, additionalProperties=$additionalProperties}" +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/cache/invalidation/InvalidationCreateParams.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/cache/invalidation/InvalidationCreateParams.kt new file mode 100644 index 0000000..1fe6f16 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/cache/invalidation/InvalidationCreateParams.kt @@ -0,0 +1,415 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.cache.invalidation + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.imagekit.api.core.ExcludeMissing +import com.imagekit.api.core.JsonField +import com.imagekit.api.core.JsonMissing +import com.imagekit.api.core.JsonValue +import com.imagekit.api.core.Params +import com.imagekit.api.core.checkRequired +import com.imagekit.api.core.http.Headers +import com.imagekit.api.core.http.QueryParams +import com.imagekit.api.errors.ImageKitInvalidDataException +import java.util.Collections +import java.util.Objects + +/** + * This API will purge CDN cache and ImageKit.io's internal cache for a file. Note: Purge cache is + * an asynchronous process and it may take some time to reflect the changes. + */ +class InvalidationCreateParams +private constructor( + private val body: Body, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** + * The full URL of the file to be purged. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun url(): String = body.url() + + /** + * Returns the raw JSON value of [url]. + * + * Unlike [url], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _url(): JsonField = body._url() + + fun _additionalBodyProperties(): Map = body._additionalProperties() + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [InvalidationCreateParams]. + * + * The following fields are required: + * ```java + * .url() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [InvalidationCreateParams]. */ + class Builder internal constructor() { + + private var body: Body.Builder = Body.builder() + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + + @JvmSynthetic + internal fun from(invalidationCreateParams: InvalidationCreateParams) = apply { + body = invalidationCreateParams.body.toBuilder() + additionalHeaders = invalidationCreateParams.additionalHeaders.toBuilder() + additionalQueryParams = invalidationCreateParams.additionalQueryParams.toBuilder() + } + + /** + * Sets the entire request body. + * + * This is generally only useful if you are already constructing the body separately. + * Otherwise, it's more convenient to use the top-level setters instead: + * - [url] + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } + + /** The full URL of the file to be purged. */ + fun url(url: String) = apply { body.url(url) } + + /** + * Sets [Builder.url] to an arbitrary JSON value. + * + * You should usually call [Builder.url] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun url(url: JsonField) = apply { body.url(url) } + + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + body.additionalProperties(additionalBodyProperties) + } + + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + body.putAdditionalProperty(key, value) + } + + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + body.putAllAdditionalProperties(additionalBodyProperties) + } + + fun removeAdditionalBodyProperty(key: String) = apply { body.removeAdditionalProperty(key) } + + fun removeAllAdditionalBodyProperties(keys: Set) = apply { + body.removeAllAdditionalProperties(keys) + } + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + /** + * Returns an immutable instance of [InvalidationCreateParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .url() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): InvalidationCreateParams = + InvalidationCreateParams( + body.build(), + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } + + fun _body(): Body = body + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + class Body + private constructor( + private val url: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("url") @ExcludeMissing url: JsonField = JsonMissing.of() + ) : this(url, mutableMapOf()) + + /** + * The full URL of the file to be purged. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun url(): String = url.getRequired("url") + + /** + * Returns the raw JSON value of [url]. + * + * Unlike [url], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("url") @ExcludeMissing fun _url(): JsonField = url + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Body]. + * + * The following fields are required: + * ```java + * .url() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Body]. */ + class Builder internal constructor() { + + private var url: JsonField? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(body: Body) = apply { + url = body.url + additionalProperties = body.additionalProperties.toMutableMap() + } + + /** The full URL of the file to be purged. */ + fun url(url: String) = url(JsonField.of(url)) + + /** + * Sets [Builder.url] to an arbitrary JSON value. + * + * You should usually call [Builder.url] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun url(url: JsonField) = apply { this.url = url } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Body]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .url() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Body = Body(checkRequired("url", url), additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Body = apply { + if (validated) { + return@apply + } + + url() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = (if (url.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Body && + url == other.url && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(url, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "Body{url=$url, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is InvalidationCreateParams && + body == other.body && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = Objects.hash(body, additionalHeaders, additionalQueryParams) + + override fun toString() = + "InvalidationCreateParams{body=$body, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/cache/invalidation/InvalidationCreateResponse.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/cache/invalidation/InvalidationCreateResponse.kt new file mode 100644 index 0000000..51e74c5 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/cache/invalidation/InvalidationCreateResponse.kt @@ -0,0 +1,162 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.cache.invalidation + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.imagekit.api.core.ExcludeMissing +import com.imagekit.api.core.JsonField +import com.imagekit.api.core.JsonMissing +import com.imagekit.api.core.JsonValue +import com.imagekit.api.errors.ImageKitInvalidDataException +import java.util.Collections +import java.util.Objects +import java.util.Optional + +class InvalidationCreateResponse +private constructor( + private val requestId: JsonField, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("requestId") @ExcludeMissing requestId: JsonField = JsonMissing.of() + ) : this(requestId, mutableMapOf()) + + /** + * Unique identifier of the purge request. This can be used to check the status of the purge + * request. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun requestId(): Optional = requestId.getOptional("requestId") + + /** + * Returns the raw JSON value of [requestId]. + * + * Unlike [requestId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("requestId") @ExcludeMissing fun _requestId(): JsonField = requestId + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [InvalidationCreateResponse]. + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [InvalidationCreateResponse]. */ + class Builder internal constructor() { + + private var requestId: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(invalidationCreateResponse: InvalidationCreateResponse) = apply { + requestId = invalidationCreateResponse.requestId + additionalProperties = invalidationCreateResponse.additionalProperties.toMutableMap() + } + + /** + * Unique identifier of the purge request. This can be used to check the status of the purge + * request. + */ + fun requestId(requestId: String) = requestId(JsonField.of(requestId)) + + /** + * Sets [Builder.requestId] to an arbitrary JSON value. + * + * You should usually call [Builder.requestId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun requestId(requestId: JsonField) = apply { this.requestId = requestId } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [InvalidationCreateResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): InvalidationCreateResponse = + InvalidationCreateResponse(requestId, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): InvalidationCreateResponse = apply { + if (validated) { + return@apply + } + + requestId() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = (if (requestId.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is InvalidationCreateResponse && + requestId == other.requestId && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(requestId, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "InvalidationCreateResponse{requestId=$requestId, additionalProperties=$additionalProperties}" +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/cache/invalidation/InvalidationGetParams.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/cache/invalidation/InvalidationGetParams.kt new file mode 100644 index 0000000..38accc7 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/cache/invalidation/InvalidationGetParams.kt @@ -0,0 +1,193 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.cache.invalidation + +import com.imagekit.api.core.Params +import com.imagekit.api.core.http.Headers +import com.imagekit.api.core.http.QueryParams +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** This API returns the status of a purge cache request. */ +class InvalidationGetParams +private constructor( + private val requestId: String?, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + fun requestId(): Optional = Optional.ofNullable(requestId) + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun none(): InvalidationGetParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [InvalidationGetParams]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [InvalidationGetParams]. */ + class Builder internal constructor() { + + private var requestId: String? = null + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + + @JvmSynthetic + internal fun from(invalidationGetParams: InvalidationGetParams) = apply { + requestId = invalidationGetParams.requestId + additionalHeaders = invalidationGetParams.additionalHeaders.toBuilder() + additionalQueryParams = invalidationGetParams.additionalQueryParams.toBuilder() + } + + fun requestId(requestId: String?) = apply { this.requestId = requestId } + + /** Alias for calling [Builder.requestId] with `requestId.orElse(null)`. */ + fun requestId(requestId: Optional) = requestId(requestId.getOrNull()) + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + /** + * Returns an immutable instance of [InvalidationGetParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): InvalidationGetParams = + InvalidationGetParams( + requestId, + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } + + fun _pathParam(index: Int): String = + when (index) { + 0 -> requestId ?: "" + else -> "" + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is InvalidationGetParams && + requestId == other.requestId && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = Objects.hash(requestId, additionalHeaders, additionalQueryParams) + + override fun toString() = + "InvalidationGetParams{requestId=$requestId, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/cache/invalidation/InvalidationGetResponse.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/cache/invalidation/InvalidationGetResponse.kt new file mode 100644 index 0000000..74befb5 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/cache/invalidation/InvalidationGetResponse.kt @@ -0,0 +1,285 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.cache.invalidation + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.imagekit.api.core.Enum +import com.imagekit.api.core.ExcludeMissing +import com.imagekit.api.core.JsonField +import com.imagekit.api.core.JsonMissing +import com.imagekit.api.core.JsonValue +import com.imagekit.api.errors.ImageKitInvalidDataException +import java.util.Collections +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +class InvalidationGetResponse +private constructor( + private val status: JsonField, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("status") @ExcludeMissing status: JsonField = JsonMissing.of() + ) : this(status, mutableMapOf()) + + /** + * Status of the purge request. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun status(): Optional = status.getOptional("status") + + /** + * Returns the raw JSON value of [status]. + * + * Unlike [status], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("status") @ExcludeMissing fun _status(): JsonField = status + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [InvalidationGetResponse]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [InvalidationGetResponse]. */ + class Builder internal constructor() { + + private var status: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(invalidationGetResponse: InvalidationGetResponse) = apply { + status = invalidationGetResponse.status + additionalProperties = invalidationGetResponse.additionalProperties.toMutableMap() + } + + /** Status of the purge request. */ + fun status(status: Status) = status(JsonField.of(status)) + + /** + * Sets [Builder.status] to an arbitrary JSON value. + * + * You should usually call [Builder.status] with a well-typed [Status] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun status(status: JsonField) = apply { this.status = status } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [InvalidationGetResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): InvalidationGetResponse = + InvalidationGetResponse(status, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): InvalidationGetResponse = apply { + if (validated) { + return@apply + } + + status().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = (status.asKnown().getOrNull()?.validity() ?: 0) + + /** Status of the purge request. */ + class Status @JsonCreator private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is on an + * older version than the API, then the API may respond with new members that the SDK is + * unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val PENDING = of("Pending") + + @JvmField val COMPLETED = of("Completed") + + @JvmStatic fun of(value: String) = Status(JsonField.of(value)) + } + + /** An enum containing [Status]'s known values. */ + enum class Known { + PENDING, + COMPLETED, + } + + /** + * An enum containing [Status]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [Status] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if the + * SDK is on an older version than the API, then the API may respond with new members that + * the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + PENDING, + COMPLETED, + /** An enum member indicating that [Status] was instantiated with an unknown value. */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] + * if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you want + * to throw for the unknown case. + */ + fun value(): Value = + when (this) { + PENDING -> Value.PENDING + COMPLETED -> Value.COMPLETED + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and don't + * want to throw for the unknown case. + * + * @throws ImageKitInvalidDataException if this class instance's value is a not a known + * member. + */ + fun known(): Known = + when (this) { + PENDING -> Known.PENDING + COMPLETED -> Known.COMPLETED + else -> throw ImageKitInvalidDataException("Unknown Status: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for debugging + * and generally doesn't throw. + * + * @throws ImageKitInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + ImageKitInvalidDataException("Value is not a String") + } + + private var validated: Boolean = false + + fun validate(): Status = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Status && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is InvalidationGetResponse && + status == other.status && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(status, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "InvalidationGetResponse{status=$status, additionalProperties=$additionalProperties}" +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/custommetadatafields/CustomMetadataField.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/custommetadatafields/CustomMetadataField.kt new file mode 100644 index 0000000..f69779f --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/custommetadatafields/CustomMetadataField.kt @@ -0,0 +1,1986 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.custommetadatafields + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.fasterxml.jackson.core.JsonGenerator +import com.fasterxml.jackson.core.ObjectCodec +import com.fasterxml.jackson.databind.JsonNode +import com.fasterxml.jackson.databind.SerializerProvider +import com.fasterxml.jackson.databind.annotation.JsonDeserialize +import com.fasterxml.jackson.databind.annotation.JsonSerialize +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.imagekit.api.core.BaseDeserializer +import com.imagekit.api.core.BaseSerializer +import com.imagekit.api.core.Enum +import com.imagekit.api.core.ExcludeMissing +import com.imagekit.api.core.JsonField +import com.imagekit.api.core.JsonMissing +import com.imagekit.api.core.JsonValue +import com.imagekit.api.core.allMaxBy +import com.imagekit.api.core.checkKnown +import com.imagekit.api.core.checkRequired +import com.imagekit.api.core.getOrThrow +import com.imagekit.api.core.toImmutable +import com.imagekit.api.errors.ImageKitInvalidDataException +import java.util.Collections +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** Object containing details of a custom metadata field. */ +class CustomMetadataField +private constructor( + private val id: JsonField, + private val label: JsonField, + private val name: JsonField, + private val schema: JsonField, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), + @JsonProperty("label") @ExcludeMissing label: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("schema") @ExcludeMissing schema: JsonField = JsonMissing.of(), + ) : this(id, label, name, schema, mutableMapOf()) + + /** + * Unique identifier for the custom metadata field. Use this to update the field. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun id(): String = id.getRequired("id") + + /** + * Human readable name of the custom metadata field. This name is displayed as form field label + * to the users while setting field value on the asset in the media library UI. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun label(): String = label.getRequired("label") + + /** + * API name of the custom metadata field. This becomes the key while setting `customMetadata` + * (key-value object) for an asset using upload or update API. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun name(): String = name.getRequired("name") + + /** + * An object that describes the rules for the custom metadata field value. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun schema(): Schema = schema.getRequired("schema") + + /** + * Returns the raw JSON value of [id]. + * + * Unlike [id], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id + + /** + * Returns the raw JSON value of [label]. + * + * Unlike [label], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("label") @ExcludeMissing fun _label(): JsonField = label + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + + /** + * Returns the raw JSON value of [schema]. + * + * Unlike [schema], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("schema") @ExcludeMissing fun _schema(): JsonField = schema + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [CustomMetadataField]. + * + * The following fields are required: + * ```java + * .id() + * .label() + * .name() + * .schema() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [CustomMetadataField]. */ + class Builder internal constructor() { + + private var id: JsonField? = null + private var label: JsonField? = null + private var name: JsonField? = null + private var schema: JsonField? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(customMetadataField: CustomMetadataField) = apply { + id = customMetadataField.id + label = customMetadataField.label + name = customMetadataField.name + schema = customMetadataField.schema + additionalProperties = customMetadataField.additionalProperties.toMutableMap() + } + + /** Unique identifier for the custom metadata field. Use this to update the field. */ + fun id(id: String) = id(JsonField.of(id)) + + /** + * Sets [Builder.id] to an arbitrary JSON value. + * + * You should usually call [Builder.id] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun id(id: JsonField) = apply { this.id = id } + + /** + * Human readable name of the custom metadata field. This name is displayed as form field + * label to the users while setting field value on the asset in the media library UI. + */ + fun label(label: String) = label(JsonField.of(label)) + + /** + * Sets [Builder.label] to an arbitrary JSON value. + * + * You should usually call [Builder.label] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun label(label: JsonField) = apply { this.label = label } + + /** + * API name of the custom metadata field. This becomes the key while setting + * `customMetadata` (key-value object) for an asset using upload or update API. + */ + fun name(name: String) = name(JsonField.of(name)) + + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun name(name: JsonField) = apply { this.name = name } + + /** An object that describes the rules for the custom metadata field value. */ + fun schema(schema: Schema) = schema(JsonField.of(schema)) + + /** + * Sets [Builder.schema] to an arbitrary JSON value. + * + * You should usually call [Builder.schema] with a well-typed [Schema] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun schema(schema: JsonField) = apply { this.schema = schema } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [CustomMetadataField]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .id() + * .label() + * .name() + * .schema() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): CustomMetadataField = + CustomMetadataField( + checkRequired("id", id), + checkRequired("label", label), + checkRequired("name", name), + checkRequired("schema", schema), + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): CustomMetadataField = apply { + if (validated) { + return@apply + } + + id() + label() + name() + schema().validate() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (id.asKnown().isPresent) 1 else 0) + + (if (label.asKnown().isPresent) 1 else 0) + + (if (name.asKnown().isPresent) 1 else 0) + + (schema.asKnown().getOrNull()?.validity() ?: 0) + + /** An object that describes the rules for the custom metadata field value. */ + class Schema + private constructor( + private val type: JsonField, + private val defaultValue: JsonField, + private val isValueRequired: JsonField, + private val maxLength: JsonField, + private val maxValue: JsonField, + private val minLength: JsonField, + private val minValue: JsonField, + private val selectOptions: JsonField>, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("type") @ExcludeMissing type: JsonField = JsonMissing.of(), + @JsonProperty("defaultValue") + @ExcludeMissing + defaultValue: JsonField = JsonMissing.of(), + @JsonProperty("isValueRequired") + @ExcludeMissing + isValueRequired: JsonField = JsonMissing.of(), + @JsonProperty("maxLength") + @ExcludeMissing + maxLength: JsonField = JsonMissing.of(), + @JsonProperty("maxValue") + @ExcludeMissing + maxValue: JsonField = JsonMissing.of(), + @JsonProperty("minLength") + @ExcludeMissing + minLength: JsonField = JsonMissing.of(), + @JsonProperty("minValue") + @ExcludeMissing + minValue: JsonField = JsonMissing.of(), + @JsonProperty("selectOptions") + @ExcludeMissing + selectOptions: JsonField> = JsonMissing.of(), + ) : this( + type, + defaultValue, + isValueRequired, + maxLength, + maxValue, + minLength, + minValue, + selectOptions, + mutableMapOf(), + ) + + /** + * Type of the custom metadata field. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun type(): Type = type.getRequired("type") + + /** + * The default value for this custom metadata field. Date type of default value depends on + * the field type. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun defaultValue(): Optional = defaultValue.getOptional("defaultValue") + + /** + * Specifies if the this custom metadata field is required or not. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun isValueRequired(): Optional = isValueRequired.getOptional("isValueRequired") + + /** + * Maximum length of string. Only set if `type` is set to `Text` or `Textarea`. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun maxLength(): Optional = maxLength.getOptional("maxLength") + + /** + * Maximum value of the field. Only set if field type is `Date` or `Number`. For `Date` type + * field, the value will be in ISO8601 string format. For `Number` type field, it will be a + * numeric value. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun maxValue(): Optional = maxValue.getOptional("maxValue") + + /** + * Minimum length of string. Only set if `type` is set to `Text` or `Textarea`. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun minLength(): Optional = minLength.getOptional("minLength") + + /** + * Minimum value of the field. Only set if field type is `Date` or `Number`. For `Date` type + * field, the value will be in ISO8601 string format. For `Number` type field, it will be a + * numeric value. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun minValue(): Optional = minValue.getOptional("minValue") + + /** + * An array of allowed values when field type is `SingleSelect` or `MultiSelect`. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun selectOptions(): Optional> = + selectOptions.getOptional("selectOptions") + + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + + /** + * Returns the raw JSON value of [defaultValue]. + * + * Unlike [defaultValue], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("defaultValue") + @ExcludeMissing + fun _defaultValue(): JsonField = defaultValue + + /** + * Returns the raw JSON value of [isValueRequired]. + * + * Unlike [isValueRequired], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("isValueRequired") + @ExcludeMissing + fun _isValueRequired(): JsonField = isValueRequired + + /** + * Returns the raw JSON value of [maxLength]. + * + * Unlike [maxLength], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("maxLength") @ExcludeMissing fun _maxLength(): JsonField = maxLength + + /** + * Returns the raw JSON value of [maxValue]. + * + * Unlike [maxValue], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("maxValue") @ExcludeMissing fun _maxValue(): JsonField = maxValue + + /** + * Returns the raw JSON value of [minLength]. + * + * Unlike [minLength], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("minLength") @ExcludeMissing fun _minLength(): JsonField = minLength + + /** + * Returns the raw JSON value of [minValue]. + * + * Unlike [minValue], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("minValue") @ExcludeMissing fun _minValue(): JsonField = minValue + + /** + * Returns the raw JSON value of [selectOptions]. + * + * Unlike [selectOptions], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("selectOptions") + @ExcludeMissing + fun _selectOptions(): JsonField> = selectOptions + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Schema]. + * + * The following fields are required: + * ```java + * .type() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Schema]. */ + class Builder internal constructor() { + + private var type: JsonField? = null + private var defaultValue: JsonField = JsonMissing.of() + private var isValueRequired: JsonField = JsonMissing.of() + private var maxLength: JsonField = JsonMissing.of() + private var maxValue: JsonField = JsonMissing.of() + private var minLength: JsonField = JsonMissing.of() + private var minValue: JsonField = JsonMissing.of() + private var selectOptions: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(schema: Schema) = apply { + type = schema.type + defaultValue = schema.defaultValue + isValueRequired = schema.isValueRequired + maxLength = schema.maxLength + maxValue = schema.maxValue + minLength = schema.minLength + minValue = schema.minValue + selectOptions = schema.selectOptions.map { it.toMutableList() } + additionalProperties = schema.additionalProperties.toMutableMap() + } + + /** Type of the custom metadata field. */ + fun type(type: Type) = type(JsonField.of(type)) + + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [Type] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun type(type: JsonField) = apply { this.type = type } + + /** + * The default value for this custom metadata field. Date type of default value depends + * on the field type. + */ + fun defaultValue(defaultValue: DefaultValue) = defaultValue(JsonField.of(defaultValue)) + + /** + * Sets [Builder.defaultValue] to an arbitrary JSON value. + * + * You should usually call [Builder.defaultValue] with a well-typed [DefaultValue] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun defaultValue(defaultValue: JsonField) = apply { + this.defaultValue = defaultValue + } + + /** Alias for calling [defaultValue] with `DefaultValue.ofString(string)`. */ + fun defaultValue(string: String) = defaultValue(DefaultValue.ofString(string)) + + /** Alias for calling [defaultValue] with `DefaultValue.ofNumber(number)`. */ + fun defaultValue(number: Double) = defaultValue(DefaultValue.ofNumber(number)) + + /** Alias for calling [defaultValue] with `DefaultValue.ofBool(bool)`. */ + fun defaultValue(bool: Boolean) = defaultValue(DefaultValue.ofBool(bool)) + + /** Alias for calling [defaultValue] with `DefaultValue.ofMixed(mixed)`. */ + fun defaultValueOfMixed(mixed: List) = + defaultValue(DefaultValue.ofMixed(mixed)) + + /** Specifies if the this custom metadata field is required or not. */ + fun isValueRequired(isValueRequired: Boolean) = + isValueRequired(JsonField.of(isValueRequired)) + + /** + * Sets [Builder.isValueRequired] to an arbitrary JSON value. + * + * You should usually call [Builder.isValueRequired] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun isValueRequired(isValueRequired: JsonField) = apply { + this.isValueRequired = isValueRequired + } + + /** Maximum length of string. Only set if `type` is set to `Text` or `Textarea`. */ + fun maxLength(maxLength: Double) = maxLength(JsonField.of(maxLength)) + + /** + * Sets [Builder.maxLength] to an arbitrary JSON value. + * + * You should usually call [Builder.maxLength] with a well-typed [Double] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun maxLength(maxLength: JsonField) = apply { this.maxLength = maxLength } + + /** + * Maximum value of the field. Only set if field type is `Date` or `Number`. For `Date` + * type field, the value will be in ISO8601 string format. For `Number` type field, it + * will be a numeric value. + */ + fun maxValue(maxValue: MaxValue) = maxValue(JsonField.of(maxValue)) + + /** + * Sets [Builder.maxValue] to an arbitrary JSON value. + * + * You should usually call [Builder.maxValue] with a well-typed [MaxValue] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun maxValue(maxValue: JsonField) = apply { this.maxValue = maxValue } + + /** Alias for calling [maxValue] with `MaxValue.ofString(string)`. */ + fun maxValue(string: String) = maxValue(MaxValue.ofString(string)) + + /** Alias for calling [maxValue] with `MaxValue.ofNumber(number)`. */ + fun maxValue(number: Double) = maxValue(MaxValue.ofNumber(number)) + + /** Minimum length of string. Only set if `type` is set to `Text` or `Textarea`. */ + fun minLength(minLength: Double) = minLength(JsonField.of(minLength)) + + /** + * Sets [Builder.minLength] to an arbitrary JSON value. + * + * You should usually call [Builder.minLength] with a well-typed [Double] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun minLength(minLength: JsonField) = apply { this.minLength = minLength } + + /** + * Minimum value of the field. Only set if field type is `Date` or `Number`. For `Date` + * type field, the value will be in ISO8601 string format. For `Number` type field, it + * will be a numeric value. + */ + fun minValue(minValue: MinValue) = minValue(JsonField.of(minValue)) + + /** + * Sets [Builder.minValue] to an arbitrary JSON value. + * + * You should usually call [Builder.minValue] with a well-typed [MinValue] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun minValue(minValue: JsonField) = apply { this.minValue = minValue } + + /** Alias for calling [minValue] with `MinValue.ofString(string)`. */ + fun minValue(string: String) = minValue(MinValue.ofString(string)) + + /** Alias for calling [minValue] with `MinValue.ofNumber(number)`. */ + fun minValue(number: Double) = minValue(MinValue.ofNumber(number)) + + /** An array of allowed values when field type is `SingleSelect` or `MultiSelect`. */ + fun selectOptions(selectOptions: List) = + selectOptions(JsonField.of(selectOptions)) + + /** + * Sets [Builder.selectOptions] to an arbitrary JSON value. + * + * You should usually call [Builder.selectOptions] with a well-typed + * `List` value instead. This method is primarily for setting the field to + * an undocumented or not yet supported value. + */ + fun selectOptions(selectOptions: JsonField>) = apply { + this.selectOptions = selectOptions.map { it.toMutableList() } + } + + /** + * Adds a single [SelectOption] to [selectOptions]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addSelectOption(selectOption: SelectOption) = apply { + selectOptions = + (selectOptions ?: JsonField.of(mutableListOf())).also { + checkKnown("selectOptions", it).add(selectOption) + } + } + + /** Alias for calling [addSelectOption] with `SelectOption.ofString(string)`. */ + fun addSelectOption(string: String) = addSelectOption(SelectOption.ofString(string)) + + /** Alias for calling [addSelectOption] with `SelectOption.ofNumber(number)`. */ + fun addSelectOption(number: Double) = addSelectOption(SelectOption.ofNumber(number)) + + /** Alias for calling [addSelectOption] with `SelectOption.ofBool(bool)`. */ + fun addSelectOption(bool: Boolean) = addSelectOption(SelectOption.ofBool(bool)) + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Schema]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .type() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Schema = + Schema( + checkRequired("type", type), + defaultValue, + isValueRequired, + maxLength, + maxValue, + minLength, + minValue, + (selectOptions ?: JsonMissing.of()).map { it.toImmutable() }, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Schema = apply { + if (validated) { + return@apply + } + + type().validate() + defaultValue().ifPresent { it.validate() } + isValueRequired() + maxLength() + maxValue().ifPresent { it.validate() } + minLength() + minValue().ifPresent { it.validate() } + selectOptions().ifPresent { it.forEach { it.validate() } } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (type.asKnown().getOrNull()?.validity() ?: 0) + + (defaultValue.asKnown().getOrNull()?.validity() ?: 0) + + (if (isValueRequired.asKnown().isPresent) 1 else 0) + + (if (maxLength.asKnown().isPresent) 1 else 0) + + (maxValue.asKnown().getOrNull()?.validity() ?: 0) + + (if (minLength.asKnown().isPresent) 1 else 0) + + (minValue.asKnown().getOrNull()?.validity() ?: 0) + + (selectOptions.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + /** Type of the custom metadata field. */ + class Type @JsonCreator private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is + * on an older version than the API, then the API may respond with new members that the + * SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val TEXT = of("Text") + + @JvmField val TEXTAREA = of("Textarea") + + @JvmField val NUMBER = of("Number") + + @JvmField val DATE = of("Date") + + @JvmField val BOOLEAN = of("Boolean") + + @JvmField val SINGLE_SELECT = of("SingleSelect") + + @JvmField val MULTI_SELECT = of("MultiSelect") + + @JvmStatic fun of(value: String) = Type(JsonField.of(value)) + } + + /** An enum containing [Type]'s known values. */ + enum class Known { + TEXT, + TEXTAREA, + NUMBER, + DATE, + BOOLEAN, + SINGLE_SELECT, + MULTI_SELECT, + } + + /** + * An enum containing [Type]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [Type] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if + * the SDK is on an older version than the API, then the API may respond with new + * members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + TEXT, + TEXTAREA, + NUMBER, + DATE, + BOOLEAN, + SINGLE_SELECT, + MULTI_SELECT, + /** An enum member indicating that [Type] was instantiated with an unknown value. */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you + * want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + TEXT -> Value.TEXT + TEXTAREA -> Value.TEXTAREA + NUMBER -> Value.NUMBER + DATE -> Value.DATE + BOOLEAN -> Value.BOOLEAN + SINGLE_SELECT -> Value.SINGLE_SELECT + MULTI_SELECT -> Value.MULTI_SELECT + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and + * don't want to throw for the unknown case. + * + * @throws ImageKitInvalidDataException if this class instance's value is a not a known + * member. + */ + fun known(): Known = + when (this) { + TEXT -> Known.TEXT + TEXTAREA -> Known.TEXTAREA + NUMBER -> Known.NUMBER + DATE -> Known.DATE + BOOLEAN -> Known.BOOLEAN + SINGLE_SELECT -> Known.SINGLE_SELECT + MULTI_SELECT -> Known.MULTI_SELECT + else -> throw ImageKitInvalidDataException("Unknown Type: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for + * debugging and generally doesn't throw. + * + * @throws ImageKitInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + ImageKitInvalidDataException("Value is not a String") + } + + private var validated: Boolean = false + + fun validate(): Type = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Type && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + /** + * The default value for this custom metadata field. Date type of default value depends on + * the field type. + */ + @JsonDeserialize(using = DefaultValue.Deserializer::class) + @JsonSerialize(using = DefaultValue.Serializer::class) + class DefaultValue + private constructor( + private val string: String? = null, + private val number: Double? = null, + private val bool: Boolean? = null, + private val mixed: List? = null, + private val _json: JsonValue? = null, + ) { + + fun string(): Optional = Optional.ofNullable(string) + + fun number(): Optional = Optional.ofNullable(number) + + fun bool(): Optional = Optional.ofNullable(bool) + + /** + * Default value should be of type array when custom metadata field type is set to + * `MultiSelect`. + */ + fun mixed(): Optional> = Optional.ofNullable(mixed) + + fun isString(): Boolean = string != null + + fun isNumber(): Boolean = number != null + + fun isBool(): Boolean = bool != null + + fun isMixed(): Boolean = mixed != null + + fun asString(): String = string.getOrThrow("string") + + fun asNumber(): Double = number.getOrThrow("number") + + fun asBool(): Boolean = bool.getOrThrow("bool") + + /** + * Default value should be of type array when custom metadata field type is set to + * `MultiSelect`. + */ + fun asMixed(): List = mixed.getOrThrow("mixed") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + string != null -> visitor.visitString(string) + number != null -> visitor.visitNumber(number) + bool != null -> visitor.visitBool(bool) + mixed != null -> visitor.visitMixed(mixed) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): DefaultValue = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitString(string: String) {} + + override fun visitNumber(number: Double) {} + + override fun visitBool(bool: Boolean) {} + + override fun visitMixed(mixed: List) { + mixed.forEach { it.validate() } + } + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitString(string: String) = 1 + + override fun visitNumber(number: Double) = 1 + + override fun visitBool(bool: Boolean) = 1 + + override fun visitMixed(mixed: List) = + mixed.sumOf { it.validity().toInt() } + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is DefaultValue && + string == other.string && + number == other.number && + bool == other.bool && + mixed == other.mixed + } + + override fun hashCode(): Int = Objects.hash(string, number, bool, mixed) + + override fun toString(): String = + when { + string != null -> "DefaultValue{string=$string}" + number != null -> "DefaultValue{number=$number}" + bool != null -> "DefaultValue{bool=$bool}" + mixed != null -> "DefaultValue{mixed=$mixed}" + _json != null -> "DefaultValue{_unknown=$_json}" + else -> throw IllegalStateException("Invalid DefaultValue") + } + + companion object { + + @JvmStatic fun ofString(string: String) = DefaultValue(string = string) + + @JvmStatic fun ofNumber(number: Double) = DefaultValue(number = number) + + @JvmStatic fun ofBool(bool: Boolean) = DefaultValue(bool = bool) + + /** + * Default value should be of type array when custom metadata field type is set to + * `MultiSelect`. + */ + @JvmStatic + fun ofMixed(mixed: List) = + DefaultValue(mixed = mixed.toImmutable()) + } + + /** + * An interface that defines how to map each variant of [DefaultValue] to a value of + * type [T]. + */ + interface Visitor { + + fun visitString(string: String): T + + fun visitNumber(number: Double): T + + fun visitBool(bool: Boolean): T + + /** + * Default value should be of type array when custom metadata field type is set to + * `MultiSelect`. + */ + fun visitMixed(mixed: List): T + + /** + * Maps an unknown variant of [DefaultValue] to a value of type [T]. + * + * An instance of [DefaultValue] can contain an unknown variant if it was + * deserialized from data that doesn't match any known variant. For example, if the + * SDK is on an older version than the API, then the API may respond with new + * variants that the SDK is unaware of. + * + * @throws ImageKitInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw ImageKitInvalidDataException("Unknown DefaultValue: $json") + } + } + + internal class Deserializer : BaseDeserializer(DefaultValue::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): DefaultValue { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + DefaultValue(string = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + DefaultValue(number = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + DefaultValue(bool = it, _json = json) + }, + tryDeserialize( + node, + jacksonTypeRef>(), + ) + ?.let { DefaultValue(mixed = it, _json = json) }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely incompatible + // with all the possible variants (e.g. deserializing from object). + 0 -> DefaultValue(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then use the + // first completely valid match, or simply the first match if none are + // completely valid. + else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() + } + } + } + + internal class Serializer : BaseSerializer(DefaultValue::class) { + + override fun serialize( + value: DefaultValue, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.string != null -> generator.writeObject(value.string) + value.number != null -> generator.writeObject(value.number) + value.bool != null -> generator.writeObject(value.bool) + value.mixed != null -> generator.writeObject(value.mixed) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid DefaultValue") + } + } + } + + @JsonDeserialize(using = UnnamedSchemaWithArrayParent0.Deserializer::class) + @JsonSerialize(using = UnnamedSchemaWithArrayParent0.Serializer::class) + class UnnamedSchemaWithArrayParent0 + private constructor( + private val string: String? = null, + private val number: Double? = null, + private val bool: Boolean? = null, + private val _json: JsonValue? = null, + ) { + + fun string(): Optional = Optional.ofNullable(string) + + fun number(): Optional = Optional.ofNullable(number) + + fun bool(): Optional = Optional.ofNullable(bool) + + fun isString(): Boolean = string != null + + fun isNumber(): Boolean = number != null + + fun isBool(): Boolean = bool != null + + fun asString(): String = string.getOrThrow("string") + + fun asNumber(): Double = number.getOrThrow("number") + + fun asBool(): Boolean = bool.getOrThrow("bool") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + string != null -> visitor.visitString(string) + number != null -> visitor.visitNumber(number) + bool != null -> visitor.visitBool(bool) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): UnnamedSchemaWithArrayParent0 = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitString(string: String) {} + + override fun visitNumber(number: Double) {} + + override fun visitBool(bool: Boolean) {} + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitString(string: String) = 1 + + override fun visitNumber(number: Double) = 1 + + override fun visitBool(bool: Boolean) = 1 + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is UnnamedSchemaWithArrayParent0 && + string == other.string && + number == other.number && + bool == other.bool + } + + override fun hashCode(): Int = Objects.hash(string, number, bool) + + override fun toString(): String = + when { + string != null -> "UnnamedSchemaWithArrayParent0{string=$string}" + number != null -> "UnnamedSchemaWithArrayParent0{number=$number}" + bool != null -> "UnnamedSchemaWithArrayParent0{bool=$bool}" + _json != null -> "UnnamedSchemaWithArrayParent0{_unknown=$_json}" + else -> throw IllegalStateException("Invalid UnnamedSchemaWithArrayParent0") + } + + companion object { + + @JvmStatic + fun ofString(string: String) = UnnamedSchemaWithArrayParent0(string = string) + + @JvmStatic + fun ofNumber(number: Double) = UnnamedSchemaWithArrayParent0(number = number) + + @JvmStatic + fun ofBool(bool: Boolean) = UnnamedSchemaWithArrayParent0(bool = bool) + } + + /** + * An interface that defines how to map each variant of + * [UnnamedSchemaWithArrayParent0] to a value of type [T]. + */ + interface Visitor { + + fun visitString(string: String): T + + fun visitNumber(number: Double): T + + fun visitBool(bool: Boolean): T + + /** + * Maps an unknown variant of [UnnamedSchemaWithArrayParent0] to a value of type + * [T]. + * + * An instance of [UnnamedSchemaWithArrayParent0] can contain an unknown variant + * if it was deserialized from data that doesn't match any known variant. For + * example, if the SDK is on an older version than the API, then the API may + * respond with new variants that the SDK is unaware of. + * + * @throws ImageKitInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw ImageKitInvalidDataException( + "Unknown UnnamedSchemaWithArrayParent0: $json" + ) + } + } + + internal class Deserializer : + BaseDeserializer( + UnnamedSchemaWithArrayParent0::class + ) { + + override fun ObjectCodec.deserialize( + node: JsonNode + ): UnnamedSchemaWithArrayParent0 { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + UnnamedSchemaWithArrayParent0(string = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + UnnamedSchemaWithArrayParent0(number = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + UnnamedSchemaWithArrayParent0(bool = it, _json = json) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely + // incompatible with all the possible variants (e.g. deserializing from + // object). + 0 -> UnnamedSchemaWithArrayParent0(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then use + // the first completely valid match, or simply the first match if none + // are completely valid. + else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() + } + } + } + + internal class Serializer : + BaseSerializer( + UnnamedSchemaWithArrayParent0::class + ) { + + override fun serialize( + value: UnnamedSchemaWithArrayParent0, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.string != null -> generator.writeObject(value.string) + value.number != null -> generator.writeObject(value.number) + value.bool != null -> generator.writeObject(value.bool) + value._json != null -> generator.writeObject(value._json) + else -> + throw IllegalStateException("Invalid UnnamedSchemaWithArrayParent0") + } + } + } + } + } + + /** + * Maximum value of the field. Only set if field type is `Date` or `Number`. For `Date` type + * field, the value will be in ISO8601 string format. For `Number` type field, it will be a + * numeric value. + */ + @JsonDeserialize(using = MaxValue.Deserializer::class) + @JsonSerialize(using = MaxValue.Serializer::class) + class MaxValue + private constructor( + private val string: String? = null, + private val number: Double? = null, + private val _json: JsonValue? = null, + ) { + + fun string(): Optional = Optional.ofNullable(string) + + fun number(): Optional = Optional.ofNullable(number) + + fun isString(): Boolean = string != null + + fun isNumber(): Boolean = number != null + + fun asString(): String = string.getOrThrow("string") + + fun asNumber(): Double = number.getOrThrow("number") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + string != null -> visitor.visitString(string) + number != null -> visitor.visitNumber(number) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): MaxValue = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitString(string: String) {} + + override fun visitNumber(number: Double) {} + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitString(string: String) = 1 + + override fun visitNumber(number: Double) = 1 + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is MaxValue && string == other.string && number == other.number + } + + override fun hashCode(): Int = Objects.hash(string, number) + + override fun toString(): String = + when { + string != null -> "MaxValue{string=$string}" + number != null -> "MaxValue{number=$number}" + _json != null -> "MaxValue{_unknown=$_json}" + else -> throw IllegalStateException("Invalid MaxValue") + } + + companion object { + + @JvmStatic fun ofString(string: String) = MaxValue(string = string) + + @JvmStatic fun ofNumber(number: Double) = MaxValue(number = number) + } + + /** + * An interface that defines how to map each variant of [MaxValue] to a value of type + * [T]. + */ + interface Visitor { + + fun visitString(string: String): T + + fun visitNumber(number: Double): T + + /** + * Maps an unknown variant of [MaxValue] to a value of type [T]. + * + * An instance of [MaxValue] can contain an unknown variant if it was deserialized + * from data that doesn't match any known variant. For example, if the SDK is on an + * older version than the API, then the API may respond with new variants that the + * SDK is unaware of. + * + * @throws ImageKitInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw ImageKitInvalidDataException("Unknown MaxValue: $json") + } + } + + internal class Deserializer : BaseDeserializer(MaxValue::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): MaxValue { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + MaxValue(string = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + MaxValue(number = it, _json = json) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely incompatible + // with all the possible variants (e.g. deserializing from object). + 0 -> MaxValue(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then use the + // first completely valid match, or simply the first match if none are + // completely valid. + else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() + } + } + } + + internal class Serializer : BaseSerializer(MaxValue::class) { + + override fun serialize( + value: MaxValue, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.string != null -> generator.writeObject(value.string) + value.number != null -> generator.writeObject(value.number) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid MaxValue") + } + } + } + } + + /** + * Minimum value of the field. Only set if field type is `Date` or `Number`. For `Date` type + * field, the value will be in ISO8601 string format. For `Number` type field, it will be a + * numeric value. + */ + @JsonDeserialize(using = MinValue.Deserializer::class) + @JsonSerialize(using = MinValue.Serializer::class) + class MinValue + private constructor( + private val string: String? = null, + private val number: Double? = null, + private val _json: JsonValue? = null, + ) { + + fun string(): Optional = Optional.ofNullable(string) + + fun number(): Optional = Optional.ofNullable(number) + + fun isString(): Boolean = string != null + + fun isNumber(): Boolean = number != null + + fun asString(): String = string.getOrThrow("string") + + fun asNumber(): Double = number.getOrThrow("number") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + string != null -> visitor.visitString(string) + number != null -> visitor.visitNumber(number) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): MinValue = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitString(string: String) {} + + override fun visitNumber(number: Double) {} + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitString(string: String) = 1 + + override fun visitNumber(number: Double) = 1 + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is MinValue && string == other.string && number == other.number + } + + override fun hashCode(): Int = Objects.hash(string, number) + + override fun toString(): String = + when { + string != null -> "MinValue{string=$string}" + number != null -> "MinValue{number=$number}" + _json != null -> "MinValue{_unknown=$_json}" + else -> throw IllegalStateException("Invalid MinValue") + } + + companion object { + + @JvmStatic fun ofString(string: String) = MinValue(string = string) + + @JvmStatic fun ofNumber(number: Double) = MinValue(number = number) + } + + /** + * An interface that defines how to map each variant of [MinValue] to a value of type + * [T]. + */ + interface Visitor { + + fun visitString(string: String): T + + fun visitNumber(number: Double): T + + /** + * Maps an unknown variant of [MinValue] to a value of type [T]. + * + * An instance of [MinValue] can contain an unknown variant if it was deserialized + * from data that doesn't match any known variant. For example, if the SDK is on an + * older version than the API, then the API may respond with new variants that the + * SDK is unaware of. + * + * @throws ImageKitInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw ImageKitInvalidDataException("Unknown MinValue: $json") + } + } + + internal class Deserializer : BaseDeserializer(MinValue::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): MinValue { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + MinValue(string = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + MinValue(number = it, _json = json) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely incompatible + // with all the possible variants (e.g. deserializing from object). + 0 -> MinValue(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then use the + // first completely valid match, or simply the first match if none are + // completely valid. + else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() + } + } + } + + internal class Serializer : BaseSerializer(MinValue::class) { + + override fun serialize( + value: MinValue, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.string != null -> generator.writeObject(value.string) + value.number != null -> generator.writeObject(value.number) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid MinValue") + } + } + } + } + + @JsonDeserialize(using = SelectOption.Deserializer::class) + @JsonSerialize(using = SelectOption.Serializer::class) + class SelectOption + private constructor( + private val string: String? = null, + private val number: Double? = null, + private val bool: Boolean? = null, + private val _json: JsonValue? = null, + ) { + + fun string(): Optional = Optional.ofNullable(string) + + fun number(): Optional = Optional.ofNullable(number) + + fun bool(): Optional = Optional.ofNullable(bool) + + fun isString(): Boolean = string != null + + fun isNumber(): Boolean = number != null + + fun isBool(): Boolean = bool != null + + fun asString(): String = string.getOrThrow("string") + + fun asNumber(): Double = number.getOrThrow("number") + + fun asBool(): Boolean = bool.getOrThrow("bool") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + string != null -> visitor.visitString(string) + number != null -> visitor.visitNumber(number) + bool != null -> visitor.visitBool(bool) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): SelectOption = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitString(string: String) {} + + override fun visitNumber(number: Double) {} + + override fun visitBool(bool: Boolean) {} + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitString(string: String) = 1 + + override fun visitNumber(number: Double) = 1 + + override fun visitBool(bool: Boolean) = 1 + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is SelectOption && + string == other.string && + number == other.number && + bool == other.bool + } + + override fun hashCode(): Int = Objects.hash(string, number, bool) + + override fun toString(): String = + when { + string != null -> "SelectOption{string=$string}" + number != null -> "SelectOption{number=$number}" + bool != null -> "SelectOption{bool=$bool}" + _json != null -> "SelectOption{_unknown=$_json}" + else -> throw IllegalStateException("Invalid SelectOption") + } + + companion object { + + @JvmStatic fun ofString(string: String) = SelectOption(string = string) + + @JvmStatic fun ofNumber(number: Double) = SelectOption(number = number) + + @JvmStatic fun ofBool(bool: Boolean) = SelectOption(bool = bool) + } + + /** + * An interface that defines how to map each variant of [SelectOption] to a value of + * type [T]. + */ + interface Visitor { + + fun visitString(string: String): T + + fun visitNumber(number: Double): T + + fun visitBool(bool: Boolean): T + + /** + * Maps an unknown variant of [SelectOption] to a value of type [T]. + * + * An instance of [SelectOption] can contain an unknown variant if it was + * deserialized from data that doesn't match any known variant. For example, if the + * SDK is on an older version than the API, then the API may respond with new + * variants that the SDK is unaware of. + * + * @throws ImageKitInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw ImageKitInvalidDataException("Unknown SelectOption: $json") + } + } + + internal class Deserializer : BaseDeserializer(SelectOption::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): SelectOption { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + SelectOption(string = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + SelectOption(number = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + SelectOption(bool = it, _json = json) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely incompatible + // with all the possible variants (e.g. deserializing from object). + 0 -> SelectOption(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then use the + // first completely valid match, or simply the first match if none are + // completely valid. + else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() + } + } + } + + internal class Serializer : BaseSerializer(SelectOption::class) { + + override fun serialize( + value: SelectOption, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.string != null -> generator.writeObject(value.string) + value.number != null -> generator.writeObject(value.number) + value.bool != null -> generator.writeObject(value.bool) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid SelectOption") + } + } + } + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Schema && + type == other.type && + defaultValue == other.defaultValue && + isValueRequired == other.isValueRequired && + maxLength == other.maxLength && + maxValue == other.maxValue && + minLength == other.minLength && + minValue == other.minValue && + selectOptions == other.selectOptions && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + type, + defaultValue, + isValueRequired, + maxLength, + maxValue, + minLength, + minValue, + selectOptions, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Schema{type=$type, defaultValue=$defaultValue, isValueRequired=$isValueRequired, maxLength=$maxLength, maxValue=$maxValue, minLength=$minLength, minValue=$minValue, selectOptions=$selectOptions, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is CustomMetadataField && + id == other.id && + label == other.label && + name == other.name && + schema == other.schema && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(id, label, name, schema, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "CustomMetadataField{id=$id, label=$label, name=$name, schema=$schema, additionalProperties=$additionalProperties}" +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/custommetadatafields/CustomMetadataFieldCreateParams.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/custommetadatafields/CustomMetadataFieldCreateParams.kt new file mode 100644 index 0000000..fa4d61f --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/custommetadatafields/CustomMetadataFieldCreateParams.kt @@ -0,0 +1,2288 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.custommetadatafields + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.fasterxml.jackson.core.JsonGenerator +import com.fasterxml.jackson.core.ObjectCodec +import com.fasterxml.jackson.databind.JsonNode +import com.fasterxml.jackson.databind.SerializerProvider +import com.fasterxml.jackson.databind.annotation.JsonDeserialize +import com.fasterxml.jackson.databind.annotation.JsonSerialize +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.imagekit.api.core.BaseDeserializer +import com.imagekit.api.core.BaseSerializer +import com.imagekit.api.core.Enum +import com.imagekit.api.core.ExcludeMissing +import com.imagekit.api.core.JsonField +import com.imagekit.api.core.JsonMissing +import com.imagekit.api.core.JsonValue +import com.imagekit.api.core.Params +import com.imagekit.api.core.allMaxBy +import com.imagekit.api.core.checkKnown +import com.imagekit.api.core.checkRequired +import com.imagekit.api.core.getOrThrow +import com.imagekit.api.core.http.Headers +import com.imagekit.api.core.http.QueryParams +import com.imagekit.api.core.toImmutable +import com.imagekit.api.errors.ImageKitInvalidDataException +import java.util.Collections +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** + * This API creates a new custom metadata field. Once a custom metadata field is created either + * through this API or using the dashboard UI, its value can be set on the assets. The value of a + * field for an asset can be set using the media library UI or programmatically through upload or + * update assets API. + */ +class CustomMetadataFieldCreateParams +private constructor( + private val body: Body, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** + * Human readable name of the custom metadata field. This should be unique across all non + * deleted custom metadata fields. This name is displayed as form field label to the users while + * setting field value on an asset in the media library UI. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun label(): String = body.label() + + /** + * API name of the custom metadata field. This should be unique across all (including deleted) + * custom metadata fields. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun name(): String = body.name() + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun schema(): Schema = body.schema() + + /** + * Returns the raw JSON value of [label]. + * + * Unlike [label], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _label(): JsonField = body._label() + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _name(): JsonField = body._name() + + /** + * Returns the raw JSON value of [schema]. + * + * Unlike [schema], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _schema(): JsonField = body._schema() + + fun _additionalBodyProperties(): Map = body._additionalProperties() + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [CustomMetadataFieldCreateParams]. + * + * The following fields are required: + * ```java + * .label() + * .name() + * .schema() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [CustomMetadataFieldCreateParams]. */ + class Builder internal constructor() { + + private var body: Body.Builder = Body.builder() + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + + @JvmSynthetic + internal fun from(customMetadataFieldCreateParams: CustomMetadataFieldCreateParams) = + apply { + body = customMetadataFieldCreateParams.body.toBuilder() + additionalHeaders = customMetadataFieldCreateParams.additionalHeaders.toBuilder() + additionalQueryParams = + customMetadataFieldCreateParams.additionalQueryParams.toBuilder() + } + + /** + * Sets the entire request body. + * + * This is generally only useful if you are already constructing the body separately. + * Otherwise, it's more convenient to use the top-level setters instead: + * - [label] + * - [name] + * - [schema] + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } + + /** + * Human readable name of the custom metadata field. This should be unique across all non + * deleted custom metadata fields. This name is displayed as form field label to the users + * while setting field value on an asset in the media library UI. + */ + fun label(label: String) = apply { body.label(label) } + + /** + * Sets [Builder.label] to an arbitrary JSON value. + * + * You should usually call [Builder.label] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun label(label: JsonField) = apply { body.label(label) } + + /** + * API name of the custom metadata field. This should be unique across all (including + * deleted) custom metadata fields. + */ + fun name(name: String) = apply { body.name(name) } + + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun name(name: JsonField) = apply { body.name(name) } + + fun schema(schema: Schema) = apply { body.schema(schema) } + + /** + * Sets [Builder.schema] to an arbitrary JSON value. + * + * You should usually call [Builder.schema] with a well-typed [Schema] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun schema(schema: JsonField) = apply { body.schema(schema) } + + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + body.additionalProperties(additionalBodyProperties) + } + + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + body.putAdditionalProperty(key, value) + } + + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + body.putAllAdditionalProperties(additionalBodyProperties) + } + + fun removeAdditionalBodyProperty(key: String) = apply { body.removeAdditionalProperty(key) } + + fun removeAllAdditionalBodyProperties(keys: Set) = apply { + body.removeAllAdditionalProperties(keys) + } + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + /** + * Returns an immutable instance of [CustomMetadataFieldCreateParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .label() + * .name() + * .schema() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): CustomMetadataFieldCreateParams = + CustomMetadataFieldCreateParams( + body.build(), + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } + + fun _body(): Body = body + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + class Body + private constructor( + private val label: JsonField, + private val name: JsonField, + private val schema: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("label") @ExcludeMissing label: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("schema") @ExcludeMissing schema: JsonField = JsonMissing.of(), + ) : this(label, name, schema, mutableMapOf()) + + /** + * Human readable name of the custom metadata field. This should be unique across all non + * deleted custom metadata fields. This name is displayed as form field label to the users + * while setting field value on an asset in the media library UI. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun label(): String = label.getRequired("label") + + /** + * API name of the custom metadata field. This should be unique across all (including + * deleted) custom metadata fields. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun name(): String = name.getRequired("name") + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun schema(): Schema = schema.getRequired("schema") + + /** + * Returns the raw JSON value of [label]. + * + * Unlike [label], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("label") @ExcludeMissing fun _label(): JsonField = label + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + + /** + * Returns the raw JSON value of [schema]. + * + * Unlike [schema], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("schema") @ExcludeMissing fun _schema(): JsonField = schema + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Body]. + * + * The following fields are required: + * ```java + * .label() + * .name() + * .schema() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Body]. */ + class Builder internal constructor() { + + private var label: JsonField? = null + private var name: JsonField? = null + private var schema: JsonField? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(body: Body) = apply { + label = body.label + name = body.name + schema = body.schema + additionalProperties = body.additionalProperties.toMutableMap() + } + + /** + * Human readable name of the custom metadata field. This should be unique across all + * non deleted custom metadata fields. This name is displayed as form field label to the + * users while setting field value on an asset in the media library UI. + */ + fun label(label: String) = label(JsonField.of(label)) + + /** + * Sets [Builder.label] to an arbitrary JSON value. + * + * You should usually call [Builder.label] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun label(label: JsonField) = apply { this.label = label } + + /** + * API name of the custom metadata field. This should be unique across all (including + * deleted) custom metadata fields. + */ + fun name(name: String) = name(JsonField.of(name)) + + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun name(name: JsonField) = apply { this.name = name } + + fun schema(schema: Schema) = schema(JsonField.of(schema)) + + /** + * Sets [Builder.schema] to an arbitrary JSON value. + * + * You should usually call [Builder.schema] with a well-typed [Schema] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun schema(schema: JsonField) = apply { this.schema = schema } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Body]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .label() + * .name() + * .schema() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Body = + Body( + checkRequired("label", label), + checkRequired("name", name), + checkRequired("schema", schema), + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Body = apply { + if (validated) { + return@apply + } + + label() + name() + schema().validate() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (label.asKnown().isPresent) 1 else 0) + + (if (name.asKnown().isPresent) 1 else 0) + + (schema.asKnown().getOrNull()?.validity() ?: 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Body && + label == other.label && + name == other.name && + schema == other.schema && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(label, name, schema, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Body{label=$label, name=$name, schema=$schema, additionalProperties=$additionalProperties}" + } + + class Schema + private constructor( + private val type: JsonField, + private val defaultValue: JsonField, + private val isValueRequired: JsonField, + private val maxLength: JsonField, + private val maxValue: JsonField, + private val minLength: JsonField, + private val minValue: JsonField, + private val selectOptions: JsonField>, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("type") @ExcludeMissing type: JsonField = JsonMissing.of(), + @JsonProperty("defaultValue") + @ExcludeMissing + defaultValue: JsonField = JsonMissing.of(), + @JsonProperty("isValueRequired") + @ExcludeMissing + isValueRequired: JsonField = JsonMissing.of(), + @JsonProperty("maxLength") + @ExcludeMissing + maxLength: JsonField = JsonMissing.of(), + @JsonProperty("maxValue") + @ExcludeMissing + maxValue: JsonField = JsonMissing.of(), + @JsonProperty("minLength") + @ExcludeMissing + minLength: JsonField = JsonMissing.of(), + @JsonProperty("minValue") + @ExcludeMissing + minValue: JsonField = JsonMissing.of(), + @JsonProperty("selectOptions") + @ExcludeMissing + selectOptions: JsonField> = JsonMissing.of(), + ) : this( + type, + defaultValue, + isValueRequired, + maxLength, + maxValue, + minLength, + minValue, + selectOptions, + mutableMapOf(), + ) + + /** + * Type of the custom metadata field. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun type(): Type = type.getRequired("type") + + /** + * The default value for this custom metadata field. This property is only required if + * `isValueRequired` property is set to `true`. The value should match the `type` of custom + * metadata field. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun defaultValue(): Optional = defaultValue.getOptional("defaultValue") + + /** + * Sets this custom metadata field as required. Setting custom metadata fields on an asset + * will throw error if the value for all required fields are not present in upload or update + * asset API request body. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun isValueRequired(): Optional = isValueRequired.getOptional("isValueRequired") + + /** + * Maximum length of string. Only set this property if `type` is set to `Text` or + * `Textarea`. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun maxLength(): Optional = maxLength.getOptional("maxLength") + + /** + * Maximum value of the field. Only set this property if field type is `Date` or `Number`. + * For `Date` type field, set the minimum date in ISO8601 string format. For `Number` type + * field, set the minimum numeric value. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun maxValue(): Optional = maxValue.getOptional("maxValue") + + /** + * Minimum length of string. Only set this property if `type` is set to `Text` or + * `Textarea`. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun minLength(): Optional = minLength.getOptional("minLength") + + /** + * Minimum value of the field. Only set this property if field type is `Date` or `Number`. + * For `Date` type field, set the minimum date in ISO8601 string format. For `Number` type + * field, set the minimum numeric value. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun minValue(): Optional = minValue.getOptional("minValue") + + /** + * An array of allowed values. This property is only required if `type` property is set to + * `SingleSelect` or `MultiSelect`. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun selectOptions(): Optional> = + selectOptions.getOptional("selectOptions") + + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + + /** + * Returns the raw JSON value of [defaultValue]. + * + * Unlike [defaultValue], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("defaultValue") + @ExcludeMissing + fun _defaultValue(): JsonField = defaultValue + + /** + * Returns the raw JSON value of [isValueRequired]. + * + * Unlike [isValueRequired], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("isValueRequired") + @ExcludeMissing + fun _isValueRequired(): JsonField = isValueRequired + + /** + * Returns the raw JSON value of [maxLength]. + * + * Unlike [maxLength], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("maxLength") @ExcludeMissing fun _maxLength(): JsonField = maxLength + + /** + * Returns the raw JSON value of [maxValue]. + * + * Unlike [maxValue], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("maxValue") @ExcludeMissing fun _maxValue(): JsonField = maxValue + + /** + * Returns the raw JSON value of [minLength]. + * + * Unlike [minLength], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("minLength") @ExcludeMissing fun _minLength(): JsonField = minLength + + /** + * Returns the raw JSON value of [minValue]. + * + * Unlike [minValue], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("minValue") @ExcludeMissing fun _minValue(): JsonField = minValue + + /** + * Returns the raw JSON value of [selectOptions]. + * + * Unlike [selectOptions], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("selectOptions") + @ExcludeMissing + fun _selectOptions(): JsonField> = selectOptions + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Schema]. + * + * The following fields are required: + * ```java + * .type() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Schema]. */ + class Builder internal constructor() { + + private var type: JsonField? = null + private var defaultValue: JsonField = JsonMissing.of() + private var isValueRequired: JsonField = JsonMissing.of() + private var maxLength: JsonField = JsonMissing.of() + private var maxValue: JsonField = JsonMissing.of() + private var minLength: JsonField = JsonMissing.of() + private var minValue: JsonField = JsonMissing.of() + private var selectOptions: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(schema: Schema) = apply { + type = schema.type + defaultValue = schema.defaultValue + isValueRequired = schema.isValueRequired + maxLength = schema.maxLength + maxValue = schema.maxValue + minLength = schema.minLength + minValue = schema.minValue + selectOptions = schema.selectOptions.map { it.toMutableList() } + additionalProperties = schema.additionalProperties.toMutableMap() + } + + /** Type of the custom metadata field. */ + fun type(type: Type) = type(JsonField.of(type)) + + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [Type] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun type(type: JsonField) = apply { this.type = type } + + /** + * The default value for this custom metadata field. This property is only required if + * `isValueRequired` property is set to `true`. The value should match the `type` of + * custom metadata field. + */ + fun defaultValue(defaultValue: DefaultValue) = defaultValue(JsonField.of(defaultValue)) + + /** + * Sets [Builder.defaultValue] to an arbitrary JSON value. + * + * You should usually call [Builder.defaultValue] with a well-typed [DefaultValue] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun defaultValue(defaultValue: JsonField) = apply { + this.defaultValue = defaultValue + } + + /** Alias for calling [defaultValue] with `DefaultValue.ofString(string)`. */ + fun defaultValue(string: String) = defaultValue(DefaultValue.ofString(string)) + + /** Alias for calling [defaultValue] with `DefaultValue.ofNumber(number)`. */ + fun defaultValue(number: Double) = defaultValue(DefaultValue.ofNumber(number)) + + /** Alias for calling [defaultValue] with `DefaultValue.ofBool(bool)`. */ + fun defaultValue(bool: Boolean) = defaultValue(DefaultValue.ofBool(bool)) + + /** Alias for calling [defaultValue] with `DefaultValue.ofMixed(mixed)`. */ + fun defaultValueOfMixed(mixed: List) = + defaultValue(DefaultValue.ofMixed(mixed)) + + /** + * Sets this custom metadata field as required. Setting custom metadata fields on an + * asset will throw error if the value for all required fields are not present in upload + * or update asset API request body. + */ + fun isValueRequired(isValueRequired: Boolean) = + isValueRequired(JsonField.of(isValueRequired)) + + /** + * Sets [Builder.isValueRequired] to an arbitrary JSON value. + * + * You should usually call [Builder.isValueRequired] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun isValueRequired(isValueRequired: JsonField) = apply { + this.isValueRequired = isValueRequired + } + + /** + * Maximum length of string. Only set this property if `type` is set to `Text` or + * `Textarea`. + */ + fun maxLength(maxLength: Double) = maxLength(JsonField.of(maxLength)) + + /** + * Sets [Builder.maxLength] to an arbitrary JSON value. + * + * You should usually call [Builder.maxLength] with a well-typed [Double] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun maxLength(maxLength: JsonField) = apply { this.maxLength = maxLength } + + /** + * Maximum value of the field. Only set this property if field type is `Date` or + * `Number`. For `Date` type field, set the minimum date in ISO8601 string format. For + * `Number` type field, set the minimum numeric value. + */ + fun maxValue(maxValue: MaxValue) = maxValue(JsonField.of(maxValue)) + + /** + * Sets [Builder.maxValue] to an arbitrary JSON value. + * + * You should usually call [Builder.maxValue] with a well-typed [MaxValue] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun maxValue(maxValue: JsonField) = apply { this.maxValue = maxValue } + + /** Alias for calling [maxValue] with `MaxValue.ofString(string)`. */ + fun maxValue(string: String) = maxValue(MaxValue.ofString(string)) + + /** Alias for calling [maxValue] with `MaxValue.ofNumber(number)`. */ + fun maxValue(number: Double) = maxValue(MaxValue.ofNumber(number)) + + /** + * Minimum length of string. Only set this property if `type` is set to `Text` or + * `Textarea`. + */ + fun minLength(minLength: Double) = minLength(JsonField.of(minLength)) + + /** + * Sets [Builder.minLength] to an arbitrary JSON value. + * + * You should usually call [Builder.minLength] with a well-typed [Double] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun minLength(minLength: JsonField) = apply { this.minLength = minLength } + + /** + * Minimum value of the field. Only set this property if field type is `Date` or + * `Number`. For `Date` type field, set the minimum date in ISO8601 string format. For + * `Number` type field, set the minimum numeric value. + */ + fun minValue(minValue: MinValue) = minValue(JsonField.of(minValue)) + + /** + * Sets [Builder.minValue] to an arbitrary JSON value. + * + * You should usually call [Builder.minValue] with a well-typed [MinValue] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun minValue(minValue: JsonField) = apply { this.minValue = minValue } + + /** Alias for calling [minValue] with `MinValue.ofString(string)`. */ + fun minValue(string: String) = minValue(MinValue.ofString(string)) + + /** Alias for calling [minValue] with `MinValue.ofNumber(number)`. */ + fun minValue(number: Double) = minValue(MinValue.ofNumber(number)) + + /** + * An array of allowed values. This property is only required if `type` property is set + * to `SingleSelect` or `MultiSelect`. + */ + fun selectOptions(selectOptions: List) = + selectOptions(JsonField.of(selectOptions)) + + /** + * Sets [Builder.selectOptions] to an arbitrary JSON value. + * + * You should usually call [Builder.selectOptions] with a well-typed + * `List` value instead. This method is primarily for setting the field to + * an undocumented or not yet supported value. + */ + fun selectOptions(selectOptions: JsonField>) = apply { + this.selectOptions = selectOptions.map { it.toMutableList() } + } + + /** + * Adds a single [SelectOption] to [selectOptions]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addSelectOption(selectOption: SelectOption) = apply { + selectOptions = + (selectOptions ?: JsonField.of(mutableListOf())).also { + checkKnown("selectOptions", it).add(selectOption) + } + } + + /** Alias for calling [addSelectOption] with `SelectOption.ofString(string)`. */ + fun addSelectOption(string: String) = addSelectOption(SelectOption.ofString(string)) + + /** Alias for calling [addSelectOption] with `SelectOption.ofNumber(number)`. */ + fun addSelectOption(number: Double) = addSelectOption(SelectOption.ofNumber(number)) + + /** Alias for calling [addSelectOption] with `SelectOption.ofBool(bool)`. */ + fun addSelectOption(bool: Boolean) = addSelectOption(SelectOption.ofBool(bool)) + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Schema]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .type() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Schema = + Schema( + checkRequired("type", type), + defaultValue, + isValueRequired, + maxLength, + maxValue, + minLength, + minValue, + (selectOptions ?: JsonMissing.of()).map { it.toImmutable() }, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Schema = apply { + if (validated) { + return@apply + } + + type().validate() + defaultValue().ifPresent { it.validate() } + isValueRequired() + maxLength() + maxValue().ifPresent { it.validate() } + minLength() + minValue().ifPresent { it.validate() } + selectOptions().ifPresent { it.forEach { it.validate() } } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (type.asKnown().getOrNull()?.validity() ?: 0) + + (defaultValue.asKnown().getOrNull()?.validity() ?: 0) + + (if (isValueRequired.asKnown().isPresent) 1 else 0) + + (if (maxLength.asKnown().isPresent) 1 else 0) + + (maxValue.asKnown().getOrNull()?.validity() ?: 0) + + (if (minLength.asKnown().isPresent) 1 else 0) + + (minValue.asKnown().getOrNull()?.validity() ?: 0) + + (selectOptions.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + /** Type of the custom metadata field. */ + class Type @JsonCreator private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is + * on an older version than the API, then the API may respond with new members that the + * SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val TEXT = of("Text") + + @JvmField val TEXTAREA = of("Textarea") + + @JvmField val NUMBER = of("Number") + + @JvmField val DATE = of("Date") + + @JvmField val BOOLEAN = of("Boolean") + + @JvmField val SINGLE_SELECT = of("SingleSelect") + + @JvmField val MULTI_SELECT = of("MultiSelect") + + @JvmStatic fun of(value: String) = Type(JsonField.of(value)) + } + + /** An enum containing [Type]'s known values. */ + enum class Known { + TEXT, + TEXTAREA, + NUMBER, + DATE, + BOOLEAN, + SINGLE_SELECT, + MULTI_SELECT, + } + + /** + * An enum containing [Type]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [Type] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if + * the SDK is on an older version than the API, then the API may respond with new + * members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + TEXT, + TEXTAREA, + NUMBER, + DATE, + BOOLEAN, + SINGLE_SELECT, + MULTI_SELECT, + /** An enum member indicating that [Type] was instantiated with an unknown value. */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you + * want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + TEXT -> Value.TEXT + TEXTAREA -> Value.TEXTAREA + NUMBER -> Value.NUMBER + DATE -> Value.DATE + BOOLEAN -> Value.BOOLEAN + SINGLE_SELECT -> Value.SINGLE_SELECT + MULTI_SELECT -> Value.MULTI_SELECT + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and + * don't want to throw for the unknown case. + * + * @throws ImageKitInvalidDataException if this class instance's value is a not a known + * member. + */ + fun known(): Known = + when (this) { + TEXT -> Known.TEXT + TEXTAREA -> Known.TEXTAREA + NUMBER -> Known.NUMBER + DATE -> Known.DATE + BOOLEAN -> Known.BOOLEAN + SINGLE_SELECT -> Known.SINGLE_SELECT + MULTI_SELECT -> Known.MULTI_SELECT + else -> throw ImageKitInvalidDataException("Unknown Type: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for + * debugging and generally doesn't throw. + * + * @throws ImageKitInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + ImageKitInvalidDataException("Value is not a String") + } + + private var validated: Boolean = false + + fun validate(): Type = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Type && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + /** + * The default value for this custom metadata field. This property is only required if + * `isValueRequired` property is set to `true`. The value should match the `type` of custom + * metadata field. + */ + @JsonDeserialize(using = DefaultValue.Deserializer::class) + @JsonSerialize(using = DefaultValue.Serializer::class) + class DefaultValue + private constructor( + private val string: String? = null, + private val number: Double? = null, + private val bool: Boolean? = null, + private val mixed: List? = null, + private val _json: JsonValue? = null, + ) { + + fun string(): Optional = Optional.ofNullable(string) + + fun number(): Optional = Optional.ofNullable(number) + + fun bool(): Optional = Optional.ofNullable(bool) + + /** + * Default value should be of type array when custom metadata field type is set to + * `MultiSelect`. + */ + fun mixed(): Optional> = Optional.ofNullable(mixed) + + fun isString(): Boolean = string != null + + fun isNumber(): Boolean = number != null + + fun isBool(): Boolean = bool != null + + fun isMixed(): Boolean = mixed != null + + fun asString(): String = string.getOrThrow("string") + + fun asNumber(): Double = number.getOrThrow("number") + + fun asBool(): Boolean = bool.getOrThrow("bool") + + /** + * Default value should be of type array when custom metadata field type is set to + * `MultiSelect`. + */ + fun asMixed(): List = mixed.getOrThrow("mixed") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + string != null -> visitor.visitString(string) + number != null -> visitor.visitNumber(number) + bool != null -> visitor.visitBool(bool) + mixed != null -> visitor.visitMixed(mixed) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): DefaultValue = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitString(string: String) {} + + override fun visitNumber(number: Double) {} + + override fun visitBool(bool: Boolean) {} + + override fun visitMixed(mixed: List) { + mixed.forEach { it.validate() } + } + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitString(string: String) = 1 + + override fun visitNumber(number: Double) = 1 + + override fun visitBool(bool: Boolean) = 1 + + override fun visitMixed(mixed: List) = + mixed.sumOf { it.validity().toInt() } + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is DefaultValue && + string == other.string && + number == other.number && + bool == other.bool && + mixed == other.mixed + } + + override fun hashCode(): Int = Objects.hash(string, number, bool, mixed) + + override fun toString(): String = + when { + string != null -> "DefaultValue{string=$string}" + number != null -> "DefaultValue{number=$number}" + bool != null -> "DefaultValue{bool=$bool}" + mixed != null -> "DefaultValue{mixed=$mixed}" + _json != null -> "DefaultValue{_unknown=$_json}" + else -> throw IllegalStateException("Invalid DefaultValue") + } + + companion object { + + @JvmStatic fun ofString(string: String) = DefaultValue(string = string) + + @JvmStatic fun ofNumber(number: Double) = DefaultValue(number = number) + + @JvmStatic fun ofBool(bool: Boolean) = DefaultValue(bool = bool) + + /** + * Default value should be of type array when custom metadata field type is set to + * `MultiSelect`. + */ + @JvmStatic + fun ofMixed(mixed: List) = + DefaultValue(mixed = mixed.toImmutable()) + } + + /** + * An interface that defines how to map each variant of [DefaultValue] to a value of + * type [T]. + */ + interface Visitor { + + fun visitString(string: String): T + + fun visitNumber(number: Double): T + + fun visitBool(bool: Boolean): T + + /** + * Default value should be of type array when custom metadata field type is set to + * `MultiSelect`. + */ + fun visitMixed(mixed: List): T + + /** + * Maps an unknown variant of [DefaultValue] to a value of type [T]. + * + * An instance of [DefaultValue] can contain an unknown variant if it was + * deserialized from data that doesn't match any known variant. For example, if the + * SDK is on an older version than the API, then the API may respond with new + * variants that the SDK is unaware of. + * + * @throws ImageKitInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw ImageKitInvalidDataException("Unknown DefaultValue: $json") + } + } + + internal class Deserializer : BaseDeserializer(DefaultValue::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): DefaultValue { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + DefaultValue(string = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + DefaultValue(number = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + DefaultValue(bool = it, _json = json) + }, + tryDeserialize( + node, + jacksonTypeRef>(), + ) + ?.let { DefaultValue(mixed = it, _json = json) }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely incompatible + // with all the possible variants (e.g. deserializing from object). + 0 -> DefaultValue(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then use the + // first completely valid match, or simply the first match if none are + // completely valid. + else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() + } + } + } + + internal class Serializer : BaseSerializer(DefaultValue::class) { + + override fun serialize( + value: DefaultValue, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.string != null -> generator.writeObject(value.string) + value.number != null -> generator.writeObject(value.number) + value.bool != null -> generator.writeObject(value.bool) + value.mixed != null -> generator.writeObject(value.mixed) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid DefaultValue") + } + } + } + + @JsonDeserialize(using = UnnamedSchemaWithArrayParent1.Deserializer::class) + @JsonSerialize(using = UnnamedSchemaWithArrayParent1.Serializer::class) + class UnnamedSchemaWithArrayParent1 + private constructor( + private val string: String? = null, + private val number: Double? = null, + private val bool: Boolean? = null, + private val _json: JsonValue? = null, + ) { + + fun string(): Optional = Optional.ofNullable(string) + + fun number(): Optional = Optional.ofNullable(number) + + fun bool(): Optional = Optional.ofNullable(bool) + + fun isString(): Boolean = string != null + + fun isNumber(): Boolean = number != null + + fun isBool(): Boolean = bool != null + + fun asString(): String = string.getOrThrow("string") + + fun asNumber(): Double = number.getOrThrow("number") + + fun asBool(): Boolean = bool.getOrThrow("bool") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + string != null -> visitor.visitString(string) + number != null -> visitor.visitNumber(number) + bool != null -> visitor.visitBool(bool) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): UnnamedSchemaWithArrayParent1 = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitString(string: String) {} + + override fun visitNumber(number: Double) {} + + override fun visitBool(bool: Boolean) {} + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitString(string: String) = 1 + + override fun visitNumber(number: Double) = 1 + + override fun visitBool(bool: Boolean) = 1 + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is UnnamedSchemaWithArrayParent1 && + string == other.string && + number == other.number && + bool == other.bool + } + + override fun hashCode(): Int = Objects.hash(string, number, bool) + + override fun toString(): String = + when { + string != null -> "UnnamedSchemaWithArrayParent1{string=$string}" + number != null -> "UnnamedSchemaWithArrayParent1{number=$number}" + bool != null -> "UnnamedSchemaWithArrayParent1{bool=$bool}" + _json != null -> "UnnamedSchemaWithArrayParent1{_unknown=$_json}" + else -> throw IllegalStateException("Invalid UnnamedSchemaWithArrayParent1") + } + + companion object { + + @JvmStatic + fun ofString(string: String) = UnnamedSchemaWithArrayParent1(string = string) + + @JvmStatic + fun ofNumber(number: Double) = UnnamedSchemaWithArrayParent1(number = number) + + @JvmStatic + fun ofBool(bool: Boolean) = UnnamedSchemaWithArrayParent1(bool = bool) + } + + /** + * An interface that defines how to map each variant of + * [UnnamedSchemaWithArrayParent1] to a value of type [T]. + */ + interface Visitor { + + fun visitString(string: String): T + + fun visitNumber(number: Double): T + + fun visitBool(bool: Boolean): T + + /** + * Maps an unknown variant of [UnnamedSchemaWithArrayParent1] to a value of type + * [T]. + * + * An instance of [UnnamedSchemaWithArrayParent1] can contain an unknown variant + * if it was deserialized from data that doesn't match any known variant. For + * example, if the SDK is on an older version than the API, then the API may + * respond with new variants that the SDK is unaware of. + * + * @throws ImageKitInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw ImageKitInvalidDataException( + "Unknown UnnamedSchemaWithArrayParent1: $json" + ) + } + } + + internal class Deserializer : + BaseDeserializer( + UnnamedSchemaWithArrayParent1::class + ) { + + override fun ObjectCodec.deserialize( + node: JsonNode + ): UnnamedSchemaWithArrayParent1 { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + UnnamedSchemaWithArrayParent1(string = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + UnnamedSchemaWithArrayParent1(number = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + UnnamedSchemaWithArrayParent1(bool = it, _json = json) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely + // incompatible with all the possible variants (e.g. deserializing from + // object). + 0 -> UnnamedSchemaWithArrayParent1(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then use + // the first completely valid match, or simply the first match if none + // are completely valid. + else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() + } + } + } + + internal class Serializer : + BaseSerializer( + UnnamedSchemaWithArrayParent1::class + ) { + + override fun serialize( + value: UnnamedSchemaWithArrayParent1, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.string != null -> generator.writeObject(value.string) + value.number != null -> generator.writeObject(value.number) + value.bool != null -> generator.writeObject(value.bool) + value._json != null -> generator.writeObject(value._json) + else -> + throw IllegalStateException("Invalid UnnamedSchemaWithArrayParent1") + } + } + } + } + } + + /** + * Maximum value of the field. Only set this property if field type is `Date` or `Number`. + * For `Date` type field, set the minimum date in ISO8601 string format. For `Number` type + * field, set the minimum numeric value. + */ + @JsonDeserialize(using = MaxValue.Deserializer::class) + @JsonSerialize(using = MaxValue.Serializer::class) + class MaxValue + private constructor( + private val string: String? = null, + private val number: Double? = null, + private val _json: JsonValue? = null, + ) { + + fun string(): Optional = Optional.ofNullable(string) + + fun number(): Optional = Optional.ofNullable(number) + + fun isString(): Boolean = string != null + + fun isNumber(): Boolean = number != null + + fun asString(): String = string.getOrThrow("string") + + fun asNumber(): Double = number.getOrThrow("number") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + string != null -> visitor.visitString(string) + number != null -> visitor.visitNumber(number) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): MaxValue = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitString(string: String) {} + + override fun visitNumber(number: Double) {} + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitString(string: String) = 1 + + override fun visitNumber(number: Double) = 1 + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is MaxValue && string == other.string && number == other.number + } + + override fun hashCode(): Int = Objects.hash(string, number) + + override fun toString(): String = + when { + string != null -> "MaxValue{string=$string}" + number != null -> "MaxValue{number=$number}" + _json != null -> "MaxValue{_unknown=$_json}" + else -> throw IllegalStateException("Invalid MaxValue") + } + + companion object { + + @JvmStatic fun ofString(string: String) = MaxValue(string = string) + + @JvmStatic fun ofNumber(number: Double) = MaxValue(number = number) + } + + /** + * An interface that defines how to map each variant of [MaxValue] to a value of type + * [T]. + */ + interface Visitor { + + fun visitString(string: String): T + + fun visitNumber(number: Double): T + + /** + * Maps an unknown variant of [MaxValue] to a value of type [T]. + * + * An instance of [MaxValue] can contain an unknown variant if it was deserialized + * from data that doesn't match any known variant. For example, if the SDK is on an + * older version than the API, then the API may respond with new variants that the + * SDK is unaware of. + * + * @throws ImageKitInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw ImageKitInvalidDataException("Unknown MaxValue: $json") + } + } + + internal class Deserializer : BaseDeserializer(MaxValue::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): MaxValue { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + MaxValue(string = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + MaxValue(number = it, _json = json) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely incompatible + // with all the possible variants (e.g. deserializing from object). + 0 -> MaxValue(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then use the + // first completely valid match, or simply the first match if none are + // completely valid. + else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() + } + } + } + + internal class Serializer : BaseSerializer(MaxValue::class) { + + override fun serialize( + value: MaxValue, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.string != null -> generator.writeObject(value.string) + value.number != null -> generator.writeObject(value.number) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid MaxValue") + } + } + } + } + + /** + * Minimum value of the field. Only set this property if field type is `Date` or `Number`. + * For `Date` type field, set the minimum date in ISO8601 string format. For `Number` type + * field, set the minimum numeric value. + */ + @JsonDeserialize(using = MinValue.Deserializer::class) + @JsonSerialize(using = MinValue.Serializer::class) + class MinValue + private constructor( + private val string: String? = null, + private val number: Double? = null, + private val _json: JsonValue? = null, + ) { + + fun string(): Optional = Optional.ofNullable(string) + + fun number(): Optional = Optional.ofNullable(number) + + fun isString(): Boolean = string != null + + fun isNumber(): Boolean = number != null + + fun asString(): String = string.getOrThrow("string") + + fun asNumber(): Double = number.getOrThrow("number") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + string != null -> visitor.visitString(string) + number != null -> visitor.visitNumber(number) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): MinValue = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitString(string: String) {} + + override fun visitNumber(number: Double) {} + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitString(string: String) = 1 + + override fun visitNumber(number: Double) = 1 + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is MinValue && string == other.string && number == other.number + } + + override fun hashCode(): Int = Objects.hash(string, number) + + override fun toString(): String = + when { + string != null -> "MinValue{string=$string}" + number != null -> "MinValue{number=$number}" + _json != null -> "MinValue{_unknown=$_json}" + else -> throw IllegalStateException("Invalid MinValue") + } + + companion object { + + @JvmStatic fun ofString(string: String) = MinValue(string = string) + + @JvmStatic fun ofNumber(number: Double) = MinValue(number = number) + } + + /** + * An interface that defines how to map each variant of [MinValue] to a value of type + * [T]. + */ + interface Visitor { + + fun visitString(string: String): T + + fun visitNumber(number: Double): T + + /** + * Maps an unknown variant of [MinValue] to a value of type [T]. + * + * An instance of [MinValue] can contain an unknown variant if it was deserialized + * from data that doesn't match any known variant. For example, if the SDK is on an + * older version than the API, then the API may respond with new variants that the + * SDK is unaware of. + * + * @throws ImageKitInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw ImageKitInvalidDataException("Unknown MinValue: $json") + } + } + + internal class Deserializer : BaseDeserializer(MinValue::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): MinValue { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + MinValue(string = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + MinValue(number = it, _json = json) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely incompatible + // with all the possible variants (e.g. deserializing from object). + 0 -> MinValue(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then use the + // first completely valid match, or simply the first match if none are + // completely valid. + else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() + } + } + } + + internal class Serializer : BaseSerializer(MinValue::class) { + + override fun serialize( + value: MinValue, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.string != null -> generator.writeObject(value.string) + value.number != null -> generator.writeObject(value.number) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid MinValue") + } + } + } + } + + @JsonDeserialize(using = SelectOption.Deserializer::class) + @JsonSerialize(using = SelectOption.Serializer::class) + class SelectOption + private constructor( + private val string: String? = null, + private val number: Double? = null, + private val bool: Boolean? = null, + private val _json: JsonValue? = null, + ) { + + fun string(): Optional = Optional.ofNullable(string) + + fun number(): Optional = Optional.ofNullable(number) + + fun bool(): Optional = Optional.ofNullable(bool) + + fun isString(): Boolean = string != null + + fun isNumber(): Boolean = number != null + + fun isBool(): Boolean = bool != null + + fun asString(): String = string.getOrThrow("string") + + fun asNumber(): Double = number.getOrThrow("number") + + fun asBool(): Boolean = bool.getOrThrow("bool") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + string != null -> visitor.visitString(string) + number != null -> visitor.visitNumber(number) + bool != null -> visitor.visitBool(bool) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): SelectOption = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitString(string: String) {} + + override fun visitNumber(number: Double) {} + + override fun visitBool(bool: Boolean) {} + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitString(string: String) = 1 + + override fun visitNumber(number: Double) = 1 + + override fun visitBool(bool: Boolean) = 1 + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is SelectOption && + string == other.string && + number == other.number && + bool == other.bool + } + + override fun hashCode(): Int = Objects.hash(string, number, bool) + + override fun toString(): String = + when { + string != null -> "SelectOption{string=$string}" + number != null -> "SelectOption{number=$number}" + bool != null -> "SelectOption{bool=$bool}" + _json != null -> "SelectOption{_unknown=$_json}" + else -> throw IllegalStateException("Invalid SelectOption") + } + + companion object { + + @JvmStatic fun ofString(string: String) = SelectOption(string = string) + + @JvmStatic fun ofNumber(number: Double) = SelectOption(number = number) + + @JvmStatic fun ofBool(bool: Boolean) = SelectOption(bool = bool) + } + + /** + * An interface that defines how to map each variant of [SelectOption] to a value of + * type [T]. + */ + interface Visitor { + + fun visitString(string: String): T + + fun visitNumber(number: Double): T + + fun visitBool(bool: Boolean): T + + /** + * Maps an unknown variant of [SelectOption] to a value of type [T]. + * + * An instance of [SelectOption] can contain an unknown variant if it was + * deserialized from data that doesn't match any known variant. For example, if the + * SDK is on an older version than the API, then the API may respond with new + * variants that the SDK is unaware of. + * + * @throws ImageKitInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw ImageKitInvalidDataException("Unknown SelectOption: $json") + } + } + + internal class Deserializer : BaseDeserializer(SelectOption::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): SelectOption { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + SelectOption(string = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + SelectOption(number = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + SelectOption(bool = it, _json = json) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely incompatible + // with all the possible variants (e.g. deserializing from object). + 0 -> SelectOption(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then use the + // first completely valid match, or simply the first match if none are + // completely valid. + else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() + } + } + } + + internal class Serializer : BaseSerializer(SelectOption::class) { + + override fun serialize( + value: SelectOption, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.string != null -> generator.writeObject(value.string) + value.number != null -> generator.writeObject(value.number) + value.bool != null -> generator.writeObject(value.bool) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid SelectOption") + } + } + } + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Schema && + type == other.type && + defaultValue == other.defaultValue && + isValueRequired == other.isValueRequired && + maxLength == other.maxLength && + maxValue == other.maxValue && + minLength == other.minLength && + minValue == other.minValue && + selectOptions == other.selectOptions && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + type, + defaultValue, + isValueRequired, + maxLength, + maxValue, + minLength, + minValue, + selectOptions, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Schema{type=$type, defaultValue=$defaultValue, isValueRequired=$isValueRequired, maxLength=$maxLength, maxValue=$maxValue, minLength=$minLength, minValue=$minValue, selectOptions=$selectOptions, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is CustomMetadataFieldCreateParams && + body == other.body && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = Objects.hash(body, additionalHeaders, additionalQueryParams) + + override fun toString() = + "CustomMetadataFieldCreateParams{body=$body, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/custommetadatafields/CustomMetadataFieldDeleteParams.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/custommetadatafields/CustomMetadataFieldDeleteParams.kt new file mode 100644 index 0000000..6266a56 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/custommetadatafields/CustomMetadataFieldDeleteParams.kt @@ -0,0 +1,238 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.custommetadatafields + +import com.imagekit.api.core.JsonValue +import com.imagekit.api.core.Params +import com.imagekit.api.core.http.Headers +import com.imagekit.api.core.http.QueryParams +import com.imagekit.api.core.toImmutable +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** + * This API deletes a custom metadata field. Even after deleting a custom metadata field, you cannot + * create any new custom metadata field with the same name. + */ +class CustomMetadataFieldDeleteParams +private constructor( + private val id: String?, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, + private val additionalBodyProperties: Map, +) : Params { + + fun id(): Optional = Optional.ofNullable(id) + + /** Additional body properties to send with the request. */ + fun _additionalBodyProperties(): Map = additionalBodyProperties + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun none(): CustomMetadataFieldDeleteParams = builder().build() + + /** + * Returns a mutable builder for constructing an instance of + * [CustomMetadataFieldDeleteParams]. + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [CustomMetadataFieldDeleteParams]. */ + class Builder internal constructor() { + + private var id: String? = null + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + private var additionalBodyProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(customMetadataFieldDeleteParams: CustomMetadataFieldDeleteParams) = + apply { + id = customMetadataFieldDeleteParams.id + additionalHeaders = customMetadataFieldDeleteParams.additionalHeaders.toBuilder() + additionalQueryParams = + customMetadataFieldDeleteParams.additionalQueryParams.toBuilder() + additionalBodyProperties = + customMetadataFieldDeleteParams.additionalBodyProperties.toMutableMap() + } + + fun id(id: String?) = apply { this.id = id } + + /** Alias for calling [Builder.id] with `id.orElse(null)`. */ + fun id(id: Optional) = id(id.getOrNull()) + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + this.additionalBodyProperties.clear() + putAllAdditionalBodyProperties(additionalBodyProperties) + } + + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + additionalBodyProperties.put(key, value) + } + + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + this.additionalBodyProperties.putAll(additionalBodyProperties) + } + + fun removeAdditionalBodyProperty(key: String) = apply { + additionalBodyProperties.remove(key) + } + + fun removeAllAdditionalBodyProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalBodyProperty) + } + + /** + * Returns an immutable instance of [CustomMetadataFieldDeleteParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): CustomMetadataFieldDeleteParams = + CustomMetadataFieldDeleteParams( + id, + additionalHeaders.build(), + additionalQueryParams.build(), + additionalBodyProperties.toImmutable(), + ) + } + + fun _body(): Optional> = + Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) + + fun _pathParam(index: Int): String = + when (index) { + 0 -> id ?: "" + else -> "" + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is CustomMetadataFieldDeleteParams && + id == other.id && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams && + additionalBodyProperties == other.additionalBodyProperties + } + + override fun hashCode(): Int = + Objects.hash(id, additionalHeaders, additionalQueryParams, additionalBodyProperties) + + override fun toString() = + "CustomMetadataFieldDeleteParams{id=$id, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams, additionalBodyProperties=$additionalBodyProperties}" +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/custommetadatafields/CustomMetadataFieldDeleteResponse.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/custommetadatafields/CustomMetadataFieldDeleteResponse.kt new file mode 100644 index 0000000..7ec2f00 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/custommetadatafields/CustomMetadataFieldDeleteResponse.kt @@ -0,0 +1,120 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.custommetadatafields + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.imagekit.api.core.ExcludeMissing +import com.imagekit.api.core.JsonValue +import com.imagekit.api.errors.ImageKitInvalidDataException +import java.util.Collections +import java.util.Objects + +class CustomMetadataFieldDeleteResponse +private constructor(private val additionalProperties: MutableMap) { + + @JsonCreator private constructor() : this(mutableMapOf()) + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [CustomMetadataFieldDeleteResponse]. + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [CustomMetadataFieldDeleteResponse]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(customMetadataFieldDeleteResponse: CustomMetadataFieldDeleteResponse) = + apply { + additionalProperties = + customMetadataFieldDeleteResponse.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [CustomMetadataFieldDeleteResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): CustomMetadataFieldDeleteResponse = + CustomMetadataFieldDeleteResponse(additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): CustomMetadataFieldDeleteResponse = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = 0 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is CustomMetadataFieldDeleteResponse && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "CustomMetadataFieldDeleteResponse{additionalProperties=$additionalProperties}" +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/custommetadatafields/CustomMetadataFieldListParams.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/custommetadatafields/CustomMetadataFieldListParams.kt new file mode 100644 index 0000000..8ae404f --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/custommetadatafields/CustomMetadataFieldListParams.kt @@ -0,0 +1,212 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.custommetadatafields + +import com.imagekit.api.core.Params +import com.imagekit.api.core.http.Headers +import com.imagekit.api.core.http.QueryParams +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** + * This API returns the array of created custom metadata field objects. By default the API returns + * only non deleted field objects, but you can include deleted fields in the API response. + */ +class CustomMetadataFieldListParams +private constructor( + private val includeDeleted: Boolean?, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** Set it to `true` to include deleted field objects in the API response. */ + fun includeDeleted(): Optional = Optional.ofNullable(includeDeleted) + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun none(): CustomMetadataFieldListParams = builder().build() + + /** + * Returns a mutable builder for constructing an instance of + * [CustomMetadataFieldListParams]. + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [CustomMetadataFieldListParams]. */ + class Builder internal constructor() { + + private var includeDeleted: Boolean? = null + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + + @JvmSynthetic + internal fun from(customMetadataFieldListParams: CustomMetadataFieldListParams) = apply { + includeDeleted = customMetadataFieldListParams.includeDeleted + additionalHeaders = customMetadataFieldListParams.additionalHeaders.toBuilder() + additionalQueryParams = customMetadataFieldListParams.additionalQueryParams.toBuilder() + } + + /** Set it to `true` to include deleted field objects in the API response. */ + fun includeDeleted(includeDeleted: Boolean?) = apply { + this.includeDeleted = includeDeleted + } + + /** + * Alias for [Builder.includeDeleted]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun includeDeleted(includeDeleted: Boolean) = includeDeleted(includeDeleted as Boolean?) + + /** Alias for calling [Builder.includeDeleted] with `includeDeleted.orElse(null)`. */ + fun includeDeleted(includeDeleted: Optional) = + includeDeleted(includeDeleted.getOrNull()) + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + /** + * Returns an immutable instance of [CustomMetadataFieldListParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): CustomMetadataFieldListParams = + CustomMetadataFieldListParams( + includeDeleted, + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = + QueryParams.builder() + .apply { + includeDeleted?.let { put("includeDeleted", it.toString()) } + putAll(additionalQueryParams) + } + .build() + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is CustomMetadataFieldListParams && + includeDeleted == other.includeDeleted && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = + Objects.hash(includeDeleted, additionalHeaders, additionalQueryParams) + + override fun toString() = + "CustomMetadataFieldListParams{includeDeleted=$includeDeleted, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/custommetadatafields/CustomMetadataFieldUpdateParams.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/custommetadatafields/CustomMetadataFieldUpdateParams.kt new file mode 100644 index 0000000..2cedf44 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/custommetadatafields/CustomMetadataFieldUpdateParams.kt @@ -0,0 +1,2009 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.custommetadatafields + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.fasterxml.jackson.core.JsonGenerator +import com.fasterxml.jackson.core.ObjectCodec +import com.fasterxml.jackson.databind.JsonNode +import com.fasterxml.jackson.databind.SerializerProvider +import com.fasterxml.jackson.databind.annotation.JsonDeserialize +import com.fasterxml.jackson.databind.annotation.JsonSerialize +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.imagekit.api.core.BaseDeserializer +import com.imagekit.api.core.BaseSerializer +import com.imagekit.api.core.ExcludeMissing +import com.imagekit.api.core.JsonField +import com.imagekit.api.core.JsonMissing +import com.imagekit.api.core.JsonValue +import com.imagekit.api.core.Params +import com.imagekit.api.core.allMaxBy +import com.imagekit.api.core.checkKnown +import com.imagekit.api.core.getOrThrow +import com.imagekit.api.core.http.Headers +import com.imagekit.api.core.http.QueryParams +import com.imagekit.api.core.toImmutable +import com.imagekit.api.errors.ImageKitInvalidDataException +import java.util.Collections +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** This API updates the label or schema of an existing custom metadata field. */ +class CustomMetadataFieldUpdateParams +private constructor( + private val id: String?, + private val body: Body, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + fun id(): Optional = Optional.ofNullable(id) + + /** + * Human readable name of the custom metadata field. This should be unique across all non + * deleted custom metadata fields. This name is displayed as form field label to the users while + * setting field value on an asset in the media library UI. This parameter is required if + * `schema` is not provided. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun label(): Optional = body.label() + + /** + * An object that describes the rules for the custom metadata key. This parameter is required if + * `label` is not provided. Note: `type` cannot be updated and will be ignored if sent with the + * `schema`. The schema will be validated as per the existing `type`. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun schema(): Optional = body.schema() + + /** + * Returns the raw JSON value of [label]. + * + * Unlike [label], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _label(): JsonField = body._label() + + /** + * Returns the raw JSON value of [schema]. + * + * Unlike [schema], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _schema(): JsonField = body._schema() + + fun _additionalBodyProperties(): Map = body._additionalProperties() + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun none(): CustomMetadataFieldUpdateParams = builder().build() + + /** + * Returns a mutable builder for constructing an instance of + * [CustomMetadataFieldUpdateParams]. + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [CustomMetadataFieldUpdateParams]. */ + class Builder internal constructor() { + + private var id: String? = null + private var body: Body.Builder = Body.builder() + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + + @JvmSynthetic + internal fun from(customMetadataFieldUpdateParams: CustomMetadataFieldUpdateParams) = + apply { + id = customMetadataFieldUpdateParams.id + body = customMetadataFieldUpdateParams.body.toBuilder() + additionalHeaders = customMetadataFieldUpdateParams.additionalHeaders.toBuilder() + additionalQueryParams = + customMetadataFieldUpdateParams.additionalQueryParams.toBuilder() + } + + fun id(id: String?) = apply { this.id = id } + + /** Alias for calling [Builder.id] with `id.orElse(null)`. */ + fun id(id: Optional) = id(id.getOrNull()) + + /** + * Sets the entire request body. + * + * This is generally only useful if you are already constructing the body separately. + * Otherwise, it's more convenient to use the top-level setters instead: + * - [label] + * - [schema] + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } + + /** + * Human readable name of the custom metadata field. This should be unique across all non + * deleted custom metadata fields. This name is displayed as form field label to the users + * while setting field value on an asset in the media library UI. This parameter is required + * if `schema` is not provided. + */ + fun label(label: String) = apply { body.label(label) } + + /** + * Sets [Builder.label] to an arbitrary JSON value. + * + * You should usually call [Builder.label] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun label(label: JsonField) = apply { body.label(label) } + + /** + * An object that describes the rules for the custom metadata key. This parameter is + * required if `label` is not provided. Note: `type` cannot be updated and will be ignored + * if sent with the `schema`. The schema will be validated as per the existing `type`. + */ + fun schema(schema: Schema) = apply { body.schema(schema) } + + /** + * Sets [Builder.schema] to an arbitrary JSON value. + * + * You should usually call [Builder.schema] with a well-typed [Schema] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun schema(schema: JsonField) = apply { body.schema(schema) } + + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + body.additionalProperties(additionalBodyProperties) + } + + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + body.putAdditionalProperty(key, value) + } + + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + body.putAllAdditionalProperties(additionalBodyProperties) + } + + fun removeAdditionalBodyProperty(key: String) = apply { body.removeAdditionalProperty(key) } + + fun removeAllAdditionalBodyProperties(keys: Set) = apply { + body.removeAllAdditionalProperties(keys) + } + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + /** + * Returns an immutable instance of [CustomMetadataFieldUpdateParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): CustomMetadataFieldUpdateParams = + CustomMetadataFieldUpdateParams( + id, + body.build(), + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } + + fun _body(): Body = body + + fun _pathParam(index: Int): String = + when (index) { + 0 -> id ?: "" + else -> "" + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + class Body + private constructor( + private val label: JsonField, + private val schema: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("label") @ExcludeMissing label: JsonField = JsonMissing.of(), + @JsonProperty("schema") @ExcludeMissing schema: JsonField = JsonMissing.of(), + ) : this(label, schema, mutableMapOf()) + + /** + * Human readable name of the custom metadata field. This should be unique across all non + * deleted custom metadata fields. This name is displayed as form field label to the users + * while setting field value on an asset in the media library UI. This parameter is required + * if `schema` is not provided. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun label(): Optional = label.getOptional("label") + + /** + * An object that describes the rules for the custom metadata key. This parameter is + * required if `label` is not provided. Note: `type` cannot be updated and will be ignored + * if sent with the `schema`. The schema will be validated as per the existing `type`. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun schema(): Optional = schema.getOptional("schema") + + /** + * Returns the raw JSON value of [label]. + * + * Unlike [label], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("label") @ExcludeMissing fun _label(): JsonField = label + + /** + * Returns the raw JSON value of [schema]. + * + * Unlike [schema], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("schema") @ExcludeMissing fun _schema(): JsonField = schema + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Body]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Body]. */ + class Builder internal constructor() { + + private var label: JsonField = JsonMissing.of() + private var schema: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(body: Body) = apply { + label = body.label + schema = body.schema + additionalProperties = body.additionalProperties.toMutableMap() + } + + /** + * Human readable name of the custom metadata field. This should be unique across all + * non deleted custom metadata fields. This name is displayed as form field label to the + * users while setting field value on an asset in the media library UI. This parameter + * is required if `schema` is not provided. + */ + fun label(label: String) = label(JsonField.of(label)) + + /** + * Sets [Builder.label] to an arbitrary JSON value. + * + * You should usually call [Builder.label] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun label(label: JsonField) = apply { this.label = label } + + /** + * An object that describes the rules for the custom metadata key. This parameter is + * required if `label` is not provided. Note: `type` cannot be updated and will be + * ignored if sent with the `schema`. The schema will be validated as per the existing + * `type`. + */ + fun schema(schema: Schema) = schema(JsonField.of(schema)) + + /** + * Sets [Builder.schema] to an arbitrary JSON value. + * + * You should usually call [Builder.schema] with a well-typed [Schema] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun schema(schema: JsonField) = apply { this.schema = schema } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Body]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Body = Body(label, schema, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Body = apply { + if (validated) { + return@apply + } + + label() + schema().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (label.asKnown().isPresent) 1 else 0) + + (schema.asKnown().getOrNull()?.validity() ?: 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Body && + label == other.label && + schema == other.schema && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(label, schema, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Body{label=$label, schema=$schema, additionalProperties=$additionalProperties}" + } + + /** + * An object that describes the rules for the custom metadata key. This parameter is required if + * `label` is not provided. Note: `type` cannot be updated and will be ignored if sent with the + * `schema`. The schema will be validated as per the existing `type`. + */ + class Schema + private constructor( + private val defaultValue: JsonField, + private val isValueRequired: JsonField, + private val maxLength: JsonField, + private val maxValue: JsonField, + private val minLength: JsonField, + private val minValue: JsonField, + private val selectOptions: JsonField>, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("defaultValue") + @ExcludeMissing + defaultValue: JsonField = JsonMissing.of(), + @JsonProperty("isValueRequired") + @ExcludeMissing + isValueRequired: JsonField = JsonMissing.of(), + @JsonProperty("maxLength") + @ExcludeMissing + maxLength: JsonField = JsonMissing.of(), + @JsonProperty("maxValue") + @ExcludeMissing + maxValue: JsonField = JsonMissing.of(), + @JsonProperty("minLength") + @ExcludeMissing + minLength: JsonField = JsonMissing.of(), + @JsonProperty("minValue") + @ExcludeMissing + minValue: JsonField = JsonMissing.of(), + @JsonProperty("selectOptions") + @ExcludeMissing + selectOptions: JsonField> = JsonMissing.of(), + ) : this( + defaultValue, + isValueRequired, + maxLength, + maxValue, + minLength, + minValue, + selectOptions, + mutableMapOf(), + ) + + /** + * The default value for this custom metadata field. This property is only required if + * `isValueRequired` property is set to `true`. The value should match the `type` of custom + * metadata field. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun defaultValue(): Optional = defaultValue.getOptional("defaultValue") + + /** + * Sets this custom metadata field as required. Setting custom metadata fields on an asset + * will throw error if the value for all required fields are not present in upload or update + * asset API request body. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun isValueRequired(): Optional = isValueRequired.getOptional("isValueRequired") + + /** + * Maximum length of string. Only set this property if `type` is set to `Text` or + * `Textarea`. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun maxLength(): Optional = maxLength.getOptional("maxLength") + + /** + * Maximum value of the field. Only set this property if field type is `Date` or `Number`. + * For `Date` type field, set the minimum date in ISO8601 string format. For `Number` type + * field, set the minimum numeric value. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun maxValue(): Optional = maxValue.getOptional("maxValue") + + /** + * Minimum length of string. Only set this property if `type` is set to `Text` or + * `Textarea`. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun minLength(): Optional = minLength.getOptional("minLength") + + /** + * Minimum value of the field. Only set this property if field type is `Date` or `Number`. + * For `Date` type field, set the minimum date in ISO8601 string format. For `Number` type + * field, set the minimum numeric value. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun minValue(): Optional = minValue.getOptional("minValue") + + /** + * An array of allowed values. This property is only required if `type` property is set to + * `SingleSelect` or `MultiSelect`. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun selectOptions(): Optional> = + selectOptions.getOptional("selectOptions") + + /** + * Returns the raw JSON value of [defaultValue]. + * + * Unlike [defaultValue], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("defaultValue") + @ExcludeMissing + fun _defaultValue(): JsonField = defaultValue + + /** + * Returns the raw JSON value of [isValueRequired]. + * + * Unlike [isValueRequired], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("isValueRequired") + @ExcludeMissing + fun _isValueRequired(): JsonField = isValueRequired + + /** + * Returns the raw JSON value of [maxLength]. + * + * Unlike [maxLength], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("maxLength") @ExcludeMissing fun _maxLength(): JsonField = maxLength + + /** + * Returns the raw JSON value of [maxValue]. + * + * Unlike [maxValue], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("maxValue") @ExcludeMissing fun _maxValue(): JsonField = maxValue + + /** + * Returns the raw JSON value of [minLength]. + * + * Unlike [minLength], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("minLength") @ExcludeMissing fun _minLength(): JsonField = minLength + + /** + * Returns the raw JSON value of [minValue]. + * + * Unlike [minValue], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("minValue") @ExcludeMissing fun _minValue(): JsonField = minValue + + /** + * Returns the raw JSON value of [selectOptions]. + * + * Unlike [selectOptions], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("selectOptions") + @ExcludeMissing + fun _selectOptions(): JsonField> = selectOptions + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Schema]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Schema]. */ + class Builder internal constructor() { + + private var defaultValue: JsonField = JsonMissing.of() + private var isValueRequired: JsonField = JsonMissing.of() + private var maxLength: JsonField = JsonMissing.of() + private var maxValue: JsonField = JsonMissing.of() + private var minLength: JsonField = JsonMissing.of() + private var minValue: JsonField = JsonMissing.of() + private var selectOptions: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(schema: Schema) = apply { + defaultValue = schema.defaultValue + isValueRequired = schema.isValueRequired + maxLength = schema.maxLength + maxValue = schema.maxValue + minLength = schema.minLength + minValue = schema.minValue + selectOptions = schema.selectOptions.map { it.toMutableList() } + additionalProperties = schema.additionalProperties.toMutableMap() + } + + /** + * The default value for this custom metadata field. This property is only required if + * `isValueRequired` property is set to `true`. The value should match the `type` of + * custom metadata field. + */ + fun defaultValue(defaultValue: DefaultValue) = defaultValue(JsonField.of(defaultValue)) + + /** + * Sets [Builder.defaultValue] to an arbitrary JSON value. + * + * You should usually call [Builder.defaultValue] with a well-typed [DefaultValue] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun defaultValue(defaultValue: JsonField) = apply { + this.defaultValue = defaultValue + } + + /** Alias for calling [defaultValue] with `DefaultValue.ofString(string)`. */ + fun defaultValue(string: String) = defaultValue(DefaultValue.ofString(string)) + + /** Alias for calling [defaultValue] with `DefaultValue.ofNumber(number)`. */ + fun defaultValue(number: Double) = defaultValue(DefaultValue.ofNumber(number)) + + /** Alias for calling [defaultValue] with `DefaultValue.ofBool(bool)`. */ + fun defaultValue(bool: Boolean) = defaultValue(DefaultValue.ofBool(bool)) + + /** Alias for calling [defaultValue] with `DefaultValue.ofMixed(mixed)`. */ + fun defaultValueOfMixed(mixed: List) = + defaultValue(DefaultValue.ofMixed(mixed)) + + /** + * Sets this custom metadata field as required. Setting custom metadata fields on an + * asset will throw error if the value for all required fields are not present in upload + * or update asset API request body. + */ + fun isValueRequired(isValueRequired: Boolean) = + isValueRequired(JsonField.of(isValueRequired)) + + /** + * Sets [Builder.isValueRequired] to an arbitrary JSON value. + * + * You should usually call [Builder.isValueRequired] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun isValueRequired(isValueRequired: JsonField) = apply { + this.isValueRequired = isValueRequired + } + + /** + * Maximum length of string. Only set this property if `type` is set to `Text` or + * `Textarea`. + */ + fun maxLength(maxLength: Double) = maxLength(JsonField.of(maxLength)) + + /** + * Sets [Builder.maxLength] to an arbitrary JSON value. + * + * You should usually call [Builder.maxLength] with a well-typed [Double] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun maxLength(maxLength: JsonField) = apply { this.maxLength = maxLength } + + /** + * Maximum value of the field. Only set this property if field type is `Date` or + * `Number`. For `Date` type field, set the minimum date in ISO8601 string format. For + * `Number` type field, set the minimum numeric value. + */ + fun maxValue(maxValue: MaxValue) = maxValue(JsonField.of(maxValue)) + + /** + * Sets [Builder.maxValue] to an arbitrary JSON value. + * + * You should usually call [Builder.maxValue] with a well-typed [MaxValue] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun maxValue(maxValue: JsonField) = apply { this.maxValue = maxValue } + + /** Alias for calling [maxValue] with `MaxValue.ofString(string)`. */ + fun maxValue(string: String) = maxValue(MaxValue.ofString(string)) + + /** Alias for calling [maxValue] with `MaxValue.ofNumber(number)`. */ + fun maxValue(number: Double) = maxValue(MaxValue.ofNumber(number)) + + /** + * Minimum length of string. Only set this property if `type` is set to `Text` or + * `Textarea`. + */ + fun minLength(minLength: Double) = minLength(JsonField.of(minLength)) + + /** + * Sets [Builder.minLength] to an arbitrary JSON value. + * + * You should usually call [Builder.minLength] with a well-typed [Double] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun minLength(minLength: JsonField) = apply { this.minLength = minLength } + + /** + * Minimum value of the field. Only set this property if field type is `Date` or + * `Number`. For `Date` type field, set the minimum date in ISO8601 string format. For + * `Number` type field, set the minimum numeric value. + */ + fun minValue(minValue: MinValue) = minValue(JsonField.of(minValue)) + + /** + * Sets [Builder.minValue] to an arbitrary JSON value. + * + * You should usually call [Builder.minValue] with a well-typed [MinValue] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun minValue(minValue: JsonField) = apply { this.minValue = minValue } + + /** Alias for calling [minValue] with `MinValue.ofString(string)`. */ + fun minValue(string: String) = minValue(MinValue.ofString(string)) + + /** Alias for calling [minValue] with `MinValue.ofNumber(number)`. */ + fun minValue(number: Double) = minValue(MinValue.ofNumber(number)) + + /** + * An array of allowed values. This property is only required if `type` property is set + * to `SingleSelect` or `MultiSelect`. + */ + fun selectOptions(selectOptions: List) = + selectOptions(JsonField.of(selectOptions)) + + /** + * Sets [Builder.selectOptions] to an arbitrary JSON value. + * + * You should usually call [Builder.selectOptions] with a well-typed + * `List` value instead. This method is primarily for setting the field to + * an undocumented or not yet supported value. + */ + fun selectOptions(selectOptions: JsonField>) = apply { + this.selectOptions = selectOptions.map { it.toMutableList() } + } + + /** + * Adds a single [SelectOption] to [selectOptions]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addSelectOption(selectOption: SelectOption) = apply { + selectOptions = + (selectOptions ?: JsonField.of(mutableListOf())).also { + checkKnown("selectOptions", it).add(selectOption) + } + } + + /** Alias for calling [addSelectOption] with `SelectOption.ofString(string)`. */ + fun addSelectOption(string: String) = addSelectOption(SelectOption.ofString(string)) + + /** Alias for calling [addSelectOption] with `SelectOption.ofNumber(number)`. */ + fun addSelectOption(number: Double) = addSelectOption(SelectOption.ofNumber(number)) + + /** Alias for calling [addSelectOption] with `SelectOption.ofBool(bool)`. */ + fun addSelectOption(bool: Boolean) = addSelectOption(SelectOption.ofBool(bool)) + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Schema]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Schema = + Schema( + defaultValue, + isValueRequired, + maxLength, + maxValue, + minLength, + minValue, + (selectOptions ?: JsonMissing.of()).map { it.toImmutable() }, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Schema = apply { + if (validated) { + return@apply + } + + defaultValue().ifPresent { it.validate() } + isValueRequired() + maxLength() + maxValue().ifPresent { it.validate() } + minLength() + minValue().ifPresent { it.validate() } + selectOptions().ifPresent { it.forEach { it.validate() } } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (defaultValue.asKnown().getOrNull()?.validity() ?: 0) + + (if (isValueRequired.asKnown().isPresent) 1 else 0) + + (if (maxLength.asKnown().isPresent) 1 else 0) + + (maxValue.asKnown().getOrNull()?.validity() ?: 0) + + (if (minLength.asKnown().isPresent) 1 else 0) + + (minValue.asKnown().getOrNull()?.validity() ?: 0) + + (selectOptions.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + /** + * The default value for this custom metadata field. This property is only required if + * `isValueRequired` property is set to `true`. The value should match the `type` of custom + * metadata field. + */ + @JsonDeserialize(using = DefaultValue.Deserializer::class) + @JsonSerialize(using = DefaultValue.Serializer::class) + class DefaultValue + private constructor( + private val string: String? = null, + private val number: Double? = null, + private val bool: Boolean? = null, + private val mixed: List? = null, + private val _json: JsonValue? = null, + ) { + + fun string(): Optional = Optional.ofNullable(string) + + fun number(): Optional = Optional.ofNullable(number) + + fun bool(): Optional = Optional.ofNullable(bool) + + /** + * Default value should be of type array when custom metadata field type is set to + * `MultiSelect`. + */ + fun mixed(): Optional> = Optional.ofNullable(mixed) + + fun isString(): Boolean = string != null + + fun isNumber(): Boolean = number != null + + fun isBool(): Boolean = bool != null + + fun isMixed(): Boolean = mixed != null + + fun asString(): String = string.getOrThrow("string") + + fun asNumber(): Double = number.getOrThrow("number") + + fun asBool(): Boolean = bool.getOrThrow("bool") + + /** + * Default value should be of type array when custom metadata field type is set to + * `MultiSelect`. + */ + fun asMixed(): List = mixed.getOrThrow("mixed") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + string != null -> visitor.visitString(string) + number != null -> visitor.visitNumber(number) + bool != null -> visitor.visitBool(bool) + mixed != null -> visitor.visitMixed(mixed) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): DefaultValue = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitString(string: String) {} + + override fun visitNumber(number: Double) {} + + override fun visitBool(bool: Boolean) {} + + override fun visitMixed(mixed: List) { + mixed.forEach { it.validate() } + } + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitString(string: String) = 1 + + override fun visitNumber(number: Double) = 1 + + override fun visitBool(bool: Boolean) = 1 + + override fun visitMixed(mixed: List) = + mixed.sumOf { it.validity().toInt() } + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is DefaultValue && + string == other.string && + number == other.number && + bool == other.bool && + mixed == other.mixed + } + + override fun hashCode(): Int = Objects.hash(string, number, bool, mixed) + + override fun toString(): String = + when { + string != null -> "DefaultValue{string=$string}" + number != null -> "DefaultValue{number=$number}" + bool != null -> "DefaultValue{bool=$bool}" + mixed != null -> "DefaultValue{mixed=$mixed}" + _json != null -> "DefaultValue{_unknown=$_json}" + else -> throw IllegalStateException("Invalid DefaultValue") + } + + companion object { + + @JvmStatic fun ofString(string: String) = DefaultValue(string = string) + + @JvmStatic fun ofNumber(number: Double) = DefaultValue(number = number) + + @JvmStatic fun ofBool(bool: Boolean) = DefaultValue(bool = bool) + + /** + * Default value should be of type array when custom metadata field type is set to + * `MultiSelect`. + */ + @JvmStatic + fun ofMixed(mixed: List) = + DefaultValue(mixed = mixed.toImmutable()) + } + + /** + * An interface that defines how to map each variant of [DefaultValue] to a value of + * type [T]. + */ + interface Visitor { + + fun visitString(string: String): T + + fun visitNumber(number: Double): T + + fun visitBool(bool: Boolean): T + + /** + * Default value should be of type array when custom metadata field type is set to + * `MultiSelect`. + */ + fun visitMixed(mixed: List): T + + /** + * Maps an unknown variant of [DefaultValue] to a value of type [T]. + * + * An instance of [DefaultValue] can contain an unknown variant if it was + * deserialized from data that doesn't match any known variant. For example, if the + * SDK is on an older version than the API, then the API may respond with new + * variants that the SDK is unaware of. + * + * @throws ImageKitInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw ImageKitInvalidDataException("Unknown DefaultValue: $json") + } + } + + internal class Deserializer : BaseDeserializer(DefaultValue::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): DefaultValue { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + DefaultValue(string = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + DefaultValue(number = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + DefaultValue(bool = it, _json = json) + }, + tryDeserialize( + node, + jacksonTypeRef>(), + ) + ?.let { DefaultValue(mixed = it, _json = json) }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely incompatible + // with all the possible variants (e.g. deserializing from object). + 0 -> DefaultValue(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then use the + // first completely valid match, or simply the first match if none are + // completely valid. + else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() + } + } + } + + internal class Serializer : BaseSerializer(DefaultValue::class) { + + override fun serialize( + value: DefaultValue, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.string != null -> generator.writeObject(value.string) + value.number != null -> generator.writeObject(value.number) + value.bool != null -> generator.writeObject(value.bool) + value.mixed != null -> generator.writeObject(value.mixed) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid DefaultValue") + } + } + } + + @JsonDeserialize(using = UnnamedSchemaWithArrayParent2.Deserializer::class) + @JsonSerialize(using = UnnamedSchemaWithArrayParent2.Serializer::class) + class UnnamedSchemaWithArrayParent2 + private constructor( + private val string: String? = null, + private val number: Double? = null, + private val bool: Boolean? = null, + private val _json: JsonValue? = null, + ) { + + fun string(): Optional = Optional.ofNullable(string) + + fun number(): Optional = Optional.ofNullable(number) + + fun bool(): Optional = Optional.ofNullable(bool) + + fun isString(): Boolean = string != null + + fun isNumber(): Boolean = number != null + + fun isBool(): Boolean = bool != null + + fun asString(): String = string.getOrThrow("string") + + fun asNumber(): Double = number.getOrThrow("number") + + fun asBool(): Boolean = bool.getOrThrow("bool") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + string != null -> visitor.visitString(string) + number != null -> visitor.visitNumber(number) + bool != null -> visitor.visitBool(bool) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): UnnamedSchemaWithArrayParent2 = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitString(string: String) {} + + override fun visitNumber(number: Double) {} + + override fun visitBool(bool: Boolean) {} + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitString(string: String) = 1 + + override fun visitNumber(number: Double) = 1 + + override fun visitBool(bool: Boolean) = 1 + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is UnnamedSchemaWithArrayParent2 && + string == other.string && + number == other.number && + bool == other.bool + } + + override fun hashCode(): Int = Objects.hash(string, number, bool) + + override fun toString(): String = + when { + string != null -> "UnnamedSchemaWithArrayParent2{string=$string}" + number != null -> "UnnamedSchemaWithArrayParent2{number=$number}" + bool != null -> "UnnamedSchemaWithArrayParent2{bool=$bool}" + _json != null -> "UnnamedSchemaWithArrayParent2{_unknown=$_json}" + else -> throw IllegalStateException("Invalid UnnamedSchemaWithArrayParent2") + } + + companion object { + + @JvmStatic + fun ofString(string: String) = UnnamedSchemaWithArrayParent2(string = string) + + @JvmStatic + fun ofNumber(number: Double) = UnnamedSchemaWithArrayParent2(number = number) + + @JvmStatic + fun ofBool(bool: Boolean) = UnnamedSchemaWithArrayParent2(bool = bool) + } + + /** + * An interface that defines how to map each variant of + * [UnnamedSchemaWithArrayParent2] to a value of type [T]. + */ + interface Visitor { + + fun visitString(string: String): T + + fun visitNumber(number: Double): T + + fun visitBool(bool: Boolean): T + + /** + * Maps an unknown variant of [UnnamedSchemaWithArrayParent2] to a value of type + * [T]. + * + * An instance of [UnnamedSchemaWithArrayParent2] can contain an unknown variant + * if it was deserialized from data that doesn't match any known variant. For + * example, if the SDK is on an older version than the API, then the API may + * respond with new variants that the SDK is unaware of. + * + * @throws ImageKitInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw ImageKitInvalidDataException( + "Unknown UnnamedSchemaWithArrayParent2: $json" + ) + } + } + + internal class Deserializer : + BaseDeserializer( + UnnamedSchemaWithArrayParent2::class + ) { + + override fun ObjectCodec.deserialize( + node: JsonNode + ): UnnamedSchemaWithArrayParent2 { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + UnnamedSchemaWithArrayParent2(string = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + UnnamedSchemaWithArrayParent2(number = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + UnnamedSchemaWithArrayParent2(bool = it, _json = json) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely + // incompatible with all the possible variants (e.g. deserializing from + // object). + 0 -> UnnamedSchemaWithArrayParent2(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then use + // the first completely valid match, or simply the first match if none + // are completely valid. + else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() + } + } + } + + internal class Serializer : + BaseSerializer( + UnnamedSchemaWithArrayParent2::class + ) { + + override fun serialize( + value: UnnamedSchemaWithArrayParent2, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.string != null -> generator.writeObject(value.string) + value.number != null -> generator.writeObject(value.number) + value.bool != null -> generator.writeObject(value.bool) + value._json != null -> generator.writeObject(value._json) + else -> + throw IllegalStateException("Invalid UnnamedSchemaWithArrayParent2") + } + } + } + } + } + + /** + * Maximum value of the field. Only set this property if field type is `Date` or `Number`. + * For `Date` type field, set the minimum date in ISO8601 string format. For `Number` type + * field, set the minimum numeric value. + */ + @JsonDeserialize(using = MaxValue.Deserializer::class) + @JsonSerialize(using = MaxValue.Serializer::class) + class MaxValue + private constructor( + private val string: String? = null, + private val number: Double? = null, + private val _json: JsonValue? = null, + ) { + + fun string(): Optional = Optional.ofNullable(string) + + fun number(): Optional = Optional.ofNullable(number) + + fun isString(): Boolean = string != null + + fun isNumber(): Boolean = number != null + + fun asString(): String = string.getOrThrow("string") + + fun asNumber(): Double = number.getOrThrow("number") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + string != null -> visitor.visitString(string) + number != null -> visitor.visitNumber(number) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): MaxValue = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitString(string: String) {} + + override fun visitNumber(number: Double) {} + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitString(string: String) = 1 + + override fun visitNumber(number: Double) = 1 + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is MaxValue && string == other.string && number == other.number + } + + override fun hashCode(): Int = Objects.hash(string, number) + + override fun toString(): String = + when { + string != null -> "MaxValue{string=$string}" + number != null -> "MaxValue{number=$number}" + _json != null -> "MaxValue{_unknown=$_json}" + else -> throw IllegalStateException("Invalid MaxValue") + } + + companion object { + + @JvmStatic fun ofString(string: String) = MaxValue(string = string) + + @JvmStatic fun ofNumber(number: Double) = MaxValue(number = number) + } + + /** + * An interface that defines how to map each variant of [MaxValue] to a value of type + * [T]. + */ + interface Visitor { + + fun visitString(string: String): T + + fun visitNumber(number: Double): T + + /** + * Maps an unknown variant of [MaxValue] to a value of type [T]. + * + * An instance of [MaxValue] can contain an unknown variant if it was deserialized + * from data that doesn't match any known variant. For example, if the SDK is on an + * older version than the API, then the API may respond with new variants that the + * SDK is unaware of. + * + * @throws ImageKitInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw ImageKitInvalidDataException("Unknown MaxValue: $json") + } + } + + internal class Deserializer : BaseDeserializer(MaxValue::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): MaxValue { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + MaxValue(string = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + MaxValue(number = it, _json = json) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely incompatible + // with all the possible variants (e.g. deserializing from object). + 0 -> MaxValue(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then use the + // first completely valid match, or simply the first match if none are + // completely valid. + else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() + } + } + } + + internal class Serializer : BaseSerializer(MaxValue::class) { + + override fun serialize( + value: MaxValue, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.string != null -> generator.writeObject(value.string) + value.number != null -> generator.writeObject(value.number) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid MaxValue") + } + } + } + } + + /** + * Minimum value of the field. Only set this property if field type is `Date` or `Number`. + * For `Date` type field, set the minimum date in ISO8601 string format. For `Number` type + * field, set the minimum numeric value. + */ + @JsonDeserialize(using = MinValue.Deserializer::class) + @JsonSerialize(using = MinValue.Serializer::class) + class MinValue + private constructor( + private val string: String? = null, + private val number: Double? = null, + private val _json: JsonValue? = null, + ) { + + fun string(): Optional = Optional.ofNullable(string) + + fun number(): Optional = Optional.ofNullable(number) + + fun isString(): Boolean = string != null + + fun isNumber(): Boolean = number != null + + fun asString(): String = string.getOrThrow("string") + + fun asNumber(): Double = number.getOrThrow("number") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + string != null -> visitor.visitString(string) + number != null -> visitor.visitNumber(number) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): MinValue = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitString(string: String) {} + + override fun visitNumber(number: Double) {} + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitString(string: String) = 1 + + override fun visitNumber(number: Double) = 1 + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is MinValue && string == other.string && number == other.number + } + + override fun hashCode(): Int = Objects.hash(string, number) + + override fun toString(): String = + when { + string != null -> "MinValue{string=$string}" + number != null -> "MinValue{number=$number}" + _json != null -> "MinValue{_unknown=$_json}" + else -> throw IllegalStateException("Invalid MinValue") + } + + companion object { + + @JvmStatic fun ofString(string: String) = MinValue(string = string) + + @JvmStatic fun ofNumber(number: Double) = MinValue(number = number) + } + + /** + * An interface that defines how to map each variant of [MinValue] to a value of type + * [T]. + */ + interface Visitor { + + fun visitString(string: String): T + + fun visitNumber(number: Double): T + + /** + * Maps an unknown variant of [MinValue] to a value of type [T]. + * + * An instance of [MinValue] can contain an unknown variant if it was deserialized + * from data that doesn't match any known variant. For example, if the SDK is on an + * older version than the API, then the API may respond with new variants that the + * SDK is unaware of. + * + * @throws ImageKitInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw ImageKitInvalidDataException("Unknown MinValue: $json") + } + } + + internal class Deserializer : BaseDeserializer(MinValue::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): MinValue { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + MinValue(string = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + MinValue(number = it, _json = json) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely incompatible + // with all the possible variants (e.g. deserializing from object). + 0 -> MinValue(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then use the + // first completely valid match, or simply the first match if none are + // completely valid. + else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() + } + } + } + + internal class Serializer : BaseSerializer(MinValue::class) { + + override fun serialize( + value: MinValue, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.string != null -> generator.writeObject(value.string) + value.number != null -> generator.writeObject(value.number) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid MinValue") + } + } + } + } + + @JsonDeserialize(using = SelectOption.Deserializer::class) + @JsonSerialize(using = SelectOption.Serializer::class) + class SelectOption + private constructor( + private val string: String? = null, + private val number: Double? = null, + private val bool: Boolean? = null, + private val _json: JsonValue? = null, + ) { + + fun string(): Optional = Optional.ofNullable(string) + + fun number(): Optional = Optional.ofNullable(number) + + fun bool(): Optional = Optional.ofNullable(bool) + + fun isString(): Boolean = string != null + + fun isNumber(): Boolean = number != null + + fun isBool(): Boolean = bool != null + + fun asString(): String = string.getOrThrow("string") + + fun asNumber(): Double = number.getOrThrow("number") + + fun asBool(): Boolean = bool.getOrThrow("bool") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + string != null -> visitor.visitString(string) + number != null -> visitor.visitNumber(number) + bool != null -> visitor.visitBool(bool) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): SelectOption = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitString(string: String) {} + + override fun visitNumber(number: Double) {} + + override fun visitBool(bool: Boolean) {} + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitString(string: String) = 1 + + override fun visitNumber(number: Double) = 1 + + override fun visitBool(bool: Boolean) = 1 + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is SelectOption && + string == other.string && + number == other.number && + bool == other.bool + } + + override fun hashCode(): Int = Objects.hash(string, number, bool) + + override fun toString(): String = + when { + string != null -> "SelectOption{string=$string}" + number != null -> "SelectOption{number=$number}" + bool != null -> "SelectOption{bool=$bool}" + _json != null -> "SelectOption{_unknown=$_json}" + else -> throw IllegalStateException("Invalid SelectOption") + } + + companion object { + + @JvmStatic fun ofString(string: String) = SelectOption(string = string) + + @JvmStatic fun ofNumber(number: Double) = SelectOption(number = number) + + @JvmStatic fun ofBool(bool: Boolean) = SelectOption(bool = bool) + } + + /** + * An interface that defines how to map each variant of [SelectOption] to a value of + * type [T]. + */ + interface Visitor { + + fun visitString(string: String): T + + fun visitNumber(number: Double): T + + fun visitBool(bool: Boolean): T + + /** + * Maps an unknown variant of [SelectOption] to a value of type [T]. + * + * An instance of [SelectOption] can contain an unknown variant if it was + * deserialized from data that doesn't match any known variant. For example, if the + * SDK is on an older version than the API, then the API may respond with new + * variants that the SDK is unaware of. + * + * @throws ImageKitInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw ImageKitInvalidDataException("Unknown SelectOption: $json") + } + } + + internal class Deserializer : BaseDeserializer(SelectOption::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): SelectOption { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + SelectOption(string = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + SelectOption(number = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + SelectOption(bool = it, _json = json) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely incompatible + // with all the possible variants (e.g. deserializing from object). + 0 -> SelectOption(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then use the + // first completely valid match, or simply the first match if none are + // completely valid. + else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() + } + } + } + + internal class Serializer : BaseSerializer(SelectOption::class) { + + override fun serialize( + value: SelectOption, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.string != null -> generator.writeObject(value.string) + value.number != null -> generator.writeObject(value.number) + value.bool != null -> generator.writeObject(value.bool) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid SelectOption") + } + } + } + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Schema && + defaultValue == other.defaultValue && + isValueRequired == other.isValueRequired && + maxLength == other.maxLength && + maxValue == other.maxValue && + minLength == other.minLength && + minValue == other.minValue && + selectOptions == other.selectOptions && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + defaultValue, + isValueRequired, + maxLength, + maxValue, + minLength, + minValue, + selectOptions, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Schema{defaultValue=$defaultValue, isValueRequired=$isValueRequired, maxLength=$maxLength, maxValue=$maxValue, minLength=$minLength, minValue=$minValue, selectOptions=$selectOptions, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is CustomMetadataFieldUpdateParams && + id == other.id && + body == other.body && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = Objects.hash(id, body, additionalHeaders, additionalQueryParams) + + override fun toString() = + "CustomMetadataFieldUpdateParams{id=$id, body=$body, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/files/File.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/files/File.kt new file mode 100644 index 0000000..f0b39c8 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/files/File.kt @@ -0,0 +1,1658 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.files + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.imagekit.api.core.Enum +import com.imagekit.api.core.ExcludeMissing +import com.imagekit.api.core.JsonField +import com.imagekit.api.core.JsonMissing +import com.imagekit.api.core.JsonValue +import com.imagekit.api.core.checkKnown +import com.imagekit.api.core.toImmutable +import com.imagekit.api.errors.ImageKitInvalidDataException +import java.time.OffsetDateTime +import java.util.Collections +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** Object containing details of a file or file version. */ +class File +private constructor( + private val aiTags: JsonField>, + private val createdAt: JsonField, + private val customCoordinates: JsonField, + private val customMetadata: JsonField, + private val description: JsonField, + private val fileId: JsonField, + private val filePath: JsonField, + private val fileType: JsonField, + private val hasAlpha: JsonField, + private val height: JsonField, + private val isPrivateFile: JsonField, + private val isPublished: JsonField, + private val mime: JsonField, + private val name: JsonField, + private val size: JsonField, + private val tags: JsonField>, + private val thumbnail: JsonField, + private val type: JsonField, + private val updatedAt: JsonField, + private val url: JsonField, + private val versionInfo: JsonField, + private val width: JsonField, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("AITags") @ExcludeMissing aiTags: JsonField> = JsonMissing.of(), + @JsonProperty("createdAt") + @ExcludeMissing + createdAt: JsonField = JsonMissing.of(), + @JsonProperty("customCoordinates") + @ExcludeMissing + customCoordinates: JsonField = JsonMissing.of(), + @JsonProperty("customMetadata") + @ExcludeMissing + customMetadata: JsonField = JsonMissing.of(), + @JsonProperty("description") + @ExcludeMissing + description: JsonField = JsonMissing.of(), + @JsonProperty("fileId") @ExcludeMissing fileId: JsonField = JsonMissing.of(), + @JsonProperty("filePath") @ExcludeMissing filePath: JsonField = JsonMissing.of(), + @JsonProperty("fileType") @ExcludeMissing fileType: JsonField = JsonMissing.of(), + @JsonProperty("hasAlpha") @ExcludeMissing hasAlpha: JsonField = JsonMissing.of(), + @JsonProperty("height") @ExcludeMissing height: JsonField = JsonMissing.of(), + @JsonProperty("isPrivateFile") + @ExcludeMissing + isPrivateFile: JsonField = JsonMissing.of(), + @JsonProperty("isPublished") + @ExcludeMissing + isPublished: JsonField = JsonMissing.of(), + @JsonProperty("mime") @ExcludeMissing mime: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("size") @ExcludeMissing size: JsonField = JsonMissing.of(), + @JsonProperty("tags") @ExcludeMissing tags: JsonField> = JsonMissing.of(), + @JsonProperty("thumbnail") @ExcludeMissing thumbnail: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonField = JsonMissing.of(), + @JsonProperty("updatedAt") + @ExcludeMissing + updatedAt: JsonField = JsonMissing.of(), + @JsonProperty("url") @ExcludeMissing url: JsonField = JsonMissing.of(), + @JsonProperty("versionInfo") + @ExcludeMissing + versionInfo: JsonField = JsonMissing.of(), + @JsonProperty("width") @ExcludeMissing width: JsonField = JsonMissing.of(), + ) : this( + aiTags, + createdAt, + customCoordinates, + customMetadata, + description, + fileId, + filePath, + fileType, + hasAlpha, + height, + isPrivateFile, + isPublished, + mime, + name, + size, + tags, + thumbnail, + type, + updatedAt, + url, + versionInfo, + width, + mutableMapOf(), + ) + + /** + * An array of tags assigned to the file by auto tagging. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun aiTags(): Optional> = aiTags.getOptional("AITags") + + /** + * Date and time when the file was uploaded. The date and time is in ISO8601 format. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun createdAt(): Optional = createdAt.getOptional("createdAt") + + /** + * An string with custom coordinates of the file. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun customCoordinates(): Optional = customCoordinates.getOptional("customCoordinates") + + /** + * An object with custom metadata for the file. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun customMetadata(): Optional = customMetadata.getOptional("customMetadata") + + /** + * Optional text to describe the contents of the file. Can be set by the user or the + * ai-auto-description extension. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun description(): Optional = description.getOptional("description") + + /** + * Unique identifier of the asset. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun fileId(): Optional = fileId.getOptional("fileId") + + /** + * Path of the file. This is the path you would use in the URL to access the file. For example, + * if the file is at the root of the media library, the path will be `/file.jpg`. If the file is + * inside a folder named `images`, the path will be `/images/file.jpg`. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun filePath(): Optional = filePath.getOptional("filePath") + + /** + * Type of the file. Possible values are `image`, `non-image`. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun fileType(): Optional = fileType.getOptional("fileType") + + /** + * Specifies if the image has an alpha channel. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun hasAlpha(): Optional = hasAlpha.getOptional("hasAlpha") + + /** + * Height of the file. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun height(): Optional = height.getOptional("height") + + /** + * Specifies if the file is private or not. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun isPrivateFile(): Optional = isPrivateFile.getOptional("isPrivateFile") + + /** + * Specifies if the file is published or not. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun isPublished(): Optional = isPublished.getOptional("isPublished") + + /** + * MIME type of the file. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun mime(): Optional = mime.getOptional("mime") + + /** + * Name of the asset. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun name(): Optional = name.getOptional("name") + + /** + * Size of the file in bytes. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun size(): Optional = size.getOptional("size") + + /** + * An array of tags assigned to the file. Tags are used to search files in the media library. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun tags(): Optional> = tags.getOptional("tags") + + /** + * URL of the thumbnail image. This URL is used to access the thumbnail image of the file in the + * media library. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun thumbnail(): Optional = thumbnail.getOptional("thumbnail") + + /** + * Type of the asset. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun type(): Optional = type.getOptional("type") + + /** + * Date and time when the file was last updated. The date and time is in ISO8601 format. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun updatedAt(): Optional = updatedAt.getOptional("updatedAt") + + /** + * URL of the file. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun url(): Optional = url.getOptional("url") + + /** + * An object with details of the file version. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun versionInfo(): Optional = versionInfo.getOptional("versionInfo") + + /** + * Width of the file. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun width(): Optional = width.getOptional("width") + + /** + * Returns the raw JSON value of [aiTags]. + * + * Unlike [aiTags], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("AITags") @ExcludeMissing fun _aiTags(): JsonField> = aiTags + + /** + * Returns the raw JSON value of [createdAt]. + * + * Unlike [createdAt], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("createdAt") + @ExcludeMissing + fun _createdAt(): JsonField = createdAt + + /** + * Returns the raw JSON value of [customCoordinates]. + * + * Unlike [customCoordinates], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("customCoordinates") + @ExcludeMissing + fun _customCoordinates(): JsonField = customCoordinates + + /** + * Returns the raw JSON value of [customMetadata]. + * + * Unlike [customMetadata], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("customMetadata") + @ExcludeMissing + fun _customMetadata(): JsonField = customMetadata + + /** + * Returns the raw JSON value of [description]. + * + * Unlike [description], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("description") @ExcludeMissing fun _description(): JsonField = description + + /** + * Returns the raw JSON value of [fileId]. + * + * Unlike [fileId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("fileId") @ExcludeMissing fun _fileId(): JsonField = fileId + + /** + * Returns the raw JSON value of [filePath]. + * + * Unlike [filePath], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("filePath") @ExcludeMissing fun _filePath(): JsonField = filePath + + /** + * Returns the raw JSON value of [fileType]. + * + * Unlike [fileType], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("fileType") @ExcludeMissing fun _fileType(): JsonField = fileType + + /** + * Returns the raw JSON value of [hasAlpha]. + * + * Unlike [hasAlpha], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("hasAlpha") @ExcludeMissing fun _hasAlpha(): JsonField = hasAlpha + + /** + * Returns the raw JSON value of [height]. + * + * Unlike [height], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("height") @ExcludeMissing fun _height(): JsonField = height + + /** + * Returns the raw JSON value of [isPrivateFile]. + * + * Unlike [isPrivateFile], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("isPrivateFile") + @ExcludeMissing + fun _isPrivateFile(): JsonField = isPrivateFile + + /** + * Returns the raw JSON value of [isPublished]. + * + * Unlike [isPublished], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("isPublished") + @ExcludeMissing + fun _isPublished(): JsonField = isPublished + + /** + * Returns the raw JSON value of [mime]. + * + * Unlike [mime], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("mime") @ExcludeMissing fun _mime(): JsonField = mime + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + + /** + * Returns the raw JSON value of [size]. + * + * Unlike [size], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("size") @ExcludeMissing fun _size(): JsonField = size + + /** + * Returns the raw JSON value of [tags]. + * + * Unlike [tags], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("tags") @ExcludeMissing fun _tags(): JsonField> = tags + + /** + * Returns the raw JSON value of [thumbnail]. + * + * Unlike [thumbnail], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("thumbnail") @ExcludeMissing fun _thumbnail(): JsonField = thumbnail + + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + + /** + * Returns the raw JSON value of [updatedAt]. + * + * Unlike [updatedAt], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("updatedAt") + @ExcludeMissing + fun _updatedAt(): JsonField = updatedAt + + /** + * Returns the raw JSON value of [url]. + * + * Unlike [url], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("url") @ExcludeMissing fun _url(): JsonField = url + + /** + * Returns the raw JSON value of [versionInfo]. + * + * Unlike [versionInfo], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("versionInfo") + @ExcludeMissing + fun _versionInfo(): JsonField = versionInfo + + /** + * Returns the raw JSON value of [width]. + * + * Unlike [width], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("width") @ExcludeMissing fun _width(): JsonField = width + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [File]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [File]. */ + class Builder internal constructor() { + + private var aiTags: JsonField>? = null + private var createdAt: JsonField = JsonMissing.of() + private var customCoordinates: JsonField = JsonMissing.of() + private var customMetadata: JsonField = JsonMissing.of() + private var description: JsonField = JsonMissing.of() + private var fileId: JsonField = JsonMissing.of() + private var filePath: JsonField = JsonMissing.of() + private var fileType: JsonField = JsonMissing.of() + private var hasAlpha: JsonField = JsonMissing.of() + private var height: JsonField = JsonMissing.of() + private var isPrivateFile: JsonField = JsonMissing.of() + private var isPublished: JsonField = JsonMissing.of() + private var mime: JsonField = JsonMissing.of() + private var name: JsonField = JsonMissing.of() + private var size: JsonField = JsonMissing.of() + private var tags: JsonField>? = null + private var thumbnail: JsonField = JsonMissing.of() + private var type: JsonField = JsonMissing.of() + private var updatedAt: JsonField = JsonMissing.of() + private var url: JsonField = JsonMissing.of() + private var versionInfo: JsonField = JsonMissing.of() + private var width: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(file: File) = apply { + aiTags = file.aiTags.map { it.toMutableList() } + createdAt = file.createdAt + customCoordinates = file.customCoordinates + customMetadata = file.customMetadata + description = file.description + fileId = file.fileId + filePath = file.filePath + fileType = file.fileType + hasAlpha = file.hasAlpha + height = file.height + isPrivateFile = file.isPrivateFile + isPublished = file.isPublished + mime = file.mime + name = file.name + size = file.size + tags = file.tags.map { it.toMutableList() } + thumbnail = file.thumbnail + type = file.type + updatedAt = file.updatedAt + url = file.url + versionInfo = file.versionInfo + width = file.width + additionalProperties = file.additionalProperties.toMutableMap() + } + + /** An array of tags assigned to the file by auto tagging. */ + fun aiTags(aiTags: List?) = aiTags(JsonField.ofNullable(aiTags)) + + /** Alias for calling [Builder.aiTags] with `aiTags.orElse(null)`. */ + fun aiTags(aiTags: Optional>) = aiTags(aiTags.getOrNull()) + + /** + * Sets [Builder.aiTags] to an arbitrary JSON value. + * + * You should usually call [Builder.aiTags] with a well-typed `List` value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun aiTags(aiTags: JsonField>) = apply { + this.aiTags = aiTags.map { it.toMutableList() } + } + + /** + * Adds a single [AiTag] to [aiTags]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addAiTag(aiTag: AiTag) = apply { + aiTags = + (aiTags ?: JsonField.of(mutableListOf())).also { + checkKnown("aiTags", it).add(aiTag) + } + } + + /** Date and time when the file was uploaded. The date and time is in ISO8601 format. */ + fun createdAt(createdAt: OffsetDateTime) = createdAt(JsonField.of(createdAt)) + + /** + * Sets [Builder.createdAt] to an arbitrary JSON value. + * + * You should usually call [Builder.createdAt] with a well-typed [OffsetDateTime] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun createdAt(createdAt: JsonField) = apply { this.createdAt = createdAt } + + /** An string with custom coordinates of the file. */ + fun customCoordinates(customCoordinates: String?) = + customCoordinates(JsonField.ofNullable(customCoordinates)) + + /** Alias for calling [Builder.customCoordinates] with `customCoordinates.orElse(null)`. */ + fun customCoordinates(customCoordinates: Optional) = + customCoordinates(customCoordinates.getOrNull()) + + /** + * Sets [Builder.customCoordinates] to an arbitrary JSON value. + * + * You should usually call [Builder.customCoordinates] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun customCoordinates(customCoordinates: JsonField) = apply { + this.customCoordinates = customCoordinates + } + + /** An object with custom metadata for the file. */ + fun customMetadata(customMetadata: CustomMetadata) = + customMetadata(JsonField.of(customMetadata)) + + /** + * Sets [Builder.customMetadata] to an arbitrary JSON value. + * + * You should usually call [Builder.customMetadata] with a well-typed [CustomMetadata] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun customMetadata(customMetadata: JsonField) = apply { + this.customMetadata = customMetadata + } + + /** + * Optional text to describe the contents of the file. Can be set by the user or the + * ai-auto-description extension. + */ + fun description(description: String) = description(JsonField.of(description)) + + /** + * Sets [Builder.description] to an arbitrary JSON value. + * + * You should usually call [Builder.description] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun description(description: JsonField) = apply { this.description = description } + + /** Unique identifier of the asset. */ + fun fileId(fileId: String) = fileId(JsonField.of(fileId)) + + /** + * Sets [Builder.fileId] to an arbitrary JSON value. + * + * You should usually call [Builder.fileId] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun fileId(fileId: JsonField) = apply { this.fileId = fileId } + + /** + * Path of the file. This is the path you would use in the URL to access the file. For + * example, if the file is at the root of the media library, the path will be `/file.jpg`. + * If the file is inside a folder named `images`, the path will be `/images/file.jpg`. + */ + fun filePath(filePath: String) = filePath(JsonField.of(filePath)) + + /** + * Sets [Builder.filePath] to an arbitrary JSON value. + * + * You should usually call [Builder.filePath] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun filePath(filePath: JsonField) = apply { this.filePath = filePath } + + /** Type of the file. Possible values are `image`, `non-image`. */ + fun fileType(fileType: String) = fileType(JsonField.of(fileType)) + + /** + * Sets [Builder.fileType] to an arbitrary JSON value. + * + * You should usually call [Builder.fileType] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun fileType(fileType: JsonField) = apply { this.fileType = fileType } + + /** Specifies if the image has an alpha channel. */ + fun hasAlpha(hasAlpha: Boolean) = hasAlpha(JsonField.of(hasAlpha)) + + /** + * Sets [Builder.hasAlpha] to an arbitrary JSON value. + * + * You should usually call [Builder.hasAlpha] with a well-typed [Boolean] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun hasAlpha(hasAlpha: JsonField) = apply { this.hasAlpha = hasAlpha } + + /** Height of the file. */ + fun height(height: Double) = height(JsonField.of(height)) + + /** + * Sets [Builder.height] to an arbitrary JSON value. + * + * You should usually call [Builder.height] with a well-typed [Double] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun height(height: JsonField) = apply { this.height = height } + + /** Specifies if the file is private or not. */ + fun isPrivateFile(isPrivateFile: Boolean) = isPrivateFile(JsonField.of(isPrivateFile)) + + /** + * Sets [Builder.isPrivateFile] to an arbitrary JSON value. + * + * You should usually call [Builder.isPrivateFile] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun isPrivateFile(isPrivateFile: JsonField) = apply { + this.isPrivateFile = isPrivateFile + } + + /** Specifies if the file is published or not. */ + fun isPublished(isPublished: Boolean) = isPublished(JsonField.of(isPublished)) + + /** + * Sets [Builder.isPublished] to an arbitrary JSON value. + * + * You should usually call [Builder.isPublished] with a well-typed [Boolean] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun isPublished(isPublished: JsonField) = apply { this.isPublished = isPublished } + + /** MIME type of the file. */ + fun mime(mime: String) = mime(JsonField.of(mime)) + + /** + * Sets [Builder.mime] to an arbitrary JSON value. + * + * You should usually call [Builder.mime] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun mime(mime: JsonField) = apply { this.mime = mime } + + /** Name of the asset. */ + fun name(name: String) = name(JsonField.of(name)) + + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun name(name: JsonField) = apply { this.name = name } + + /** Size of the file in bytes. */ + fun size(size: Double) = size(JsonField.of(size)) + + /** + * Sets [Builder.size] to an arbitrary JSON value. + * + * You should usually call [Builder.size] with a well-typed [Double] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun size(size: JsonField) = apply { this.size = size } + + /** + * An array of tags assigned to the file. Tags are used to search files in the media + * library. + */ + fun tags(tags: List?) = tags(JsonField.ofNullable(tags)) + + /** Alias for calling [Builder.tags] with `tags.orElse(null)`. */ + fun tags(tags: Optional>) = tags(tags.getOrNull()) + + /** + * Sets [Builder.tags] to an arbitrary JSON value. + * + * You should usually call [Builder.tags] with a well-typed `List` value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun tags(tags: JsonField>) = apply { + this.tags = tags.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [tags]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addTag(tag: String) = apply { + tags = (tags ?: JsonField.of(mutableListOf())).also { checkKnown("tags", it).add(tag) } + } + + /** + * URL of the thumbnail image. This URL is used to access the thumbnail image of the file in + * the media library. + */ + fun thumbnail(thumbnail: String) = thumbnail(JsonField.of(thumbnail)) + + /** + * Sets [Builder.thumbnail] to an arbitrary JSON value. + * + * You should usually call [Builder.thumbnail] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun thumbnail(thumbnail: JsonField) = apply { this.thumbnail = thumbnail } + + /** Type of the asset. */ + fun type(type: Type) = type(JsonField.of(type)) + + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [Type] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun type(type: JsonField) = apply { this.type = type } + + /** Date and time when the file was last updated. The date and time is in ISO8601 format. */ + fun updatedAt(updatedAt: OffsetDateTime) = updatedAt(JsonField.of(updatedAt)) + + /** + * Sets [Builder.updatedAt] to an arbitrary JSON value. + * + * You should usually call [Builder.updatedAt] with a well-typed [OffsetDateTime] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun updatedAt(updatedAt: JsonField) = apply { this.updatedAt = updatedAt } + + /** URL of the file. */ + fun url(url: String) = url(JsonField.of(url)) + + /** + * Sets [Builder.url] to an arbitrary JSON value. + * + * You should usually call [Builder.url] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun url(url: JsonField) = apply { this.url = url } + + /** An object with details of the file version. */ + fun versionInfo(versionInfo: VersionInfo) = versionInfo(JsonField.of(versionInfo)) + + /** + * Sets [Builder.versionInfo] to an arbitrary JSON value. + * + * You should usually call [Builder.versionInfo] with a well-typed [VersionInfo] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun versionInfo(versionInfo: JsonField) = apply { + this.versionInfo = versionInfo + } + + /** Width of the file. */ + fun width(width: Double) = width(JsonField.of(width)) + + /** + * Sets [Builder.width] to an arbitrary JSON value. + * + * You should usually call [Builder.width] with a well-typed [Double] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun width(width: JsonField) = apply { this.width = width } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [File]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): File = + File( + (aiTags ?: JsonMissing.of()).map { it.toImmutable() }, + createdAt, + customCoordinates, + customMetadata, + description, + fileId, + filePath, + fileType, + hasAlpha, + height, + isPrivateFile, + isPublished, + mime, + name, + size, + (tags ?: JsonMissing.of()).map { it.toImmutable() }, + thumbnail, + type, + updatedAt, + url, + versionInfo, + width, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): File = apply { + if (validated) { + return@apply + } + + aiTags().ifPresent { it.forEach { it.validate() } } + createdAt() + customCoordinates() + customMetadata().ifPresent { it.validate() } + description() + fileId() + filePath() + fileType() + hasAlpha() + height() + isPrivateFile() + isPublished() + mime() + name() + size() + tags() + thumbnail() + type().ifPresent { it.validate() } + updatedAt() + url() + versionInfo().ifPresent { it.validate() } + width() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (aiTags.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + (if (createdAt.asKnown().isPresent) 1 else 0) + + (if (customCoordinates.asKnown().isPresent) 1 else 0) + + (customMetadata.asKnown().getOrNull()?.validity() ?: 0) + + (if (description.asKnown().isPresent) 1 else 0) + + (if (fileId.asKnown().isPresent) 1 else 0) + + (if (filePath.asKnown().isPresent) 1 else 0) + + (if (fileType.asKnown().isPresent) 1 else 0) + + (if (hasAlpha.asKnown().isPresent) 1 else 0) + + (if (height.asKnown().isPresent) 1 else 0) + + (if (isPrivateFile.asKnown().isPresent) 1 else 0) + + (if (isPublished.asKnown().isPresent) 1 else 0) + + (if (mime.asKnown().isPresent) 1 else 0) + + (if (name.asKnown().isPresent) 1 else 0) + + (if (size.asKnown().isPresent) 1 else 0) + + (tags.asKnown().getOrNull()?.size ?: 0) + + (if (thumbnail.asKnown().isPresent) 1 else 0) + + (type.asKnown().getOrNull()?.validity() ?: 0) + + (if (updatedAt.asKnown().isPresent) 1 else 0) + + (if (url.asKnown().isPresent) 1 else 0) + + (versionInfo.asKnown().getOrNull()?.validity() ?: 0) + + (if (width.asKnown().isPresent) 1 else 0) + + class AiTag + private constructor( + private val confidence: JsonField, + private val name: JsonField, + private val source: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("confidence") + @ExcludeMissing + confidence: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("source") @ExcludeMissing source: JsonField = JsonMissing.of(), + ) : this(confidence, name, source, mutableMapOf()) + + /** + * Confidence score of the tag. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun confidence(): Optional = confidence.getOptional("confidence") + + /** + * Name of the tag. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun name(): Optional = name.getOptional("name") + + /** + * Source of the tag. Possible values are `google-auto-tagging` and `aws-auto-tagging`. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun source(): Optional = source.getOptional("source") + + /** + * Returns the raw JSON value of [confidence]. + * + * Unlike [confidence], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("confidence") + @ExcludeMissing + fun _confidence(): JsonField = confidence + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + + /** + * Returns the raw JSON value of [source]. + * + * Unlike [source], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("source") @ExcludeMissing fun _source(): JsonField = source + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [AiTag]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [AiTag]. */ + class Builder internal constructor() { + + private var confidence: JsonField = JsonMissing.of() + private var name: JsonField = JsonMissing.of() + private var source: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(aiTag: AiTag) = apply { + confidence = aiTag.confidence + name = aiTag.name + source = aiTag.source + additionalProperties = aiTag.additionalProperties.toMutableMap() + } + + /** Confidence score of the tag. */ + fun confidence(confidence: Double) = confidence(JsonField.of(confidence)) + + /** + * Sets [Builder.confidence] to an arbitrary JSON value. + * + * You should usually call [Builder.confidence] with a well-typed [Double] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun confidence(confidence: JsonField) = apply { this.confidence = confidence } + + /** Name of the tag. */ + fun name(name: String) = name(JsonField.of(name)) + + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun name(name: JsonField) = apply { this.name = name } + + /** + * Source of the tag. Possible values are `google-auto-tagging` and `aws-auto-tagging`. + */ + fun source(source: String) = source(JsonField.of(source)) + + /** + * Sets [Builder.source] to an arbitrary JSON value. + * + * You should usually call [Builder.source] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun source(source: JsonField) = apply { this.source = source } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [AiTag]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): AiTag = + AiTag(confidence, name, source, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): AiTag = apply { + if (validated) { + return@apply + } + + confidence() + name() + source() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (confidence.asKnown().isPresent) 1 else 0) + + (if (name.asKnown().isPresent) 1 else 0) + + (if (source.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is AiTag && + confidence == other.confidence && + name == other.name && + source == other.source && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(confidence, name, source, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "AiTag{confidence=$confidence, name=$name, source=$source, additionalProperties=$additionalProperties}" + } + + /** An object with custom metadata for the file. */ + class CustomMetadata + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [CustomMetadata]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [CustomMetadata]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(customMetadata: CustomMetadata) = apply { + additionalProperties = customMetadata.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [CustomMetadata]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): CustomMetadata = CustomMetadata(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): CustomMetadata = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is CustomMetadata && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "CustomMetadata{additionalProperties=$additionalProperties}" + } + + /** Type of the asset. */ + class Type @JsonCreator private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is on an + * older version than the API, then the API may respond with new members that the SDK is + * unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val FILE = of("file") + + @JvmField val FILE_VERSION = of("file-version") + + @JvmStatic fun of(value: String) = Type(JsonField.of(value)) + } + + /** An enum containing [Type]'s known values. */ + enum class Known { + FILE, + FILE_VERSION, + } + + /** + * An enum containing [Type]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [Type] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if the + * SDK is on an older version than the API, then the API may respond with new members that + * the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + FILE, + FILE_VERSION, + /** An enum member indicating that [Type] was instantiated with an unknown value. */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] + * if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you want + * to throw for the unknown case. + */ + fun value(): Value = + when (this) { + FILE -> Value.FILE + FILE_VERSION -> Value.FILE_VERSION + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and don't + * want to throw for the unknown case. + * + * @throws ImageKitInvalidDataException if this class instance's value is a not a known + * member. + */ + fun known(): Known = + when (this) { + FILE -> Known.FILE + FILE_VERSION -> Known.FILE_VERSION + else -> throw ImageKitInvalidDataException("Unknown Type: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for debugging + * and generally doesn't throw. + * + * @throws ImageKitInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + ImageKitInvalidDataException("Value is not a String") + } + + private var validated: Boolean = false + + fun validate(): Type = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Type && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + /** An object with details of the file version. */ + class VersionInfo + private constructor( + private val id: JsonField, + private val name: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + ) : this(id, name, mutableMapOf()) + + /** + * Unique identifier of the file version. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun id(): Optional = id.getOptional("id") + + /** + * Name of the file version. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun name(): Optional = name.getOptional("name") + + /** + * Returns the raw JSON value of [id]. + * + * Unlike [id], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [VersionInfo]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [VersionInfo]. */ + class Builder internal constructor() { + + private var id: JsonField = JsonMissing.of() + private var name: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(versionInfo: VersionInfo) = apply { + id = versionInfo.id + name = versionInfo.name + additionalProperties = versionInfo.additionalProperties.toMutableMap() + } + + /** Unique identifier of the file version. */ + fun id(id: String) = id(JsonField.of(id)) + + /** + * Sets [Builder.id] to an arbitrary JSON value. + * + * You should usually call [Builder.id] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun id(id: JsonField) = apply { this.id = id } + + /** Name of the file version. */ + fun name(name: String) = name(JsonField.of(name)) + + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun name(name: JsonField) = apply { this.name = name } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [VersionInfo]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): VersionInfo = VersionInfo(id, name, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): VersionInfo = apply { + if (validated) { + return@apply + } + + id() + name() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (id.asKnown().isPresent) 1 else 0) + (if (name.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is VersionInfo && + id == other.id && + name == other.name && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(id, name, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "VersionInfo{id=$id, name=$name, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is File && + aiTags == other.aiTags && + createdAt == other.createdAt && + customCoordinates == other.customCoordinates && + customMetadata == other.customMetadata && + description == other.description && + fileId == other.fileId && + filePath == other.filePath && + fileType == other.fileType && + hasAlpha == other.hasAlpha && + height == other.height && + isPrivateFile == other.isPrivateFile && + isPublished == other.isPublished && + mime == other.mime && + name == other.name && + size == other.size && + tags == other.tags && + thumbnail == other.thumbnail && + type == other.type && + updatedAt == other.updatedAt && + url == other.url && + versionInfo == other.versionInfo && + width == other.width && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + aiTags, + createdAt, + customCoordinates, + customMetadata, + description, + fileId, + filePath, + fileType, + hasAlpha, + height, + isPrivateFile, + isPublished, + mime, + name, + size, + tags, + thumbnail, + type, + updatedAt, + url, + versionInfo, + width, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "File{aiTags=$aiTags, createdAt=$createdAt, customCoordinates=$customCoordinates, customMetadata=$customMetadata, description=$description, fileId=$fileId, filePath=$filePath, fileType=$fileType, hasAlpha=$hasAlpha, height=$height, isPrivateFile=$isPrivateFile, isPublished=$isPublished, mime=$mime, name=$name, size=$size, tags=$tags, thumbnail=$thumbnail, type=$type, updatedAt=$updatedAt, url=$url, versionInfo=$versionInfo, width=$width, additionalProperties=$additionalProperties}" +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/files/FileCopyParams.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/files/FileCopyParams.kt new file mode 100644 index 0000000..7fb1d9d --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/files/FileCopyParams.kt @@ -0,0 +1,602 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.files + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.imagekit.api.core.ExcludeMissing +import com.imagekit.api.core.JsonField +import com.imagekit.api.core.JsonMissing +import com.imagekit.api.core.JsonValue +import com.imagekit.api.core.Params +import com.imagekit.api.core.checkRequired +import com.imagekit.api.core.http.Headers +import com.imagekit.api.core.http.QueryParams +import com.imagekit.api.errors.ImageKitInvalidDataException +import java.util.Collections +import java.util.Objects +import java.util.Optional + +/** + * This will copy a file from one folder to another. + * + * Note: If any file at the destination has the same name as the source file, then the source file + * and its versions (if `includeFileVersions` is set to true) will be appended to the destination + * file version history. + */ +class FileCopyParams +private constructor( + private val body: Body, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** + * Full path to the folder you want to copy the above file into. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun destinationPath(): String = body.destinationPath() + + /** + * The full path of the file you want to copy. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun sourceFilePath(): String = body.sourceFilePath() + + /** + * Option to copy all versions of a file. By default, only the current version of the file is + * copied. When set to true, all versions of the file will be copied. Default value - `false`. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun includeFileVersions(): Optional = body.includeFileVersions() + + /** + * Returns the raw JSON value of [destinationPath]. + * + * Unlike [destinationPath], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _destinationPath(): JsonField = body._destinationPath() + + /** + * Returns the raw JSON value of [sourceFilePath]. + * + * Unlike [sourceFilePath], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _sourceFilePath(): JsonField = body._sourceFilePath() + + /** + * Returns the raw JSON value of [includeFileVersions]. + * + * Unlike [includeFileVersions], this method doesn't throw if the JSON field has an unexpected + * type. + */ + fun _includeFileVersions(): JsonField = body._includeFileVersions() + + fun _additionalBodyProperties(): Map = body._additionalProperties() + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [FileCopyParams]. + * + * The following fields are required: + * ```java + * .destinationPath() + * .sourceFilePath() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [FileCopyParams]. */ + class Builder internal constructor() { + + private var body: Body.Builder = Body.builder() + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + + @JvmSynthetic + internal fun from(fileCopyParams: FileCopyParams) = apply { + body = fileCopyParams.body.toBuilder() + additionalHeaders = fileCopyParams.additionalHeaders.toBuilder() + additionalQueryParams = fileCopyParams.additionalQueryParams.toBuilder() + } + + /** + * Sets the entire request body. + * + * This is generally only useful if you are already constructing the body separately. + * Otherwise, it's more convenient to use the top-level setters instead: + * - [destinationPath] + * - [sourceFilePath] + * - [includeFileVersions] + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } + + /** Full path to the folder you want to copy the above file into. */ + fun destinationPath(destinationPath: String) = apply { + body.destinationPath(destinationPath) + } + + /** + * Sets [Builder.destinationPath] to an arbitrary JSON value. + * + * You should usually call [Builder.destinationPath] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun destinationPath(destinationPath: JsonField) = apply { + body.destinationPath(destinationPath) + } + + /** The full path of the file you want to copy. */ + fun sourceFilePath(sourceFilePath: String) = apply { body.sourceFilePath(sourceFilePath) } + + /** + * Sets [Builder.sourceFilePath] to an arbitrary JSON value. + * + * You should usually call [Builder.sourceFilePath] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun sourceFilePath(sourceFilePath: JsonField) = apply { + body.sourceFilePath(sourceFilePath) + } + + /** + * Option to copy all versions of a file. By default, only the current version of the file + * is copied. When set to true, all versions of the file will be copied. Default value - + * `false`. + */ + fun includeFileVersions(includeFileVersions: Boolean) = apply { + body.includeFileVersions(includeFileVersions) + } + + /** + * Sets [Builder.includeFileVersions] to an arbitrary JSON value. + * + * You should usually call [Builder.includeFileVersions] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun includeFileVersions(includeFileVersions: JsonField) = apply { + body.includeFileVersions(includeFileVersions) + } + + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + body.additionalProperties(additionalBodyProperties) + } + + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + body.putAdditionalProperty(key, value) + } + + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + body.putAllAdditionalProperties(additionalBodyProperties) + } + + fun removeAdditionalBodyProperty(key: String) = apply { body.removeAdditionalProperty(key) } + + fun removeAllAdditionalBodyProperties(keys: Set) = apply { + body.removeAllAdditionalProperties(keys) + } + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + /** + * Returns an immutable instance of [FileCopyParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .destinationPath() + * .sourceFilePath() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): FileCopyParams = + FileCopyParams(body.build(), additionalHeaders.build(), additionalQueryParams.build()) + } + + fun _body(): Body = body + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + class Body + private constructor( + private val destinationPath: JsonField, + private val sourceFilePath: JsonField, + private val includeFileVersions: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("destinationPath") + @ExcludeMissing + destinationPath: JsonField = JsonMissing.of(), + @JsonProperty("sourceFilePath") + @ExcludeMissing + sourceFilePath: JsonField = JsonMissing.of(), + @JsonProperty("includeFileVersions") + @ExcludeMissing + includeFileVersions: JsonField = JsonMissing.of(), + ) : this(destinationPath, sourceFilePath, includeFileVersions, mutableMapOf()) + + /** + * Full path to the folder you want to copy the above file into. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun destinationPath(): String = destinationPath.getRequired("destinationPath") + + /** + * The full path of the file you want to copy. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun sourceFilePath(): String = sourceFilePath.getRequired("sourceFilePath") + + /** + * Option to copy all versions of a file. By default, only the current version of the file + * is copied. When set to true, all versions of the file will be copied. Default value - + * `false`. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun includeFileVersions(): Optional = + includeFileVersions.getOptional("includeFileVersions") + + /** + * Returns the raw JSON value of [destinationPath]. + * + * Unlike [destinationPath], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("destinationPath") + @ExcludeMissing + fun _destinationPath(): JsonField = destinationPath + + /** + * Returns the raw JSON value of [sourceFilePath]. + * + * Unlike [sourceFilePath], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("sourceFilePath") + @ExcludeMissing + fun _sourceFilePath(): JsonField = sourceFilePath + + /** + * Returns the raw JSON value of [includeFileVersions]. + * + * Unlike [includeFileVersions], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("includeFileVersions") + @ExcludeMissing + fun _includeFileVersions(): JsonField = includeFileVersions + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Body]. + * + * The following fields are required: + * ```java + * .destinationPath() + * .sourceFilePath() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Body]. */ + class Builder internal constructor() { + + private var destinationPath: JsonField? = null + private var sourceFilePath: JsonField? = null + private var includeFileVersions: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(body: Body) = apply { + destinationPath = body.destinationPath + sourceFilePath = body.sourceFilePath + includeFileVersions = body.includeFileVersions + additionalProperties = body.additionalProperties.toMutableMap() + } + + /** Full path to the folder you want to copy the above file into. */ + fun destinationPath(destinationPath: String) = + destinationPath(JsonField.of(destinationPath)) + + /** + * Sets [Builder.destinationPath] to an arbitrary JSON value. + * + * You should usually call [Builder.destinationPath] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun destinationPath(destinationPath: JsonField) = apply { + this.destinationPath = destinationPath + } + + /** The full path of the file you want to copy. */ + fun sourceFilePath(sourceFilePath: String) = + sourceFilePath(JsonField.of(sourceFilePath)) + + /** + * Sets [Builder.sourceFilePath] to an arbitrary JSON value. + * + * You should usually call [Builder.sourceFilePath] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun sourceFilePath(sourceFilePath: JsonField) = apply { + this.sourceFilePath = sourceFilePath + } + + /** + * Option to copy all versions of a file. By default, only the current version of the + * file is copied. When set to true, all versions of the file will be copied. Default + * value - `false`. + */ + fun includeFileVersions(includeFileVersions: Boolean) = + includeFileVersions(JsonField.of(includeFileVersions)) + + /** + * Sets [Builder.includeFileVersions] to an arbitrary JSON value. + * + * You should usually call [Builder.includeFileVersions] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun includeFileVersions(includeFileVersions: JsonField) = apply { + this.includeFileVersions = includeFileVersions + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Body]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .destinationPath() + * .sourceFilePath() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Body = + Body( + checkRequired("destinationPath", destinationPath), + checkRequired("sourceFilePath", sourceFilePath), + includeFileVersions, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Body = apply { + if (validated) { + return@apply + } + + destinationPath() + sourceFilePath() + includeFileVersions() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (destinationPath.asKnown().isPresent) 1 else 0) + + (if (sourceFilePath.asKnown().isPresent) 1 else 0) + + (if (includeFileVersions.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Body && + destinationPath == other.destinationPath && + sourceFilePath == other.sourceFilePath && + includeFileVersions == other.includeFileVersions && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(destinationPath, sourceFilePath, includeFileVersions, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Body{destinationPath=$destinationPath, sourceFilePath=$sourceFilePath, includeFileVersions=$includeFileVersions, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is FileCopyParams && + body == other.body && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = Objects.hash(body, additionalHeaders, additionalQueryParams) + + override fun toString() = + "FileCopyParams{body=$body, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/files/FileCopyResponse.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/files/FileCopyResponse.kt new file mode 100644 index 0000000..b3b4aff --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/files/FileCopyResponse.kt @@ -0,0 +1,112 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.files + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.imagekit.api.core.ExcludeMissing +import com.imagekit.api.core.JsonValue +import com.imagekit.api.errors.ImageKitInvalidDataException +import java.util.Collections +import java.util.Objects + +class FileCopyResponse +private constructor(private val additionalProperties: MutableMap) { + + @JsonCreator private constructor() : this(mutableMapOf()) + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [FileCopyResponse]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [FileCopyResponse]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(fileCopyResponse: FileCopyResponse) = apply { + additionalProperties = fileCopyResponse.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [FileCopyResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): FileCopyResponse = FileCopyResponse(additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): FileCopyResponse = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = 0 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is FileCopyResponse && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "FileCopyResponse{additionalProperties=$additionalProperties}" +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/files/FileDeleteParams.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/files/FileDeleteParams.kt new file mode 100644 index 0000000..16ae110 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/files/FileDeleteParams.kt @@ -0,0 +1,234 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.files + +import com.imagekit.api.core.JsonValue +import com.imagekit.api.core.Params +import com.imagekit.api.core.http.Headers +import com.imagekit.api.core.http.QueryParams +import com.imagekit.api.core.toImmutable +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** + * This API deletes the file and all its file versions permanently. + * + * Note: If a file or specific transformation has been requested in the past, then the response is + * cached. Deleting a file does not purge the cache. You can purge the cache using purge cache API. + */ +class FileDeleteParams +private constructor( + private val fileId: String?, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, + private val additionalBodyProperties: Map, +) : Params { + + fun fileId(): Optional = Optional.ofNullable(fileId) + + /** Additional body properties to send with the request. */ + fun _additionalBodyProperties(): Map = additionalBodyProperties + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun none(): FileDeleteParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [FileDeleteParams]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [FileDeleteParams]. */ + class Builder internal constructor() { + + private var fileId: String? = null + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + private var additionalBodyProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(fileDeleteParams: FileDeleteParams) = apply { + fileId = fileDeleteParams.fileId + additionalHeaders = fileDeleteParams.additionalHeaders.toBuilder() + additionalQueryParams = fileDeleteParams.additionalQueryParams.toBuilder() + additionalBodyProperties = fileDeleteParams.additionalBodyProperties.toMutableMap() + } + + fun fileId(fileId: String?) = apply { this.fileId = fileId } + + /** Alias for calling [Builder.fileId] with `fileId.orElse(null)`. */ + fun fileId(fileId: Optional) = fileId(fileId.getOrNull()) + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + this.additionalBodyProperties.clear() + putAllAdditionalBodyProperties(additionalBodyProperties) + } + + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + additionalBodyProperties.put(key, value) + } + + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + this.additionalBodyProperties.putAll(additionalBodyProperties) + } + + fun removeAdditionalBodyProperty(key: String) = apply { + additionalBodyProperties.remove(key) + } + + fun removeAllAdditionalBodyProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalBodyProperty) + } + + /** + * Returns an immutable instance of [FileDeleteParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): FileDeleteParams = + FileDeleteParams( + fileId, + additionalHeaders.build(), + additionalQueryParams.build(), + additionalBodyProperties.toImmutable(), + ) + } + + fun _body(): Optional> = + Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) + + fun _pathParam(index: Int): String = + when (index) { + 0 -> fileId ?: "" + else -> "" + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is FileDeleteParams && + fileId == other.fileId && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams && + additionalBodyProperties == other.additionalBodyProperties + } + + override fun hashCode(): Int = + Objects.hash(fileId, additionalHeaders, additionalQueryParams, additionalBodyProperties) + + override fun toString() = + "FileDeleteParams{fileId=$fileId, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams, additionalBodyProperties=$additionalBodyProperties}" +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/files/FileGetParams.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/files/FileGetParams.kt new file mode 100644 index 0000000..e5a8821 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/files/FileGetParams.kt @@ -0,0 +1,189 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.files + +import com.imagekit.api.core.Params +import com.imagekit.api.core.http.Headers +import com.imagekit.api.core.http.QueryParams +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** This API returns an object with details or attributes about the current version of the file. */ +class FileGetParams +private constructor( + private val fileId: String?, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + fun fileId(): Optional = Optional.ofNullable(fileId) + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun none(): FileGetParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [FileGetParams]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [FileGetParams]. */ + class Builder internal constructor() { + + private var fileId: String? = null + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + + @JvmSynthetic + internal fun from(fileGetParams: FileGetParams) = apply { + fileId = fileGetParams.fileId + additionalHeaders = fileGetParams.additionalHeaders.toBuilder() + additionalQueryParams = fileGetParams.additionalQueryParams.toBuilder() + } + + fun fileId(fileId: String?) = apply { this.fileId = fileId } + + /** Alias for calling [Builder.fileId] with `fileId.orElse(null)`. */ + fun fileId(fileId: Optional) = fileId(fileId.getOrNull()) + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + /** + * Returns an immutable instance of [FileGetParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): FileGetParams = + FileGetParams(fileId, additionalHeaders.build(), additionalQueryParams.build()) + } + + fun _pathParam(index: Int): String = + when (index) { + 0 -> fileId ?: "" + else -> "" + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is FileGetParams && + fileId == other.fileId && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = Objects.hash(fileId, additionalHeaders, additionalQueryParams) + + override fun toString() = + "FileGetParams{fileId=$fileId, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/files/FileMoveParams.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/files/FileMoveParams.kt new file mode 100644 index 0000000..f4e3c64 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/files/FileMoveParams.kt @@ -0,0 +1,512 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.files + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.imagekit.api.core.ExcludeMissing +import com.imagekit.api.core.JsonField +import com.imagekit.api.core.JsonMissing +import com.imagekit.api.core.JsonValue +import com.imagekit.api.core.Params +import com.imagekit.api.core.checkRequired +import com.imagekit.api.core.http.Headers +import com.imagekit.api.core.http.QueryParams +import com.imagekit.api.errors.ImageKitInvalidDataException +import java.util.Collections +import java.util.Objects + +/** + * This will move a file and all its versions from one folder to another. + * + * Note: If any file at the destination has the same name as the source file, then the source file + * and its versions will be appended to the destination file. + */ +class FileMoveParams +private constructor( + private val body: Body, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** + * Full path to the folder you want to move the above file into. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun destinationPath(): String = body.destinationPath() + + /** + * The full path of the file you want to move. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun sourceFilePath(): String = body.sourceFilePath() + + /** + * Returns the raw JSON value of [destinationPath]. + * + * Unlike [destinationPath], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _destinationPath(): JsonField = body._destinationPath() + + /** + * Returns the raw JSON value of [sourceFilePath]. + * + * Unlike [sourceFilePath], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _sourceFilePath(): JsonField = body._sourceFilePath() + + fun _additionalBodyProperties(): Map = body._additionalProperties() + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [FileMoveParams]. + * + * The following fields are required: + * ```java + * .destinationPath() + * .sourceFilePath() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [FileMoveParams]. */ + class Builder internal constructor() { + + private var body: Body.Builder = Body.builder() + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + + @JvmSynthetic + internal fun from(fileMoveParams: FileMoveParams) = apply { + body = fileMoveParams.body.toBuilder() + additionalHeaders = fileMoveParams.additionalHeaders.toBuilder() + additionalQueryParams = fileMoveParams.additionalQueryParams.toBuilder() + } + + /** + * Sets the entire request body. + * + * This is generally only useful if you are already constructing the body separately. + * Otherwise, it's more convenient to use the top-level setters instead: + * - [destinationPath] + * - [sourceFilePath] + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } + + /** Full path to the folder you want to move the above file into. */ + fun destinationPath(destinationPath: String) = apply { + body.destinationPath(destinationPath) + } + + /** + * Sets [Builder.destinationPath] to an arbitrary JSON value. + * + * You should usually call [Builder.destinationPath] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun destinationPath(destinationPath: JsonField) = apply { + body.destinationPath(destinationPath) + } + + /** The full path of the file you want to move. */ + fun sourceFilePath(sourceFilePath: String) = apply { body.sourceFilePath(sourceFilePath) } + + /** + * Sets [Builder.sourceFilePath] to an arbitrary JSON value. + * + * You should usually call [Builder.sourceFilePath] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun sourceFilePath(sourceFilePath: JsonField) = apply { + body.sourceFilePath(sourceFilePath) + } + + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + body.additionalProperties(additionalBodyProperties) + } + + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + body.putAdditionalProperty(key, value) + } + + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + body.putAllAdditionalProperties(additionalBodyProperties) + } + + fun removeAdditionalBodyProperty(key: String) = apply { body.removeAdditionalProperty(key) } + + fun removeAllAdditionalBodyProperties(keys: Set) = apply { + body.removeAllAdditionalProperties(keys) + } + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + /** + * Returns an immutable instance of [FileMoveParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .destinationPath() + * .sourceFilePath() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): FileMoveParams = + FileMoveParams(body.build(), additionalHeaders.build(), additionalQueryParams.build()) + } + + fun _body(): Body = body + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + class Body + private constructor( + private val destinationPath: JsonField, + private val sourceFilePath: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("destinationPath") + @ExcludeMissing + destinationPath: JsonField = JsonMissing.of(), + @JsonProperty("sourceFilePath") + @ExcludeMissing + sourceFilePath: JsonField = JsonMissing.of(), + ) : this(destinationPath, sourceFilePath, mutableMapOf()) + + /** + * Full path to the folder you want to move the above file into. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun destinationPath(): String = destinationPath.getRequired("destinationPath") + + /** + * The full path of the file you want to move. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun sourceFilePath(): String = sourceFilePath.getRequired("sourceFilePath") + + /** + * Returns the raw JSON value of [destinationPath]. + * + * Unlike [destinationPath], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("destinationPath") + @ExcludeMissing + fun _destinationPath(): JsonField = destinationPath + + /** + * Returns the raw JSON value of [sourceFilePath]. + * + * Unlike [sourceFilePath], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("sourceFilePath") + @ExcludeMissing + fun _sourceFilePath(): JsonField = sourceFilePath + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Body]. + * + * The following fields are required: + * ```java + * .destinationPath() + * .sourceFilePath() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Body]. */ + class Builder internal constructor() { + + private var destinationPath: JsonField? = null + private var sourceFilePath: JsonField? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(body: Body) = apply { + destinationPath = body.destinationPath + sourceFilePath = body.sourceFilePath + additionalProperties = body.additionalProperties.toMutableMap() + } + + /** Full path to the folder you want to move the above file into. */ + fun destinationPath(destinationPath: String) = + destinationPath(JsonField.of(destinationPath)) + + /** + * Sets [Builder.destinationPath] to an arbitrary JSON value. + * + * You should usually call [Builder.destinationPath] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun destinationPath(destinationPath: JsonField) = apply { + this.destinationPath = destinationPath + } + + /** The full path of the file you want to move. */ + fun sourceFilePath(sourceFilePath: String) = + sourceFilePath(JsonField.of(sourceFilePath)) + + /** + * Sets [Builder.sourceFilePath] to an arbitrary JSON value. + * + * You should usually call [Builder.sourceFilePath] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun sourceFilePath(sourceFilePath: JsonField) = apply { + this.sourceFilePath = sourceFilePath + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Body]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .destinationPath() + * .sourceFilePath() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Body = + Body( + checkRequired("destinationPath", destinationPath), + checkRequired("sourceFilePath", sourceFilePath), + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Body = apply { + if (validated) { + return@apply + } + + destinationPath() + sourceFilePath() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (destinationPath.asKnown().isPresent) 1 else 0) + + (if (sourceFilePath.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Body && + destinationPath == other.destinationPath && + sourceFilePath == other.sourceFilePath && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(destinationPath, sourceFilePath, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Body{destinationPath=$destinationPath, sourceFilePath=$sourceFilePath, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is FileMoveParams && + body == other.body && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = Objects.hash(body, additionalHeaders, additionalQueryParams) + + override fun toString() = + "FileMoveParams{body=$body, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/files/FileMoveResponse.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/files/FileMoveResponse.kt new file mode 100644 index 0000000..726f9e2 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/files/FileMoveResponse.kt @@ -0,0 +1,112 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.files + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.imagekit.api.core.ExcludeMissing +import com.imagekit.api.core.JsonValue +import com.imagekit.api.errors.ImageKitInvalidDataException +import java.util.Collections +import java.util.Objects + +class FileMoveResponse +private constructor(private val additionalProperties: MutableMap) { + + @JsonCreator private constructor() : this(mutableMapOf()) + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [FileMoveResponse]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [FileMoveResponse]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(fileMoveResponse: FileMoveResponse) = apply { + additionalProperties = fileMoveResponse.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [FileMoveResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): FileMoveResponse = FileMoveResponse(additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): FileMoveResponse = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = 0 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is FileMoveResponse && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "FileMoveResponse{additionalProperties=$additionalProperties}" +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/files/FileRenameParams.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/files/FileRenameParams.kt new file mode 100644 index 0000000..2b7b4b5 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/files/FileRenameParams.kt @@ -0,0 +1,649 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.files + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.imagekit.api.core.ExcludeMissing +import com.imagekit.api.core.JsonField +import com.imagekit.api.core.JsonMissing +import com.imagekit.api.core.JsonValue +import com.imagekit.api.core.Params +import com.imagekit.api.core.checkRequired +import com.imagekit.api.core.http.Headers +import com.imagekit.api.core.http.QueryParams +import com.imagekit.api.errors.ImageKitInvalidDataException +import java.util.Collections +import java.util.Objects +import java.util.Optional + +/** + * You can rename an already existing file in the media library using rename file API. This + * operation would rename all file versions of the file. + * + * Note: The old URLs will stop working. The file/file version URLs cached on CDN will continue to + * work unless a purge is requested. + */ +class FileRenameParams +private constructor( + private val body: Body, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** + * The full path of the file you want to rename. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun filePath(): String = body.filePath() + + /** + * The new name of the file. A filename can contain: + * + * Alphanumeric Characters: `a-z`, `A-Z`, `0-9` (including Unicode letters, marks, and numerals + * in other languages). Special Characters: `.`, `_`, and `-`. + * + * Any other character, including space, will be replaced by `_`. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun newFileName(): String = body.newFileName() + + /** + * Option to purge cache for the old file and its versions' URLs. + * + * When set to true, it will internally issue a purge cache request on CDN to remove cached + * content of old file and its versions. This purge request is counted against your monthly + * purge quota. + * + * Note: If the old file were accessible at `https://ik.imagekit.io/demo/old-filename.jpg`, a + * purge cache request would be issued against `https://ik.imagekit.io/demo/old-filename.jpg*` + * (with a wildcard at the end). It will remove the file and its versions' URLs and any + * transformations made using query parameters on this file or its versions. However, the cache + * for file transformations made using path parameters will persist. You can purge them using + * the purge API. For more details, refer to the purge API documentation. + * + * Default value - `false` + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun purgeCache(): Optional = body.purgeCache() + + /** + * Returns the raw JSON value of [filePath]. + * + * Unlike [filePath], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _filePath(): JsonField = body._filePath() + + /** + * Returns the raw JSON value of [newFileName]. + * + * Unlike [newFileName], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _newFileName(): JsonField = body._newFileName() + + /** + * Returns the raw JSON value of [purgeCache]. + * + * Unlike [purgeCache], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _purgeCache(): JsonField = body._purgeCache() + + fun _additionalBodyProperties(): Map = body._additionalProperties() + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [FileRenameParams]. + * + * The following fields are required: + * ```java + * .filePath() + * .newFileName() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [FileRenameParams]. */ + class Builder internal constructor() { + + private var body: Body.Builder = Body.builder() + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + + @JvmSynthetic + internal fun from(fileRenameParams: FileRenameParams) = apply { + body = fileRenameParams.body.toBuilder() + additionalHeaders = fileRenameParams.additionalHeaders.toBuilder() + additionalQueryParams = fileRenameParams.additionalQueryParams.toBuilder() + } + + /** + * Sets the entire request body. + * + * This is generally only useful if you are already constructing the body separately. + * Otherwise, it's more convenient to use the top-level setters instead: + * - [filePath] + * - [newFileName] + * - [purgeCache] + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } + + /** The full path of the file you want to rename. */ + fun filePath(filePath: String) = apply { body.filePath(filePath) } + + /** + * Sets [Builder.filePath] to an arbitrary JSON value. + * + * You should usually call [Builder.filePath] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun filePath(filePath: JsonField) = apply { body.filePath(filePath) } + + /** + * The new name of the file. A filename can contain: + * + * Alphanumeric Characters: `a-z`, `A-Z`, `0-9` (including Unicode letters, marks, and + * numerals in other languages). Special Characters: `.`, `_`, and `-`. + * + * Any other character, including space, will be replaced by `_`. + */ + fun newFileName(newFileName: String) = apply { body.newFileName(newFileName) } + + /** + * Sets [Builder.newFileName] to an arbitrary JSON value. + * + * You should usually call [Builder.newFileName] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun newFileName(newFileName: JsonField) = apply { body.newFileName(newFileName) } + + /** + * Option to purge cache for the old file and its versions' URLs. + * + * When set to true, it will internally issue a purge cache request on CDN to remove cached + * content of old file and its versions. This purge request is counted against your monthly + * purge quota. + * + * Note: If the old file were accessible at `https://ik.imagekit.io/demo/old-filename.jpg`, + * a purge cache request would be issued against + * `https://ik.imagekit.io/demo/old-filename.jpg*` (with a wildcard at the end). It will + * remove the file and its versions' URLs and any transformations made using query + * parameters on this file or its versions. However, the cache for file transformations made + * using path parameters will persist. You can purge them using the purge API. For more + * details, refer to the purge API documentation. + * + * Default value - `false` + */ + fun purgeCache(purgeCache: Boolean) = apply { body.purgeCache(purgeCache) } + + /** + * Sets [Builder.purgeCache] to an arbitrary JSON value. + * + * You should usually call [Builder.purgeCache] with a well-typed [Boolean] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun purgeCache(purgeCache: JsonField) = apply { body.purgeCache(purgeCache) } + + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + body.additionalProperties(additionalBodyProperties) + } + + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + body.putAdditionalProperty(key, value) + } + + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + body.putAllAdditionalProperties(additionalBodyProperties) + } + + fun removeAdditionalBodyProperty(key: String) = apply { body.removeAdditionalProperty(key) } + + fun removeAllAdditionalBodyProperties(keys: Set) = apply { + body.removeAllAdditionalProperties(keys) + } + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + /** + * Returns an immutable instance of [FileRenameParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .filePath() + * .newFileName() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): FileRenameParams = + FileRenameParams(body.build(), additionalHeaders.build(), additionalQueryParams.build()) + } + + fun _body(): Body = body + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + class Body + private constructor( + private val filePath: JsonField, + private val newFileName: JsonField, + private val purgeCache: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("filePath") + @ExcludeMissing + filePath: JsonField = JsonMissing.of(), + @JsonProperty("newFileName") + @ExcludeMissing + newFileName: JsonField = JsonMissing.of(), + @JsonProperty("purgeCache") + @ExcludeMissing + purgeCache: JsonField = JsonMissing.of(), + ) : this(filePath, newFileName, purgeCache, mutableMapOf()) + + /** + * The full path of the file you want to rename. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun filePath(): String = filePath.getRequired("filePath") + + /** + * The new name of the file. A filename can contain: + * + * Alphanumeric Characters: `a-z`, `A-Z`, `0-9` (including Unicode letters, marks, and + * numerals in other languages). Special Characters: `.`, `_`, and `-`. + * + * Any other character, including space, will be replaced by `_`. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun newFileName(): String = newFileName.getRequired("newFileName") + + /** + * Option to purge cache for the old file and its versions' URLs. + * + * When set to true, it will internally issue a purge cache request on CDN to remove cached + * content of old file and its versions. This purge request is counted against your monthly + * purge quota. + * + * Note: If the old file were accessible at `https://ik.imagekit.io/demo/old-filename.jpg`, + * a purge cache request would be issued against + * `https://ik.imagekit.io/demo/old-filename.jpg*` (with a wildcard at the end). It will + * remove the file and its versions' URLs and any transformations made using query + * parameters on this file or its versions. However, the cache for file transformations made + * using path parameters will persist. You can purge them using the purge API. For more + * details, refer to the purge API documentation. + * + * Default value - `false` + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun purgeCache(): Optional = purgeCache.getOptional("purgeCache") + + /** + * Returns the raw JSON value of [filePath]. + * + * Unlike [filePath], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("filePath") @ExcludeMissing fun _filePath(): JsonField = filePath + + /** + * Returns the raw JSON value of [newFileName]. + * + * Unlike [newFileName], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("newFileName") + @ExcludeMissing + fun _newFileName(): JsonField = newFileName + + /** + * Returns the raw JSON value of [purgeCache]. + * + * Unlike [purgeCache], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("purgeCache") + @ExcludeMissing + fun _purgeCache(): JsonField = purgeCache + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Body]. + * + * The following fields are required: + * ```java + * .filePath() + * .newFileName() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Body]. */ + class Builder internal constructor() { + + private var filePath: JsonField? = null + private var newFileName: JsonField? = null + private var purgeCache: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(body: Body) = apply { + filePath = body.filePath + newFileName = body.newFileName + purgeCache = body.purgeCache + additionalProperties = body.additionalProperties.toMutableMap() + } + + /** The full path of the file you want to rename. */ + fun filePath(filePath: String) = filePath(JsonField.of(filePath)) + + /** + * Sets [Builder.filePath] to an arbitrary JSON value. + * + * You should usually call [Builder.filePath] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun filePath(filePath: JsonField) = apply { this.filePath = filePath } + + /** + * The new name of the file. A filename can contain: + * + * Alphanumeric Characters: `a-z`, `A-Z`, `0-9` (including Unicode letters, marks, and + * numerals in other languages). Special Characters: `.`, `_`, and `-`. + * + * Any other character, including space, will be replaced by `_`. + */ + fun newFileName(newFileName: String) = newFileName(JsonField.of(newFileName)) + + /** + * Sets [Builder.newFileName] to an arbitrary JSON value. + * + * You should usually call [Builder.newFileName] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun newFileName(newFileName: JsonField) = apply { + this.newFileName = newFileName + } + + /** + * Option to purge cache for the old file and its versions' URLs. + * + * When set to true, it will internally issue a purge cache request on CDN to remove + * cached content of old file and its versions. This purge request is counted against + * your monthly purge quota. + * + * Note: If the old file were accessible at + * `https://ik.imagekit.io/demo/old-filename.jpg`, a purge cache request would be issued + * against `https://ik.imagekit.io/demo/old-filename.jpg*` (with a wildcard at the end). + * It will remove the file and its versions' URLs and any transformations made using + * query parameters on this file or its versions. However, the cache for file + * transformations made using path parameters will persist. You can purge them using the + * purge API. For more details, refer to the purge API documentation. + * + * Default value - `false` + */ + fun purgeCache(purgeCache: Boolean) = purgeCache(JsonField.of(purgeCache)) + + /** + * Sets [Builder.purgeCache] to an arbitrary JSON value. + * + * You should usually call [Builder.purgeCache] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun purgeCache(purgeCache: JsonField) = apply { this.purgeCache = purgeCache } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Body]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .filePath() + * .newFileName() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Body = + Body( + checkRequired("filePath", filePath), + checkRequired("newFileName", newFileName), + purgeCache, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Body = apply { + if (validated) { + return@apply + } + + filePath() + newFileName() + purgeCache() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (filePath.asKnown().isPresent) 1 else 0) + + (if (newFileName.asKnown().isPresent) 1 else 0) + + (if (purgeCache.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Body && + filePath == other.filePath && + newFileName == other.newFileName && + purgeCache == other.purgeCache && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(filePath, newFileName, purgeCache, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Body{filePath=$filePath, newFileName=$newFileName, purgeCache=$purgeCache, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is FileRenameParams && + body == other.body && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = Objects.hash(body, additionalHeaders, additionalQueryParams) + + override fun toString() = + "FileRenameParams{body=$body, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/files/FileRenameResponse.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/files/FileRenameResponse.kt new file mode 100644 index 0000000..3f9dc4c --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/files/FileRenameResponse.kt @@ -0,0 +1,166 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.files + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.imagekit.api.core.ExcludeMissing +import com.imagekit.api.core.JsonField +import com.imagekit.api.core.JsonMissing +import com.imagekit.api.core.JsonValue +import com.imagekit.api.errors.ImageKitInvalidDataException +import java.util.Collections +import java.util.Objects +import java.util.Optional + +class FileRenameResponse +private constructor( + private val purgeRequestId: JsonField, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("purgeRequestId") + @ExcludeMissing + purgeRequestId: JsonField = JsonMissing.of() + ) : this(purgeRequestId, mutableMapOf()) + + /** + * Unique identifier of the purge request. This can be used to check the status of the purge + * request. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun purgeRequestId(): Optional = purgeRequestId.getOptional("purgeRequestId") + + /** + * Returns the raw JSON value of [purgeRequestId]. + * + * Unlike [purgeRequestId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("purgeRequestId") + @ExcludeMissing + fun _purgeRequestId(): JsonField = purgeRequestId + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [FileRenameResponse]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [FileRenameResponse]. */ + class Builder internal constructor() { + + private var purgeRequestId: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(fileRenameResponse: FileRenameResponse) = apply { + purgeRequestId = fileRenameResponse.purgeRequestId + additionalProperties = fileRenameResponse.additionalProperties.toMutableMap() + } + + /** + * Unique identifier of the purge request. This can be used to check the status of the purge + * request. + */ + fun purgeRequestId(purgeRequestId: String) = purgeRequestId(JsonField.of(purgeRequestId)) + + /** + * Sets [Builder.purgeRequestId] to an arbitrary JSON value. + * + * You should usually call [Builder.purgeRequestId] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun purgeRequestId(purgeRequestId: JsonField) = apply { + this.purgeRequestId = purgeRequestId + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [FileRenameResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): FileRenameResponse = + FileRenameResponse(purgeRequestId, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): FileRenameResponse = apply { + if (validated) { + return@apply + } + + purgeRequestId() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = (if (purgeRequestId.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is FileRenameResponse && + purgeRequestId == other.purgeRequestId && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(purgeRequestId, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "FileRenameResponse{purgeRequestId=$purgeRequestId, additionalProperties=$additionalProperties}" +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/files/FileUpdateParams.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/files/FileUpdateParams.kt new file mode 100644 index 0000000..54d724d --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/files/FileUpdateParams.kt @@ -0,0 +1,2802 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.files + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.fasterxml.jackson.core.JsonGenerator +import com.fasterxml.jackson.core.ObjectCodec +import com.fasterxml.jackson.databind.JsonNode +import com.fasterxml.jackson.databind.SerializerProvider +import com.fasterxml.jackson.databind.annotation.JsonDeserialize +import com.fasterxml.jackson.databind.annotation.JsonSerialize +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.imagekit.api.core.BaseDeserializer +import com.imagekit.api.core.BaseSerializer +import com.imagekit.api.core.Enum +import com.imagekit.api.core.ExcludeMissing +import com.imagekit.api.core.JsonField +import com.imagekit.api.core.JsonMissing +import com.imagekit.api.core.JsonValue +import com.imagekit.api.core.Params +import com.imagekit.api.core.allMaxBy +import com.imagekit.api.core.checkKnown +import com.imagekit.api.core.checkRequired +import com.imagekit.api.core.getOrThrow +import com.imagekit.api.core.http.Headers +import com.imagekit.api.core.http.QueryParams +import com.imagekit.api.core.toImmutable +import com.imagekit.api.errors.ImageKitInvalidDataException +import com.imagekit.api.models.UnnamedSchemaWithArrayParent3 +import java.util.Collections +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** + * This API updates the details or attributes of the current version of the file. You can update + * `tags`, `customCoordinates`, `customMetadata`, publication status, remove existing `AITags` and + * apply extensions using this API. + */ +class FileUpdateParams +private constructor( + private val fileId: String?, + private val body: Body?, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + fun fileId(): Optional = Optional.ofNullable(fileId) + + fun body(): Optional = Optional.ofNullable(body) + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun none(): FileUpdateParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [FileUpdateParams]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [FileUpdateParams]. */ + class Builder internal constructor() { + + private var fileId: String? = null + private var body: Body? = null + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + + @JvmSynthetic + internal fun from(fileUpdateParams: FileUpdateParams) = apply { + fileId = fileUpdateParams.fileId + body = fileUpdateParams.body + additionalHeaders = fileUpdateParams.additionalHeaders.toBuilder() + additionalQueryParams = fileUpdateParams.additionalQueryParams.toBuilder() + } + + fun fileId(fileId: String?) = apply { this.fileId = fileId } + + /** Alias for calling [Builder.fileId] with `fileId.orElse(null)`. */ + fun fileId(fileId: Optional) = fileId(fileId.getOrNull()) + + fun body(body: Body?) = apply { this.body = body } + + /** Alias for calling [Builder.body] with `body.orElse(null)`. */ + fun body(body: Optional) = body(body.getOrNull()) + + /** Alias for calling [body] with `Body.ofUpdateFileDetails(updateFileDetails)`. */ + fun body(updateFileDetails: Body.UpdateFileDetails) = + body(Body.ofUpdateFileDetails(updateFileDetails)) + + /** + * Alias for calling [body] with `Body.ofChangePublicationStatus(changePublicationStatus)`. + */ + fun body(changePublicationStatus: Body.ChangePublicationStatus) = + body(Body.ofChangePublicationStatus(changePublicationStatus)) + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + /** + * Returns an immutable instance of [FileUpdateParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): FileUpdateParams = + FileUpdateParams(fileId, body, additionalHeaders.build(), additionalQueryParams.build()) + } + + fun _body(): Optional = Optional.ofNullable(body) + + fun _pathParam(index: Int): String = + when (index) { + 0 -> fileId ?: "" + else -> "" + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + @JsonDeserialize(using = Body.Deserializer::class) + @JsonSerialize(using = Body.Serializer::class) + class Body + private constructor( + private val updateFileDetails: UpdateFileDetails? = null, + private val changePublicationStatus: ChangePublicationStatus? = null, + private val _json: JsonValue? = null, + ) { + + fun updateFileDetails(): Optional = + Optional.ofNullable(updateFileDetails) + + fun changePublicationStatus(): Optional = + Optional.ofNullable(changePublicationStatus) + + fun isUpdateFileDetails(): Boolean = updateFileDetails != null + + fun isChangePublicationStatus(): Boolean = changePublicationStatus != null + + fun asUpdateFileDetails(): UpdateFileDetails = + updateFileDetails.getOrThrow("updateFileDetails") + + fun asChangePublicationStatus(): ChangePublicationStatus = + changePublicationStatus.getOrThrow("changePublicationStatus") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + updateFileDetails != null -> visitor.visitUpdateFileDetails(updateFileDetails) + changePublicationStatus != null -> + visitor.visitChangePublicationStatus(changePublicationStatus) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): Body = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitUpdateFileDetails(updateFileDetails: UpdateFileDetails) { + updateFileDetails.validate() + } + + override fun visitChangePublicationStatus( + changePublicationStatus: ChangePublicationStatus + ) { + changePublicationStatus.validate() + } + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitUpdateFileDetails(updateFileDetails: UpdateFileDetails) = + updateFileDetails.validity() + + override fun visitChangePublicationStatus( + changePublicationStatus: ChangePublicationStatus + ) = changePublicationStatus.validity() + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Body && + updateFileDetails == other.updateFileDetails && + changePublicationStatus == other.changePublicationStatus + } + + override fun hashCode(): Int = Objects.hash(updateFileDetails, changePublicationStatus) + + override fun toString(): String = + when { + updateFileDetails != null -> "Body{updateFileDetails=$updateFileDetails}" + changePublicationStatus != null -> + "Body{changePublicationStatus=$changePublicationStatus}" + _json != null -> "Body{_unknown=$_json}" + else -> throw IllegalStateException("Invalid Body") + } + + companion object { + + @JvmStatic + fun ofUpdateFileDetails(updateFileDetails: UpdateFileDetails) = + Body(updateFileDetails = updateFileDetails) + + @JvmStatic + fun ofChangePublicationStatus(changePublicationStatus: ChangePublicationStatus) = + Body(changePublicationStatus = changePublicationStatus) + } + + /** An interface that defines how to map each variant of [Body] to a value of type [T]. */ + interface Visitor { + + fun visitUpdateFileDetails(updateFileDetails: UpdateFileDetails): T + + fun visitChangePublicationStatus(changePublicationStatus: ChangePublicationStatus): T + + /** + * Maps an unknown variant of [Body] to a value of type [T]. + * + * An instance of [Body] can contain an unknown variant if it was deserialized from data + * that doesn't match any known variant. For example, if the SDK is on an older version + * than the API, then the API may respond with new variants that the SDK is unaware of. + * + * @throws ImageKitInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw ImageKitInvalidDataException("Unknown Body: $json") + } + } + + internal class Deserializer : BaseDeserializer(Body::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): Body { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + Body(updateFileDetails = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + Body(changePublicationStatus = it, _json = json) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely incompatible with + // all the possible variants (e.g. deserializing from boolean). + 0 -> Body(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then use the first + // completely valid match, or simply the first match if none are completely + // valid. + else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() + } + } + } + + internal class Serializer : BaseSerializer(Body::class) { + + override fun serialize( + value: Body, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.updateFileDetails != null -> + generator.writeObject(value.updateFileDetails) + value.changePublicationStatus != null -> + generator.writeObject(value.changePublicationStatus) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid Body") + } + } + } + + class UpdateFileDetails + private constructor( + private val customCoordinates: JsonField, + private val customMetadata: JsonField, + private val description: JsonField, + private val extensions: JsonField>, + private val removeAiTags: JsonField, + private val tags: JsonField>, + private val webhookUrl: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("customCoordinates") + @ExcludeMissing + customCoordinates: JsonField = JsonMissing.of(), + @JsonProperty("customMetadata") + @ExcludeMissing + customMetadata: JsonField = JsonMissing.of(), + @JsonProperty("description") + @ExcludeMissing + description: JsonField = JsonMissing.of(), + @JsonProperty("extensions") + @ExcludeMissing + extensions: JsonField> = JsonMissing.of(), + @JsonProperty("removeAITags") + @ExcludeMissing + removeAiTags: JsonField = JsonMissing.of(), + @JsonProperty("tags") + @ExcludeMissing + tags: JsonField> = JsonMissing.of(), + @JsonProperty("webhookUrl") + @ExcludeMissing + webhookUrl: JsonField = JsonMissing.of(), + ) : this( + customCoordinates, + customMetadata, + description, + extensions, + removeAiTags, + tags, + webhookUrl, + mutableMapOf(), + ) + + /** + * Define an important area in the image in the format `x,y,width,height` e.g. + * `10,10,100,100`. Send `null` to unset this value. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun customCoordinates(): Optional = + customCoordinates.getOptional("customCoordinates") + + /** + * A key-value data to be associated with the asset. To unset a key, send `null` value + * for that key. Before setting any custom metadata on an asset you have to create the + * field using custom metadata fields API. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun customMetadata(): Optional = + customMetadata.getOptional("customMetadata") + + /** + * Optional text to describe the contents of the file. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun description(): Optional = description.getOptional("description") + + /** + * Array of extensions to be applied to the asset. Each extension can be configured with + * specific parameters based on the extension type. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun extensions(): Optional> = + extensions.getOptional("extensions") + + /** + * An array of AITags associated with the file that you want to remove, e.g. `["car", + * "vehicle", "motorsports"]`. + * + * If you want to remove all AITags associated with the file, send a string - "all". + * + * Note: The remove operation for `AITags` executes before any of the `extensions` are + * processed. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun removeAiTags(): Optional = removeAiTags.getOptional("removeAITags") + + /** + * An array of tags associated with the file, such as `["tag1", "tag2"]`. Send `null` to + * unset all tags associated with the file. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun tags(): Optional> = tags.getOptional("tags") + + /** + * The final status of extensions after they have completed execution will be delivered + * to this endpoint as a POST request. + * [Learn more](/docs/api-reference/digital-asset-management-dam/managing-assets/update-file-details#webhook-payload-structure) + * about the webhook payload structure. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun webhookUrl(): Optional = webhookUrl.getOptional("webhookUrl") + + /** + * Returns the raw JSON value of [customCoordinates]. + * + * Unlike [customCoordinates], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("customCoordinates") + @ExcludeMissing + fun _customCoordinates(): JsonField = customCoordinates + + /** + * Returns the raw JSON value of [customMetadata]. + * + * Unlike [customMetadata], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("customMetadata") + @ExcludeMissing + fun _customMetadata(): JsonField = customMetadata + + /** + * Returns the raw JSON value of [description]. + * + * Unlike [description], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("description") + @ExcludeMissing + fun _description(): JsonField = description + + /** + * Returns the raw JSON value of [extensions]. + * + * Unlike [extensions], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("extensions") + @ExcludeMissing + fun _extensions(): JsonField> = extensions + + /** + * Returns the raw JSON value of [removeAiTags]. + * + * Unlike [removeAiTags], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("removeAITags") + @ExcludeMissing + fun _removeAiTags(): JsonField = removeAiTags + + /** + * Returns the raw JSON value of [tags]. + * + * Unlike [tags], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("tags") @ExcludeMissing fun _tags(): JsonField> = tags + + /** + * Returns the raw JSON value of [webhookUrl]. + * + * Unlike [webhookUrl], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("webhookUrl") + @ExcludeMissing + fun _webhookUrl(): JsonField = webhookUrl + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [UpdateFileDetails]. + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [UpdateFileDetails]. */ + class Builder internal constructor() { + + private var customCoordinates: JsonField = JsonMissing.of() + private var customMetadata: JsonField = JsonMissing.of() + private var description: JsonField = JsonMissing.of() + private var extensions: JsonField>? = + null + private var removeAiTags: JsonField = JsonMissing.of() + private var tags: JsonField>? = null + private var webhookUrl: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(updateFileDetails: UpdateFileDetails) = apply { + customCoordinates = updateFileDetails.customCoordinates + customMetadata = updateFileDetails.customMetadata + description = updateFileDetails.description + extensions = updateFileDetails.extensions.map { it.toMutableList() } + removeAiTags = updateFileDetails.removeAiTags + tags = updateFileDetails.tags.map { it.toMutableList() } + webhookUrl = updateFileDetails.webhookUrl + additionalProperties = updateFileDetails.additionalProperties.toMutableMap() + } + + /** + * Define an important area in the image in the format `x,y,width,height` e.g. + * `10,10,100,100`. Send `null` to unset this value. + */ + fun customCoordinates(customCoordinates: String?) = + customCoordinates(JsonField.ofNullable(customCoordinates)) + + /** + * Alias for calling [Builder.customCoordinates] with + * `customCoordinates.orElse(null)`. + */ + fun customCoordinates(customCoordinates: Optional) = + customCoordinates(customCoordinates.getOrNull()) + + /** + * Sets [Builder.customCoordinates] to an arbitrary JSON value. + * + * You should usually call [Builder.customCoordinates] with a well-typed [String] + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun customCoordinates(customCoordinates: JsonField) = apply { + this.customCoordinates = customCoordinates + } + + /** + * A key-value data to be associated with the asset. To unset a key, send `null` + * value for that key. Before setting any custom metadata on an asset you have to + * create the field using custom metadata fields API. + */ + fun customMetadata(customMetadata: CustomMetadata) = + customMetadata(JsonField.of(customMetadata)) + + /** + * Sets [Builder.customMetadata] to an arbitrary JSON value. + * + * You should usually call [Builder.customMetadata] with a well-typed + * [CustomMetadata] value instead. This method is primarily for setting the field to + * an undocumented or not yet supported value. + */ + fun customMetadata(customMetadata: JsonField) = apply { + this.customMetadata = customMetadata + } + + /** Optional text to describe the contents of the file. */ + fun description(description: String) = description(JsonField.of(description)) + + /** + * Sets [Builder.description] to an arbitrary JSON value. + * + * You should usually call [Builder.description] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun description(description: JsonField) = apply { + this.description = description + } + + /** + * Array of extensions to be applied to the asset. Each extension can be configured + * with specific parameters based on the extension type. + */ + fun extensions(extensions: List) = + extensions(JsonField.of(extensions)) + + /** + * Sets [Builder.extensions] to an arbitrary JSON value. + * + * You should usually call [Builder.extensions] with a well-typed + * `List` value instead. This method is primarily for + * setting the field to an undocumented or not yet supported value. + */ + fun extensions(extensions: JsonField>) = apply { + this.extensions = extensions.map { it.toMutableList() } + } + + /** + * Adds a single [UnnamedSchemaWithArrayParent3] to [extensions]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addExtension(extension: UnnamedSchemaWithArrayParent3) = apply { + extensions = + (extensions ?: JsonField.of(mutableListOf())).also { + checkKnown("extensions", it).add(extension) + } + } + + /** + * Alias for calling [addExtension] with + * `UnnamedSchemaWithArrayParent3.ofRemoveBg(removeBg)`. + */ + fun addExtension(removeBg: UnnamedSchemaWithArrayParent3.RemoveBg) = + addExtension(UnnamedSchemaWithArrayParent3.ofRemoveBg(removeBg)) + + /** + * Alias for calling [addExtension] with + * `UnnamedSchemaWithArrayParent3.ofAutoTaggingExtension(autoTaggingExtension)`. + */ + fun addExtension( + autoTaggingExtension: UnnamedSchemaWithArrayParent3.AutoTaggingExtension + ) = + addExtension( + UnnamedSchemaWithArrayParent3.ofAutoTaggingExtension(autoTaggingExtension) + ) + + /** + * Alias for calling [addExtension] with + * `UnnamedSchemaWithArrayParent3.ofAiAutoDescription()`. + */ + fun addExtensionAiAutoDescription() = + addExtension(UnnamedSchemaWithArrayParent3.ofAiAutoDescription()) + + /** + * An array of AITags associated with the file that you want to remove, e.g. + * `["car", "vehicle", "motorsports"]`. + * + * If you want to remove all AITags associated with the file, send a string - "all". + * + * Note: The remove operation for `AITags` executes before any of the `extensions` + * are processed. + */ + fun removeAiTags(removeAiTags: RemoveAiTags) = + removeAiTags(JsonField.of(removeAiTags)) + + /** + * Sets [Builder.removeAiTags] to an arbitrary JSON value. + * + * You should usually call [Builder.removeAiTags] with a well-typed [RemoveAiTags] + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun removeAiTags(removeAiTags: JsonField) = apply { + this.removeAiTags = removeAiTags + } + + /** Alias for calling [removeAiTags] with `RemoveAiTags.ofStrings(strings)`. */ + fun removeAiTagsOfStrings(strings: List) = + removeAiTags(RemoveAiTags.ofStrings(strings)) + + /** Alias for calling [removeAiTags] with `RemoveAiTags.ofAll()`. */ + fun removeAiTagsAll() = removeAiTags(RemoveAiTags.ofAll()) + + /** + * An array of tags associated with the file, such as `["tag1", "tag2"]`. Send + * `null` to unset all tags associated with the file. + */ + fun tags(tags: List?) = tags(JsonField.ofNullable(tags)) + + /** Alias for calling [Builder.tags] with `tags.orElse(null)`. */ + fun tags(tags: Optional>) = tags(tags.getOrNull()) + + /** + * Sets [Builder.tags] to an arbitrary JSON value. + * + * You should usually call [Builder.tags] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun tags(tags: JsonField>) = apply { + this.tags = tags.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [tags]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addTag(tag: String) = apply { + tags = + (tags ?: JsonField.of(mutableListOf())).also { + checkKnown("tags", it).add(tag) + } + } + + /** + * The final status of extensions after they have completed execution will be + * delivered to this endpoint as a POST request. + * [Learn more](/docs/api-reference/digital-asset-management-dam/managing-assets/update-file-details#webhook-payload-structure) + * about the webhook payload structure. + */ + fun webhookUrl(webhookUrl: String) = webhookUrl(JsonField.of(webhookUrl)) + + /** + * Sets [Builder.webhookUrl] to an arbitrary JSON value. + * + * You should usually call [Builder.webhookUrl] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun webhookUrl(webhookUrl: JsonField) = apply { + this.webhookUrl = webhookUrl + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [UpdateFileDetails]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): UpdateFileDetails = + UpdateFileDetails( + customCoordinates, + customMetadata, + description, + (extensions ?: JsonMissing.of()).map { it.toImmutable() }, + removeAiTags, + (tags ?: JsonMissing.of()).map { it.toImmutable() }, + webhookUrl, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): UpdateFileDetails = apply { + if (validated) { + return@apply + } + + customCoordinates() + customMetadata().ifPresent { it.validate() } + description() + extensions().ifPresent { it.forEach { it.validate() } } + removeAiTags().ifPresent { it.validate() } + tags() + webhookUrl() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (customCoordinates.asKnown().isPresent) 1 else 0) + + (customMetadata.asKnown().getOrNull()?.validity() ?: 0) + + (if (description.asKnown().isPresent) 1 else 0) + + (extensions.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + (removeAiTags.asKnown().getOrNull()?.validity() ?: 0) + + (tags.asKnown().getOrNull()?.size ?: 0) + + (if (webhookUrl.asKnown().isPresent) 1 else 0) + + /** + * A key-value data to be associated with the asset. To unset a key, send `null` value + * for that key. Before setting any custom metadata on an asset you have to create the + * field using custom metadata fields API. + */ + class CustomMetadata + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [CustomMetadata]. + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [CustomMetadata]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(customMetadata: CustomMetadata) = apply { + additionalProperties = customMetadata.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [CustomMetadata]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): CustomMetadata = CustomMetadata(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): CustomMetadata = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> + !value.isNull() && !value.isMissing() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is CustomMetadata && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "CustomMetadata{additionalProperties=$additionalProperties}" + } + + @JsonDeserialize(using = UnnamedSchemaWithArrayParent3.Deserializer::class) + @JsonSerialize(using = UnnamedSchemaWithArrayParent3.Serializer::class) + class UnnamedSchemaWithArrayParent3 + private constructor( + private val removeBg: RemoveBg? = null, + private val autoTaggingExtension: AutoTaggingExtension? = null, + private val aiAutoDescription: JsonValue? = null, + private val _json: JsonValue? = null, + ) { + + fun removeBg(): Optional = Optional.ofNullable(removeBg) + + fun autoTaggingExtension(): Optional = + Optional.ofNullable(autoTaggingExtension) + + fun aiAutoDescription(): Optional = + Optional.ofNullable(aiAutoDescription) + + fun isRemoveBg(): Boolean = removeBg != null + + fun isAutoTaggingExtension(): Boolean = autoTaggingExtension != null + + fun isAiAutoDescription(): Boolean = aiAutoDescription != null + + fun asRemoveBg(): RemoveBg = removeBg.getOrThrow("removeBg") + + fun asAutoTaggingExtension(): AutoTaggingExtension = + autoTaggingExtension.getOrThrow("autoTaggingExtension") + + fun asAiAutoDescription(): JsonValue = + aiAutoDescription.getOrThrow("aiAutoDescription") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + removeBg != null -> visitor.visitRemoveBg(removeBg) + autoTaggingExtension != null -> + visitor.visitAutoTaggingExtension(autoTaggingExtension) + aiAutoDescription != null -> + visitor.visitAiAutoDescription(aiAutoDescription) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): UnnamedSchemaWithArrayParent3 = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitRemoveBg(removeBg: RemoveBg) { + removeBg.validate() + } + + override fun visitAutoTaggingExtension( + autoTaggingExtension: AutoTaggingExtension + ) { + autoTaggingExtension.validate() + } + + override fun visitAiAutoDescription(aiAutoDescription: JsonValue) { + aiAutoDescription.let { + if ( + it != JsonValue.from(mapOf("name" to "ai-auto-description")) + ) { + throw ImageKitInvalidDataException( + "'aiAutoDescription' is invalid, received $it" + ) + } + } + } + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitRemoveBg(removeBg: RemoveBg) = removeBg.validity() + + override fun visitAutoTaggingExtension( + autoTaggingExtension: AutoTaggingExtension + ) = autoTaggingExtension.validity() + + override fun visitAiAutoDescription(aiAutoDescription: JsonValue) = + aiAutoDescription.let { + if ( + it == JsonValue.from(mapOf("name" to "ai-auto-description")) + ) + 1 + else 0 + } + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is UnnamedSchemaWithArrayParent3 && + removeBg == other.removeBg && + autoTaggingExtension == other.autoTaggingExtension && + aiAutoDescription == other.aiAutoDescription + } + + override fun hashCode(): Int = + Objects.hash(removeBg, autoTaggingExtension, aiAutoDescription) + + override fun toString(): String = + when { + removeBg != null -> "UnnamedSchemaWithArrayParent3{removeBg=$removeBg}" + autoTaggingExtension != null -> + "UnnamedSchemaWithArrayParent3{autoTaggingExtension=$autoTaggingExtension}" + aiAutoDescription != null -> + "UnnamedSchemaWithArrayParent3{aiAutoDescription=$aiAutoDescription}" + _json != null -> "UnnamedSchemaWithArrayParent3{_unknown=$_json}" + else -> throw IllegalStateException("Invalid UnnamedSchemaWithArrayParent3") + } + + companion object { + + @JvmStatic + fun ofRemoveBg(removeBg: RemoveBg) = + UnnamedSchemaWithArrayParent3(removeBg = removeBg) + + @JvmStatic + fun ofAutoTaggingExtension(autoTaggingExtension: AutoTaggingExtension) = + UnnamedSchemaWithArrayParent3(autoTaggingExtension = autoTaggingExtension) + + @JvmStatic + fun ofAiAutoDescription() = + UnnamedSchemaWithArrayParent3( + aiAutoDescription = + JsonValue.from(mapOf("name" to "ai-auto-description")) + ) + } + + /** + * An interface that defines how to map each variant of + * [UnnamedSchemaWithArrayParent3] to a value of type [T]. + */ + interface Visitor { + + fun visitRemoveBg(removeBg: RemoveBg): T + + fun visitAutoTaggingExtension(autoTaggingExtension: AutoTaggingExtension): T + + fun visitAiAutoDescription(aiAutoDescription: JsonValue): T + + /** + * Maps an unknown variant of [UnnamedSchemaWithArrayParent3] to a value of type + * [T]. + * + * An instance of [UnnamedSchemaWithArrayParent3] can contain an unknown variant + * if it was deserialized from data that doesn't match any known variant. For + * example, if the SDK is on an older version than the API, then the API may + * respond with new variants that the SDK is unaware of. + * + * @throws ImageKitInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw ImageKitInvalidDataException( + "Unknown UnnamedSchemaWithArrayParent3: $json" + ) + } + } + + internal class Deserializer : + BaseDeserializer( + UnnamedSchemaWithArrayParent3::class + ) { + + override fun ObjectCodec.deserialize( + node: JsonNode + ): UnnamedSchemaWithArrayParent3 { + val json = JsonValue.fromJsonNode(node) + val name = json.asObject().getOrNull()?.get("name")?.asString()?.getOrNull() + + when (name) { + "remove-bg" -> { + return tryDeserialize(node, jacksonTypeRef())?.let { + UnnamedSchemaWithArrayParent3(removeBg = it, _json = json) + } ?: UnnamedSchemaWithArrayParent3(_json = json) + } + "ai-auto-description" -> { + return tryDeserialize(node, jacksonTypeRef()) + ?.let { + UnnamedSchemaWithArrayParent3( + aiAutoDescription = it, + _json = json, + ) + } + ?.takeIf { it.isValid() } + ?: UnnamedSchemaWithArrayParent3(_json = json) + } + } + + return tryDeserialize(node, jacksonTypeRef())?.let { + UnnamedSchemaWithArrayParent3(autoTaggingExtension = it, _json = json) + } ?: UnnamedSchemaWithArrayParent3(_json = json) + } + } + + internal class Serializer : + BaseSerializer( + UnnamedSchemaWithArrayParent3::class + ) { + + override fun serialize( + value: UnnamedSchemaWithArrayParent3, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.removeBg != null -> generator.writeObject(value.removeBg) + value.autoTaggingExtension != null -> + generator.writeObject(value.autoTaggingExtension) + value.aiAutoDescription != null -> + generator.writeObject(value.aiAutoDescription) + value._json != null -> generator.writeObject(value._json) + else -> + throw IllegalStateException("Invalid UnnamedSchemaWithArrayParent3") + } + } + } + + class RemoveBg + private constructor( + private val name: JsonValue, + private val options: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("name") @ExcludeMissing name: JsonValue = JsonMissing.of(), + @JsonProperty("options") + @ExcludeMissing + options: JsonField = JsonMissing.of(), + ) : this(name, options, mutableMapOf()) + + /** + * Specifies the background removal extension. + * + * Expected to always return the following: + * ```java + * JsonValue.from("remove-bg") + * ``` + * + * However, this method can be useful for debugging and logging (e.g. if the + * server responded with an unexpected value). + */ + @JsonProperty("name") @ExcludeMissing fun _name(): JsonValue = name + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun options(): Optional = options.getOptional("options") + + /** + * Returns the raw JSON value of [options]. + * + * Unlike [options], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("options") + @ExcludeMissing + fun _options(): JsonField = options + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [RemoveBg]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [RemoveBg]. */ + class Builder internal constructor() { + + private var name: JsonValue = JsonValue.from("remove-bg") + private var options: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = + mutableMapOf() + + @JvmSynthetic + internal fun from(removeBg: RemoveBg) = apply { + name = removeBg.name + options = removeBg.options + additionalProperties = removeBg.additionalProperties.toMutableMap() + } + + /** + * Sets the field to an arbitrary JSON value. + * + * It is usually unnecessary to call this method because the field defaults + * to the following: + * ```java + * JsonValue.from("remove-bg") + * ``` + * + * This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun name(name: JsonValue) = apply { this.name = name } + + fun options(options: Options) = options(JsonField.of(options)) + + /** + * Sets [Builder.options] to an arbitrary JSON value. + * + * You should usually call [Builder.options] with a well-typed [Options] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun options(options: JsonField) = apply { this.options = options } + + fun additionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties( + additionalProperties: Map + ) = apply { this.additionalProperties.putAll(additionalProperties) } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [RemoveBg]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): RemoveBg = + RemoveBg(name, options, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): RemoveBg = apply { + if (validated) { + return@apply + } + + _name().let { + if (it != JsonValue.from("remove-bg")) { + throw ImageKitInvalidDataException( + "'name' is invalid, received $it" + ) + } + } + options().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + name.let { if (it == JsonValue.from("remove-bg")) 1 else 0 } + + (options.asKnown().getOrNull()?.validity() ?: 0) + + class Options + private constructor( + private val addShadow: JsonField, + private val bgColor: JsonField, + private val bgImageUrl: JsonField, + private val semitransparency: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("add_shadow") + @ExcludeMissing + addShadow: JsonField = JsonMissing.of(), + @JsonProperty("bg_color") + @ExcludeMissing + bgColor: JsonField = JsonMissing.of(), + @JsonProperty("bg_image_url") + @ExcludeMissing + bgImageUrl: JsonField = JsonMissing.of(), + @JsonProperty("semitransparency") + @ExcludeMissing + semitransparency: JsonField = JsonMissing.of(), + ) : this(addShadow, bgColor, bgImageUrl, semitransparency, mutableMapOf()) + + /** + * Whether to add an artificial shadow to the result. Default is false. + * Note: Adding shadows is currently only supported for car photos. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun addShadow(): Optional = addShadow.getOptional("add_shadow") + + /** + * Specifies a solid color background using hex code (e.g., "81d4fa", "fff") + * or color name (e.g., "green"). If this parameter is set, `bg_image_url` + * must be empty. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun bgColor(): Optional = bgColor.getOptional("bg_color") + + /** + * Sets a background image from a URL. If this parameter is set, `bg_color` + * must be empty. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun bgImageUrl(): Optional = bgImageUrl.getOptional("bg_image_url") + + /** + * Allows semi-transparent regions in the result. Default is true. Note: + * Semitransparency is currently only supported for car windows. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun semitransparency(): Optional = + semitransparency.getOptional("semitransparency") + + /** + * Returns the raw JSON value of [addShadow]. + * + * Unlike [addShadow], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("add_shadow") + @ExcludeMissing + fun _addShadow(): JsonField = addShadow + + /** + * Returns the raw JSON value of [bgColor]. + * + * Unlike [bgColor], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("bg_color") + @ExcludeMissing + fun _bgColor(): JsonField = bgColor + + /** + * Returns the raw JSON value of [bgImageUrl]. + * + * Unlike [bgImageUrl], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("bg_image_url") + @ExcludeMissing + fun _bgImageUrl(): JsonField = bgImageUrl + + /** + * Returns the raw JSON value of [semitransparency]. + * + * Unlike [semitransparency], this method doesn't throw if the JSON field + * has an unexpected type. + */ + @JsonProperty("semitransparency") + @ExcludeMissing + fun _semitransparency(): JsonField = semitransparency + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Options]. + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Options]. */ + class Builder internal constructor() { + + private var addShadow: JsonField = JsonMissing.of() + private var bgColor: JsonField = JsonMissing.of() + private var bgImageUrl: JsonField = JsonMissing.of() + private var semitransparency: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = + mutableMapOf() + + @JvmSynthetic + internal fun from(options: Options) = apply { + addShadow = options.addShadow + bgColor = options.bgColor + bgImageUrl = options.bgImageUrl + semitransparency = options.semitransparency + additionalProperties = options.additionalProperties.toMutableMap() + } + + /** + * Whether to add an artificial shadow to the result. Default is false. + * Note: Adding shadows is currently only supported for car photos. + */ + fun addShadow(addShadow: Boolean) = addShadow(JsonField.of(addShadow)) + + /** + * Sets [Builder.addShadow] to an arbitrary JSON value. + * + * You should usually call [Builder.addShadow] with a well-typed + * [Boolean] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ + fun addShadow(addShadow: JsonField) = apply { + this.addShadow = addShadow + } + + /** + * Specifies a solid color background using hex code (e.g., "81d4fa", + * "fff") or color name (e.g., "green"). If this parameter is set, + * `bg_image_url` must be empty. + */ + fun bgColor(bgColor: String) = bgColor(JsonField.of(bgColor)) + + /** + * Sets [Builder.bgColor] to an arbitrary JSON value. + * + * You should usually call [Builder.bgColor] with a well-typed [String] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun bgColor(bgColor: JsonField) = apply { + this.bgColor = bgColor + } + + /** + * Sets a background image from a URL. If this parameter is set, + * `bg_color` must be empty. + */ + fun bgImageUrl(bgImageUrl: String) = + bgImageUrl(JsonField.of(bgImageUrl)) + + /** + * Sets [Builder.bgImageUrl] to an arbitrary JSON value. + * + * You should usually call [Builder.bgImageUrl] with a well-typed + * [String] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ + fun bgImageUrl(bgImageUrl: JsonField) = apply { + this.bgImageUrl = bgImageUrl + } + + /** + * Allows semi-transparent regions in the result. Default is true. Note: + * Semitransparency is currently only supported for car windows. + */ + fun semitransparency(semitransparency: Boolean) = + semitransparency(JsonField.of(semitransparency)) + + /** + * Sets [Builder.semitransparency] to an arbitrary JSON value. + * + * You should usually call [Builder.semitransparency] with a well-typed + * [Boolean] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ + fun semitransparency(semitransparency: JsonField) = apply { + this.semitransparency = semitransparency + } + + fun additionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties( + additionalProperties: Map + ) = apply { this.additionalProperties.putAll(additionalProperties) } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Options]. + * + * Further updates to this [Builder] will not mutate the returned + * instance. + */ + fun build(): Options = + Options( + addShadow, + bgColor, + bgImageUrl, + semitransparency, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Options = apply { + if (validated) { + return@apply + } + + addShadow() + bgColor() + bgImageUrl() + semitransparency() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this + * object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (addShadow.asKnown().isPresent) 1 else 0) + + (if (bgColor.asKnown().isPresent) 1 else 0) + + (if (bgImageUrl.asKnown().isPresent) 1 else 0) + + (if (semitransparency.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Options && + addShadow == other.addShadow && + bgColor == other.bgColor && + bgImageUrl == other.bgImageUrl && + semitransparency == other.semitransparency && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + addShadow, + bgColor, + bgImageUrl, + semitransparency, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Options{addShadow=$addShadow, bgColor=$bgColor, bgImageUrl=$bgImageUrl, semitransparency=$semitransparency, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is RemoveBg && + name == other.name && + options == other.options && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(name, options, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "RemoveBg{name=$name, options=$options, additionalProperties=$additionalProperties}" + } + + class AutoTaggingExtension + private constructor( + private val maxTags: JsonField, + private val minConfidence: JsonField, + private val name: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("maxTags") + @ExcludeMissing + maxTags: JsonField = JsonMissing.of(), + @JsonProperty("minConfidence") + @ExcludeMissing + minConfidence: JsonField = JsonMissing.of(), + @JsonProperty("name") + @ExcludeMissing + name: JsonField = JsonMissing.of(), + ) : this(maxTags, minConfidence, name, mutableMapOf()) + + /** + * Maximum number of tags to attach to the asset. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type + * or is unexpectedly missing or null (e.g. if the server responded with an + * unexpected value). + */ + fun maxTags(): Long = maxTags.getRequired("maxTags") + + /** + * Minimum confidence level for tags to be considered valid. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type + * or is unexpectedly missing or null (e.g. if the server responded with an + * unexpected value). + */ + fun minConfidence(): Long = minConfidence.getRequired("minConfidence") + + /** + * Specifies the auto-tagging extension used. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type + * or is unexpectedly missing or null (e.g. if the server responded with an + * unexpected value). + */ + fun name(): Name = name.getRequired("name") + + /** + * Returns the raw JSON value of [maxTags]. + * + * Unlike [maxTags], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("maxTags") + @ExcludeMissing + fun _maxTags(): JsonField = maxTags + + /** + * Returns the raw JSON value of [minConfidence]. + * + * Unlike [minConfidence], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("minConfidence") + @ExcludeMissing + fun _minConfidence(): JsonField = minConfidence + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [AutoTaggingExtension]. + * + * The following fields are required: + * ```java + * .maxTags() + * .minConfidence() + * .name() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [AutoTaggingExtension]. */ + class Builder internal constructor() { + + private var maxTags: JsonField? = null + private var minConfidence: JsonField? = null + private var name: JsonField? = null + private var additionalProperties: MutableMap = + mutableMapOf() + + @JvmSynthetic + internal fun from(autoTaggingExtension: AutoTaggingExtension) = apply { + maxTags = autoTaggingExtension.maxTags + minConfidence = autoTaggingExtension.minConfidence + name = autoTaggingExtension.name + additionalProperties = + autoTaggingExtension.additionalProperties.toMutableMap() + } + + /** Maximum number of tags to attach to the asset. */ + fun maxTags(maxTags: Long) = maxTags(JsonField.of(maxTags)) + + /** + * Sets [Builder.maxTags] to an arbitrary JSON value. + * + * You should usually call [Builder.maxTags] with a well-typed [Long] value + * instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun maxTags(maxTags: JsonField) = apply { this.maxTags = maxTags } + + /** Minimum confidence level for tags to be considered valid. */ + fun minConfidence(minConfidence: Long) = + minConfidence(JsonField.of(minConfidence)) + + /** + * Sets [Builder.minConfidence] to an arbitrary JSON value. + * + * You should usually call [Builder.minConfidence] with a well-typed [Long] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun minConfidence(minConfidence: JsonField) = apply { + this.minConfidence = minConfidence + } + + /** Specifies the auto-tagging extension used. */ + fun name(name: Name) = name(JsonField.of(name)) + + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [Name] value + * instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun name(name: JsonField) = apply { this.name = name } + + fun additionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties( + additionalProperties: Map + ) = apply { this.additionalProperties.putAll(additionalProperties) } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [AutoTaggingExtension]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .maxTags() + * .minConfidence() + * .name() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): AutoTaggingExtension = + AutoTaggingExtension( + checkRequired("maxTags", maxTags), + checkRequired("minConfidence", minConfidence), + checkRequired("name", name), + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): AutoTaggingExtension = apply { + if (validated) { + return@apply + } + + maxTags() + minConfidence() + name().validate() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (maxTags.asKnown().isPresent) 1 else 0) + + (if (minConfidence.asKnown().isPresent) 1 else 0) + + (name.asKnown().getOrNull()?.validity() ?: 0) + + /** Specifies the auto-tagging extension used. */ + class Name + @JsonCreator + private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data + * that doesn't match any known member, and you want to know that value. For + * example, if the SDK is on an older version than the API, then the API may + * respond with new members that the SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue + fun _value(): JsonField = value + + companion object { + + @JvmField val GOOGLE_AUTO_TAGGING = of("google-auto-tagging") + + @JvmField val AWS_AUTO_TAGGING = of("aws-auto-tagging") + + @JvmStatic fun of(value: String) = Name(JsonField.of(value)) + } + + /** An enum containing [Name]'s known values. */ + enum class Known { + GOOGLE_AUTO_TAGGING, + AWS_AUTO_TAGGING, + } + + /** + * An enum containing [Name]'s known values, as well as an [_UNKNOWN] + * member. + * + * An instance of [Name] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For + * example, if the SDK is on an older version than the API, then the API + * may respond with new members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + GOOGLE_AUTO_TAGGING, + AWS_AUTO_TAGGING, + /** + * An enum member indicating that [Name] was instantiated with an + * unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always + * known or if you want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + GOOGLE_AUTO_TAGGING -> Value.GOOGLE_AUTO_TAGGING + AWS_AUTO_TAGGING -> Value.AWS_AUTO_TAGGING + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always + * known and don't want to throw for the unknown case. + * + * @throws ImageKitInvalidDataException if this class instance's value is a + * not a known member. + */ + fun known(): Known = + when (this) { + GOOGLE_AUTO_TAGGING -> Known.GOOGLE_AUTO_TAGGING + AWS_AUTO_TAGGING -> Known.AWS_AUTO_TAGGING + else -> throw ImageKitInvalidDataException("Unknown Name: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily + * for debugging and generally doesn't throw. + * + * @throws ImageKitInvalidDataException if this class instance's value does + * not have the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + ImageKitInvalidDataException("Value is not a String") + } + + private var validated: Boolean = false + + fun validate(): Name = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this + * object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Name && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is AutoTaggingExtension && + maxTags == other.maxTags && + minConfidence == other.minConfidence && + name == other.name && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(maxTags, minConfidence, name, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "AutoTaggingExtension{maxTags=$maxTags, minConfidence=$minConfidence, name=$name, additionalProperties=$additionalProperties}" + } + } + + /** + * An array of AITags associated with the file that you want to remove, e.g. `["car", + * "vehicle", "motorsports"]`. + * + * If you want to remove all AITags associated with the file, send a string - "all". + * + * Note: The remove operation for `AITags` executes before any of the `extensions` are + * processed. + */ + @JsonDeserialize(using = RemoveAiTags.Deserializer::class) + @JsonSerialize(using = RemoveAiTags.Serializer::class) + class RemoveAiTags + private constructor( + private val strings: List? = null, + private val all: JsonValue? = null, + private val _json: JsonValue? = null, + ) { + + fun strings(): Optional> = Optional.ofNullable(strings) + + fun all(): Optional = Optional.ofNullable(all) + + fun isStrings(): Boolean = strings != null + + fun isAll(): Boolean = all != null + + fun asStrings(): List = strings.getOrThrow("strings") + + fun asAll(): JsonValue = all.getOrThrow("all") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + strings != null -> visitor.visitStrings(strings) + all != null -> visitor.visitAll(all) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): RemoveAiTags = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitStrings(strings: List) {} + + override fun visitAll(all: JsonValue) { + all.let { + if (it != JsonValue.from("all")) { + throw ImageKitInvalidDataException( + "'all' is invalid, received $it" + ) + } + } + } + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitStrings(strings: List) = strings.size + + override fun visitAll(all: JsonValue) = + all.let { if (it == JsonValue.from("all")) 1 else 0 } + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is RemoveAiTags && strings == other.strings && all == other.all + } + + override fun hashCode(): Int = Objects.hash(strings, all) + + override fun toString(): String = + when { + strings != null -> "RemoveAiTags{strings=$strings}" + all != null -> "RemoveAiTags{all=$all}" + _json != null -> "RemoveAiTags{_unknown=$_json}" + else -> throw IllegalStateException("Invalid RemoveAiTags") + } + + companion object { + + @JvmStatic + fun ofStrings(strings: List) = + RemoveAiTags(strings = strings.toImmutable()) + + @JvmStatic fun ofAll() = RemoveAiTags(all = JsonValue.from("all")) + } + + /** + * An interface that defines how to map each variant of [RemoveAiTags] to a value of + * type [T]. + */ + interface Visitor { + + fun visitStrings(strings: List): T + + fun visitAll(all: JsonValue): T + + /** + * Maps an unknown variant of [RemoveAiTags] to a value of type [T]. + * + * An instance of [RemoveAiTags] can contain an unknown variant if it was + * deserialized from data that doesn't match any known variant. For example, if + * the SDK is on an older version than the API, then the API may respond with + * new variants that the SDK is unaware of. + * + * @throws ImageKitInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw ImageKitInvalidDataException("Unknown RemoveAiTags: $json") + } + } + + internal class Deserializer : BaseDeserializer(RemoveAiTags::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): RemoveAiTags { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef()) + ?.let { RemoveAiTags(all = it, _json = json) } + ?.takeIf { it.isValid() }, + tryDeserialize(node, jacksonTypeRef>())?.let { + RemoveAiTags(strings = it, _json = json) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely + // incompatible with all the possible variants (e.g. deserializing from + // object). + 0 -> RemoveAiTags(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then use + // the first completely valid match, or simply the first match if none + // are completely valid. + else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() + } + } + } + + internal class Serializer : BaseSerializer(RemoveAiTags::class) { + + override fun serialize( + value: RemoveAiTags, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.strings != null -> generator.writeObject(value.strings) + value.all != null -> generator.writeObject(value.all) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid RemoveAiTags") + } + } + } + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is UpdateFileDetails && + customCoordinates == other.customCoordinates && + customMetadata == other.customMetadata && + description == other.description && + extensions == other.extensions && + removeAiTags == other.removeAiTags && + tags == other.tags && + webhookUrl == other.webhookUrl && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + customCoordinates, + customMetadata, + description, + extensions, + removeAiTags, + tags, + webhookUrl, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "UpdateFileDetails{customCoordinates=$customCoordinates, customMetadata=$customMetadata, description=$description, extensions=$extensions, removeAiTags=$removeAiTags, tags=$tags, webhookUrl=$webhookUrl, additionalProperties=$additionalProperties}" + } + + class ChangePublicationStatus + private constructor( + private val publish: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("publish") + @ExcludeMissing + publish: JsonField = JsonMissing.of() + ) : this(publish, mutableMapOf()) + + /** + * Configure the publication status of a file and its versions. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun publish(): Optional = publish.getOptional("publish") + + /** + * Returns the raw JSON value of [publish]. + * + * Unlike [publish], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("publish") @ExcludeMissing fun _publish(): JsonField = publish + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [ChangePublicationStatus]. + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ChangePublicationStatus]. */ + class Builder internal constructor() { + + private var publish: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(changePublicationStatus: ChangePublicationStatus) = apply { + publish = changePublicationStatus.publish + additionalProperties = + changePublicationStatus.additionalProperties.toMutableMap() + } + + /** Configure the publication status of a file and its versions. */ + fun publish(publish: Publish) = publish(JsonField.of(publish)) + + /** + * Sets [Builder.publish] to an arbitrary JSON value. + * + * You should usually call [Builder.publish] with a well-typed [Publish] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun publish(publish: JsonField) = apply { this.publish = publish } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ChangePublicationStatus]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): ChangePublicationStatus = + ChangePublicationStatus(publish, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): ChangePublicationStatus = apply { + if (validated) { + return@apply + } + + publish().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = (publish.asKnown().getOrNull()?.validity() ?: 0) + + /** Configure the publication status of a file and its versions. */ + class Publish + private constructor( + private val isPublished: JsonField, + private val includeFileVersions: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("isPublished") + @ExcludeMissing + isPublished: JsonField = JsonMissing.of(), + @JsonProperty("includeFileVersions") + @ExcludeMissing + includeFileVersions: JsonField = JsonMissing.of(), + ) : this(isPublished, includeFileVersions, mutableMapOf()) + + /** + * Set to `true` to publish the file. Set to `false` to unpublish the file. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or + * is unexpectedly missing or null (e.g. if the server responded with an + * unexpected value). + */ + fun isPublished(): Boolean = isPublished.getRequired("isPublished") + + /** + * Set to `true` to publish/unpublish all versions of the file. Set to `false` to + * publish/unpublish only the current version of the file. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun includeFileVersions(): Optional = + includeFileVersions.getOptional("includeFileVersions") + + /** + * Returns the raw JSON value of [isPublished]. + * + * Unlike [isPublished], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("isPublished") + @ExcludeMissing + fun _isPublished(): JsonField = isPublished + + /** + * Returns the raw JSON value of [includeFileVersions]. + * + * Unlike [includeFileVersions], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("includeFileVersions") + @ExcludeMissing + fun _includeFileVersions(): JsonField = includeFileVersions + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Publish]. + * + * The following fields are required: + * ```java + * .isPublished() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Publish]. */ + class Builder internal constructor() { + + private var isPublished: JsonField? = null + private var includeFileVersions: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(publish: Publish) = apply { + isPublished = publish.isPublished + includeFileVersions = publish.includeFileVersions + additionalProperties = publish.additionalProperties.toMutableMap() + } + + /** Set to `true` to publish the file. Set to `false` to unpublish the file. */ + fun isPublished(isPublished: Boolean) = isPublished(JsonField.of(isPublished)) + + /** + * Sets [Builder.isPublished] to an arbitrary JSON value. + * + * You should usually call [Builder.isPublished] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun isPublished(isPublished: JsonField) = apply { + this.isPublished = isPublished + } + + /** + * Set to `true` to publish/unpublish all versions of the file. Set to `false` + * to publish/unpublish only the current version of the file. + */ + fun includeFileVersions(includeFileVersions: Boolean) = + includeFileVersions(JsonField.of(includeFileVersions)) + + /** + * Sets [Builder.includeFileVersions] to an arbitrary JSON value. + * + * You should usually call [Builder.includeFileVersions] with a well-typed + * [Boolean] value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun includeFileVersions(includeFileVersions: JsonField) = apply { + this.includeFileVersions = includeFileVersions + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Publish]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .isPublished() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Publish = + Publish( + checkRequired("isPublished", isPublished), + includeFileVersions, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Publish = apply { + if (validated) { + return@apply + } + + isPublished() + includeFileVersions() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (isPublished.asKnown().isPresent) 1 else 0) + + (if (includeFileVersions.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Publish && + isPublished == other.isPublished && + includeFileVersions == other.includeFileVersions && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(isPublished, includeFileVersions, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Publish{isPublished=$isPublished, includeFileVersions=$includeFileVersions, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ChangePublicationStatus && + publish == other.publish && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(publish, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ChangePublicationStatus{publish=$publish, additionalProperties=$additionalProperties}" + } + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is FileUpdateParams && + fileId == other.fileId && + body == other.body && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = + Objects.hash(fileId, body, additionalHeaders, additionalQueryParams) + + override fun toString() = + "FileUpdateParams{fileId=$fileId, body=$body, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/files/FileUpdateResponse.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/files/FileUpdateResponse.kt new file mode 100644 index 0000000..d8ecc3e --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/files/FileUpdateResponse.kt @@ -0,0 +1,1934 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.files + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.imagekit.api.core.Enum +import com.imagekit.api.core.ExcludeMissing +import com.imagekit.api.core.JsonField +import com.imagekit.api.core.JsonMissing +import com.imagekit.api.core.JsonValue +import com.imagekit.api.core.checkKnown +import com.imagekit.api.core.toImmutable +import com.imagekit.api.errors.ImageKitInvalidDataException +import java.time.OffsetDateTime +import java.util.Collections +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** Object containing details of a file or file version. */ +class FileUpdateResponse +private constructor( + private val aiTags: JsonField>, + private val createdAt: JsonField, + private val customCoordinates: JsonField, + private val customMetadata: JsonField, + private val description: JsonField, + private val fileId: JsonField, + private val filePath: JsonField, + private val fileType: JsonField, + private val hasAlpha: JsonField, + private val height: JsonField, + private val isPrivateFile: JsonField, + private val isPublished: JsonField, + private val mime: JsonField, + private val name: JsonField, + private val size: JsonField, + private val tags: JsonField>, + private val thumbnail: JsonField, + private val type: JsonField, + private val updatedAt: JsonField, + private val url: JsonField, + private val versionInfo: JsonField, + private val width: JsonField, + private val extensionStatus: JsonField, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("AITags") + @ExcludeMissing + aiTags: JsonField> = JsonMissing.of(), + @JsonProperty("createdAt") + @ExcludeMissing + createdAt: JsonField = JsonMissing.of(), + @JsonProperty("customCoordinates") + @ExcludeMissing + customCoordinates: JsonField = JsonMissing.of(), + @JsonProperty("customMetadata") + @ExcludeMissing + customMetadata: JsonField = JsonMissing.of(), + @JsonProperty("description") + @ExcludeMissing + description: JsonField = JsonMissing.of(), + @JsonProperty("fileId") @ExcludeMissing fileId: JsonField = JsonMissing.of(), + @JsonProperty("filePath") @ExcludeMissing filePath: JsonField = JsonMissing.of(), + @JsonProperty("fileType") @ExcludeMissing fileType: JsonField = JsonMissing.of(), + @JsonProperty("hasAlpha") @ExcludeMissing hasAlpha: JsonField = JsonMissing.of(), + @JsonProperty("height") @ExcludeMissing height: JsonField = JsonMissing.of(), + @JsonProperty("isPrivateFile") + @ExcludeMissing + isPrivateFile: JsonField = JsonMissing.of(), + @JsonProperty("isPublished") + @ExcludeMissing + isPublished: JsonField = JsonMissing.of(), + @JsonProperty("mime") @ExcludeMissing mime: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("size") @ExcludeMissing size: JsonField = JsonMissing.of(), + @JsonProperty("tags") @ExcludeMissing tags: JsonField> = JsonMissing.of(), + @JsonProperty("thumbnail") @ExcludeMissing thumbnail: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonField = JsonMissing.of(), + @JsonProperty("updatedAt") + @ExcludeMissing + updatedAt: JsonField = JsonMissing.of(), + @JsonProperty("url") @ExcludeMissing url: JsonField = JsonMissing.of(), + @JsonProperty("versionInfo") + @ExcludeMissing + versionInfo: JsonField = JsonMissing.of(), + @JsonProperty("width") @ExcludeMissing width: JsonField = JsonMissing.of(), + @JsonProperty("extensionStatus") + @ExcludeMissing + extensionStatus: JsonField = JsonMissing.of(), + ) : this( + aiTags, + createdAt, + customCoordinates, + customMetadata, + description, + fileId, + filePath, + fileType, + hasAlpha, + height, + isPrivateFile, + isPublished, + mime, + name, + size, + tags, + thumbnail, + type, + updatedAt, + url, + versionInfo, + width, + extensionStatus, + mutableMapOf(), + ) + + fun toFile(): File = + File.builder() + .aiTags(aiTags) + .createdAt(createdAt) + .customCoordinates(customCoordinates) + .customMetadata(customMetadata) + .description(description) + .fileId(fileId) + .filePath(filePath) + .fileType(fileType) + .hasAlpha(hasAlpha) + .height(height) + .isPrivateFile(isPrivateFile) + .isPublished(isPublished) + .mime(mime) + .name(name) + .size(size) + .tags(tags) + .thumbnail(thumbnail) + .type(type) + .updatedAt(updatedAt) + .url(url) + .versionInfo(versionInfo) + .width(width) + .build() + + /** + * An array of tags assigned to the file by auto tagging. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun aiTags(): Optional> = aiTags.getOptional("AITags") + + /** + * Date and time when the file was uploaded. The date and time is in ISO8601 format. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun createdAt(): Optional = createdAt.getOptional("createdAt") + + /** + * An string with custom coordinates of the file. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun customCoordinates(): Optional = customCoordinates.getOptional("customCoordinates") + + /** + * An object with custom metadata for the file. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun customMetadata(): Optional = + customMetadata.getOptional("customMetadata") + + /** + * Optional text to describe the contents of the file. Can be set by the user or the + * ai-auto-description extension. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun description(): Optional = description.getOptional("description") + + /** + * Unique identifier of the asset. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun fileId(): Optional = fileId.getOptional("fileId") + + /** + * Path of the file. This is the path you would use in the URL to access the file. For example, + * if the file is at the root of the media library, the path will be `/file.jpg`. If the file is + * inside a folder named `images`, the path will be `/images/file.jpg`. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun filePath(): Optional = filePath.getOptional("filePath") + + /** + * Type of the file. Possible values are `image`, `non-image`. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun fileType(): Optional = fileType.getOptional("fileType") + + /** + * Specifies if the image has an alpha channel. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun hasAlpha(): Optional = hasAlpha.getOptional("hasAlpha") + + /** + * Height of the file. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun height(): Optional = height.getOptional("height") + + /** + * Specifies if the file is private or not. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun isPrivateFile(): Optional = isPrivateFile.getOptional("isPrivateFile") + + /** + * Specifies if the file is published or not. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun isPublished(): Optional = isPublished.getOptional("isPublished") + + /** + * MIME type of the file. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun mime(): Optional = mime.getOptional("mime") + + /** + * Name of the asset. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun name(): Optional = name.getOptional("name") + + /** + * Size of the file in bytes. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun size(): Optional = size.getOptional("size") + + /** + * An array of tags assigned to the file. Tags are used to search files in the media library. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun tags(): Optional> = tags.getOptional("tags") + + /** + * URL of the thumbnail image. This URL is used to access the thumbnail image of the file in the + * media library. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun thumbnail(): Optional = thumbnail.getOptional("thumbnail") + + /** + * Type of the asset. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun type(): Optional = type.getOptional("type") + + /** + * Date and time when the file was last updated. The date and time is in ISO8601 format. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun updatedAt(): Optional = updatedAt.getOptional("updatedAt") + + /** + * URL of the file. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun url(): Optional = url.getOptional("url") + + /** + * An object with details of the file version. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun versionInfo(): Optional = versionInfo.getOptional("versionInfo") + + /** + * Width of the file. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun width(): Optional = width.getOptional("width") + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun extensionStatus(): Optional = + extensionStatus.getOptional("extensionStatus") + + /** + * Returns the raw JSON value of [aiTags]. + * + * Unlike [aiTags], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("AITags") @ExcludeMissing fun _aiTags(): JsonField> = aiTags + + /** + * Returns the raw JSON value of [createdAt]. + * + * Unlike [createdAt], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("createdAt") + @ExcludeMissing + fun _createdAt(): JsonField = createdAt + + /** + * Returns the raw JSON value of [customCoordinates]. + * + * Unlike [customCoordinates], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("customCoordinates") + @ExcludeMissing + fun _customCoordinates(): JsonField = customCoordinates + + /** + * Returns the raw JSON value of [customMetadata]. + * + * Unlike [customMetadata], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("customMetadata") + @ExcludeMissing + fun _customMetadata(): JsonField = customMetadata + + /** + * Returns the raw JSON value of [description]. + * + * Unlike [description], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("description") @ExcludeMissing fun _description(): JsonField = description + + /** + * Returns the raw JSON value of [fileId]. + * + * Unlike [fileId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("fileId") @ExcludeMissing fun _fileId(): JsonField = fileId + + /** + * Returns the raw JSON value of [filePath]. + * + * Unlike [filePath], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("filePath") @ExcludeMissing fun _filePath(): JsonField = filePath + + /** + * Returns the raw JSON value of [fileType]. + * + * Unlike [fileType], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("fileType") @ExcludeMissing fun _fileType(): JsonField = fileType + + /** + * Returns the raw JSON value of [hasAlpha]. + * + * Unlike [hasAlpha], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("hasAlpha") @ExcludeMissing fun _hasAlpha(): JsonField = hasAlpha + + /** + * Returns the raw JSON value of [height]. + * + * Unlike [height], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("height") @ExcludeMissing fun _height(): JsonField = height + + /** + * Returns the raw JSON value of [isPrivateFile]. + * + * Unlike [isPrivateFile], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("isPrivateFile") + @ExcludeMissing + fun _isPrivateFile(): JsonField = isPrivateFile + + /** + * Returns the raw JSON value of [isPublished]. + * + * Unlike [isPublished], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("isPublished") + @ExcludeMissing + fun _isPublished(): JsonField = isPublished + + /** + * Returns the raw JSON value of [mime]. + * + * Unlike [mime], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("mime") @ExcludeMissing fun _mime(): JsonField = mime + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + + /** + * Returns the raw JSON value of [size]. + * + * Unlike [size], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("size") @ExcludeMissing fun _size(): JsonField = size + + /** + * Returns the raw JSON value of [tags]. + * + * Unlike [tags], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("tags") @ExcludeMissing fun _tags(): JsonField> = tags + + /** + * Returns the raw JSON value of [thumbnail]. + * + * Unlike [thumbnail], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("thumbnail") @ExcludeMissing fun _thumbnail(): JsonField = thumbnail + + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + + /** + * Returns the raw JSON value of [updatedAt]. + * + * Unlike [updatedAt], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("updatedAt") + @ExcludeMissing + fun _updatedAt(): JsonField = updatedAt + + /** + * Returns the raw JSON value of [url]. + * + * Unlike [url], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("url") @ExcludeMissing fun _url(): JsonField = url + + /** + * Returns the raw JSON value of [versionInfo]. + * + * Unlike [versionInfo], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("versionInfo") + @ExcludeMissing + fun _versionInfo(): JsonField = versionInfo + + /** + * Returns the raw JSON value of [width]. + * + * Unlike [width], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("width") @ExcludeMissing fun _width(): JsonField = width + + /** + * Returns the raw JSON value of [extensionStatus]. + * + * Unlike [extensionStatus], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("extensionStatus") + @ExcludeMissing + fun _extensionStatus(): JsonField = extensionStatus + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [FileUpdateResponse]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [FileUpdateResponse]. */ + class Builder internal constructor() { + + private var aiTags: JsonField>? = null + private var createdAt: JsonField = JsonMissing.of() + private var customCoordinates: JsonField = JsonMissing.of() + private var customMetadata: JsonField = JsonMissing.of() + private var description: JsonField = JsonMissing.of() + private var fileId: JsonField = JsonMissing.of() + private var filePath: JsonField = JsonMissing.of() + private var fileType: JsonField = JsonMissing.of() + private var hasAlpha: JsonField = JsonMissing.of() + private var height: JsonField = JsonMissing.of() + private var isPrivateFile: JsonField = JsonMissing.of() + private var isPublished: JsonField = JsonMissing.of() + private var mime: JsonField = JsonMissing.of() + private var name: JsonField = JsonMissing.of() + private var size: JsonField = JsonMissing.of() + private var tags: JsonField>? = null + private var thumbnail: JsonField = JsonMissing.of() + private var type: JsonField = JsonMissing.of() + private var updatedAt: JsonField = JsonMissing.of() + private var url: JsonField = JsonMissing.of() + private var versionInfo: JsonField = JsonMissing.of() + private var width: JsonField = JsonMissing.of() + private var extensionStatus: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(fileUpdateResponse: FileUpdateResponse) = apply { + aiTags = fileUpdateResponse.aiTags.map { it.toMutableList() } + createdAt = fileUpdateResponse.createdAt + customCoordinates = fileUpdateResponse.customCoordinates + customMetadata = fileUpdateResponse.customMetadata + description = fileUpdateResponse.description + fileId = fileUpdateResponse.fileId + filePath = fileUpdateResponse.filePath + fileType = fileUpdateResponse.fileType + hasAlpha = fileUpdateResponse.hasAlpha + height = fileUpdateResponse.height + isPrivateFile = fileUpdateResponse.isPrivateFile + isPublished = fileUpdateResponse.isPublished + mime = fileUpdateResponse.mime + name = fileUpdateResponse.name + size = fileUpdateResponse.size + tags = fileUpdateResponse.tags.map { it.toMutableList() } + thumbnail = fileUpdateResponse.thumbnail + type = fileUpdateResponse.type + updatedAt = fileUpdateResponse.updatedAt + url = fileUpdateResponse.url + versionInfo = fileUpdateResponse.versionInfo + width = fileUpdateResponse.width + extensionStatus = fileUpdateResponse.extensionStatus + additionalProperties = fileUpdateResponse.additionalProperties.toMutableMap() + } + + /** An array of tags assigned to the file by auto tagging. */ + fun aiTags(aiTags: List?) = aiTags(JsonField.ofNullable(aiTags)) + + /** Alias for calling [Builder.aiTags] with `aiTags.orElse(null)`. */ + fun aiTags(aiTags: Optional>) = aiTags(aiTags.getOrNull()) + + /** + * Sets [Builder.aiTags] to an arbitrary JSON value. + * + * You should usually call [Builder.aiTags] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun aiTags(aiTags: JsonField>) = apply { + this.aiTags = aiTags.map { it.toMutableList() } + } + + /** + * Adds a single [File.AiTag] to [aiTags]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addAiTag(aiTag: File.AiTag) = apply { + aiTags = + (aiTags ?: JsonField.of(mutableListOf())).also { + checkKnown("aiTags", it).add(aiTag) + } + } + + /** Date and time when the file was uploaded. The date and time is in ISO8601 format. */ + fun createdAt(createdAt: OffsetDateTime) = createdAt(JsonField.of(createdAt)) + + /** + * Sets [Builder.createdAt] to an arbitrary JSON value. + * + * You should usually call [Builder.createdAt] with a well-typed [OffsetDateTime] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun createdAt(createdAt: JsonField) = apply { this.createdAt = createdAt } + + /** An string with custom coordinates of the file. */ + fun customCoordinates(customCoordinates: String?) = + customCoordinates(JsonField.ofNullable(customCoordinates)) + + /** Alias for calling [Builder.customCoordinates] with `customCoordinates.orElse(null)`. */ + fun customCoordinates(customCoordinates: Optional) = + customCoordinates(customCoordinates.getOrNull()) + + /** + * Sets [Builder.customCoordinates] to an arbitrary JSON value. + * + * You should usually call [Builder.customCoordinates] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun customCoordinates(customCoordinates: JsonField) = apply { + this.customCoordinates = customCoordinates + } + + /** An object with custom metadata for the file. */ + fun customMetadata(customMetadata: File.CustomMetadata) = + customMetadata(JsonField.of(customMetadata)) + + /** + * Sets [Builder.customMetadata] to an arbitrary JSON value. + * + * You should usually call [Builder.customMetadata] with a well-typed [File.CustomMetadata] + * value instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun customMetadata(customMetadata: JsonField) = apply { + this.customMetadata = customMetadata + } + + /** + * Optional text to describe the contents of the file. Can be set by the user or the + * ai-auto-description extension. + */ + fun description(description: String) = description(JsonField.of(description)) + + /** + * Sets [Builder.description] to an arbitrary JSON value. + * + * You should usually call [Builder.description] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun description(description: JsonField) = apply { this.description = description } + + /** Unique identifier of the asset. */ + fun fileId(fileId: String) = fileId(JsonField.of(fileId)) + + /** + * Sets [Builder.fileId] to an arbitrary JSON value. + * + * You should usually call [Builder.fileId] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun fileId(fileId: JsonField) = apply { this.fileId = fileId } + + /** + * Path of the file. This is the path you would use in the URL to access the file. For + * example, if the file is at the root of the media library, the path will be `/file.jpg`. + * If the file is inside a folder named `images`, the path will be `/images/file.jpg`. + */ + fun filePath(filePath: String) = filePath(JsonField.of(filePath)) + + /** + * Sets [Builder.filePath] to an arbitrary JSON value. + * + * You should usually call [Builder.filePath] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun filePath(filePath: JsonField) = apply { this.filePath = filePath } + + /** Type of the file. Possible values are `image`, `non-image`. */ + fun fileType(fileType: String) = fileType(JsonField.of(fileType)) + + /** + * Sets [Builder.fileType] to an arbitrary JSON value. + * + * You should usually call [Builder.fileType] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun fileType(fileType: JsonField) = apply { this.fileType = fileType } + + /** Specifies if the image has an alpha channel. */ + fun hasAlpha(hasAlpha: Boolean) = hasAlpha(JsonField.of(hasAlpha)) + + /** + * Sets [Builder.hasAlpha] to an arbitrary JSON value. + * + * You should usually call [Builder.hasAlpha] with a well-typed [Boolean] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun hasAlpha(hasAlpha: JsonField) = apply { this.hasAlpha = hasAlpha } + + /** Height of the file. */ + fun height(height: Double) = height(JsonField.of(height)) + + /** + * Sets [Builder.height] to an arbitrary JSON value. + * + * You should usually call [Builder.height] with a well-typed [Double] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun height(height: JsonField) = apply { this.height = height } + + /** Specifies if the file is private or not. */ + fun isPrivateFile(isPrivateFile: Boolean) = isPrivateFile(JsonField.of(isPrivateFile)) + + /** + * Sets [Builder.isPrivateFile] to an arbitrary JSON value. + * + * You should usually call [Builder.isPrivateFile] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun isPrivateFile(isPrivateFile: JsonField) = apply { + this.isPrivateFile = isPrivateFile + } + + /** Specifies if the file is published or not. */ + fun isPublished(isPublished: Boolean) = isPublished(JsonField.of(isPublished)) + + /** + * Sets [Builder.isPublished] to an arbitrary JSON value. + * + * You should usually call [Builder.isPublished] with a well-typed [Boolean] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun isPublished(isPublished: JsonField) = apply { this.isPublished = isPublished } + + /** MIME type of the file. */ + fun mime(mime: String) = mime(JsonField.of(mime)) + + /** + * Sets [Builder.mime] to an arbitrary JSON value. + * + * You should usually call [Builder.mime] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun mime(mime: JsonField) = apply { this.mime = mime } + + /** Name of the asset. */ + fun name(name: String) = name(JsonField.of(name)) + + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun name(name: JsonField) = apply { this.name = name } + + /** Size of the file in bytes. */ + fun size(size: Double) = size(JsonField.of(size)) + + /** + * Sets [Builder.size] to an arbitrary JSON value. + * + * You should usually call [Builder.size] with a well-typed [Double] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun size(size: JsonField) = apply { this.size = size } + + /** + * An array of tags assigned to the file. Tags are used to search files in the media + * library. + */ + fun tags(tags: List?) = tags(JsonField.ofNullable(tags)) + + /** Alias for calling [Builder.tags] with `tags.orElse(null)`. */ + fun tags(tags: Optional>) = tags(tags.getOrNull()) + + /** + * Sets [Builder.tags] to an arbitrary JSON value. + * + * You should usually call [Builder.tags] with a well-typed `List` value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun tags(tags: JsonField>) = apply { + this.tags = tags.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [tags]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addTag(tag: String) = apply { + tags = (tags ?: JsonField.of(mutableListOf())).also { checkKnown("tags", it).add(tag) } + } + + /** + * URL of the thumbnail image. This URL is used to access the thumbnail image of the file in + * the media library. + */ + fun thumbnail(thumbnail: String) = thumbnail(JsonField.of(thumbnail)) + + /** + * Sets [Builder.thumbnail] to an arbitrary JSON value. + * + * You should usually call [Builder.thumbnail] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun thumbnail(thumbnail: JsonField) = apply { this.thumbnail = thumbnail } + + /** Type of the asset. */ + fun type(type: File.Type) = type(JsonField.of(type)) + + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [File.Type] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun type(type: JsonField) = apply { this.type = type } + + /** Date and time when the file was last updated. The date and time is in ISO8601 format. */ + fun updatedAt(updatedAt: OffsetDateTime) = updatedAt(JsonField.of(updatedAt)) + + /** + * Sets [Builder.updatedAt] to an arbitrary JSON value. + * + * You should usually call [Builder.updatedAt] with a well-typed [OffsetDateTime] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun updatedAt(updatedAt: JsonField) = apply { this.updatedAt = updatedAt } + + /** URL of the file. */ + fun url(url: String) = url(JsonField.of(url)) + + /** + * Sets [Builder.url] to an arbitrary JSON value. + * + * You should usually call [Builder.url] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun url(url: JsonField) = apply { this.url = url } + + /** An object with details of the file version. */ + fun versionInfo(versionInfo: File.VersionInfo) = versionInfo(JsonField.of(versionInfo)) + + /** + * Sets [Builder.versionInfo] to an arbitrary JSON value. + * + * You should usually call [Builder.versionInfo] with a well-typed [File.VersionInfo] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun versionInfo(versionInfo: JsonField) = apply { + this.versionInfo = versionInfo + } + + /** Width of the file. */ + fun width(width: Double) = width(JsonField.of(width)) + + /** + * Sets [Builder.width] to an arbitrary JSON value. + * + * You should usually call [Builder.width] with a well-typed [Double] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun width(width: JsonField) = apply { this.width = width } + + fun extensionStatus(extensionStatus: ExtensionStatus) = + extensionStatus(JsonField.of(extensionStatus)) + + /** + * Sets [Builder.extensionStatus] to an arbitrary JSON value. + * + * You should usually call [Builder.extensionStatus] with a well-typed [ExtensionStatus] + * value instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun extensionStatus(extensionStatus: JsonField) = apply { + this.extensionStatus = extensionStatus + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [FileUpdateResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): FileUpdateResponse = + FileUpdateResponse( + (aiTags ?: JsonMissing.of()).map { it.toImmutable() }, + createdAt, + customCoordinates, + customMetadata, + description, + fileId, + filePath, + fileType, + hasAlpha, + height, + isPrivateFile, + isPublished, + mime, + name, + size, + (tags ?: JsonMissing.of()).map { it.toImmutable() }, + thumbnail, + type, + updatedAt, + url, + versionInfo, + width, + extensionStatus, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): FileUpdateResponse = apply { + if (validated) { + return@apply + } + + aiTags().ifPresent { it.forEach { it.validate() } } + createdAt() + customCoordinates() + customMetadata().ifPresent { it.validate() } + description() + fileId() + filePath() + fileType() + hasAlpha() + height() + isPrivateFile() + isPublished() + mime() + name() + size() + tags() + thumbnail() + type().ifPresent { it.validate() } + updatedAt() + url() + versionInfo().ifPresent { it.validate() } + width() + extensionStatus().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (aiTags.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + (if (createdAt.asKnown().isPresent) 1 else 0) + + (if (customCoordinates.asKnown().isPresent) 1 else 0) + + (customMetadata.asKnown().getOrNull()?.validity() ?: 0) + + (if (description.asKnown().isPresent) 1 else 0) + + (if (fileId.asKnown().isPresent) 1 else 0) + + (if (filePath.asKnown().isPresent) 1 else 0) + + (if (fileType.asKnown().isPresent) 1 else 0) + + (if (hasAlpha.asKnown().isPresent) 1 else 0) + + (if (height.asKnown().isPresent) 1 else 0) + + (if (isPrivateFile.asKnown().isPresent) 1 else 0) + + (if (isPublished.asKnown().isPresent) 1 else 0) + + (if (mime.asKnown().isPresent) 1 else 0) + + (if (name.asKnown().isPresent) 1 else 0) + + (if (size.asKnown().isPresent) 1 else 0) + + (tags.asKnown().getOrNull()?.size ?: 0) + + (if (thumbnail.asKnown().isPresent) 1 else 0) + + (type.asKnown().getOrNull()?.validity() ?: 0) + + (if (updatedAt.asKnown().isPresent) 1 else 0) + + (if (url.asKnown().isPresent) 1 else 0) + + (versionInfo.asKnown().getOrNull()?.validity() ?: 0) + + (if (width.asKnown().isPresent) 1 else 0) + + (extensionStatus.asKnown().getOrNull()?.validity() ?: 0) + + class ExtensionStatus + private constructor( + private val aiAutoDescription: JsonField, + private val awsAutoTagging: JsonField, + private val googleAutoTagging: JsonField, + private val removeBg: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("ai-auto-description") + @ExcludeMissing + aiAutoDescription: JsonField = JsonMissing.of(), + @JsonProperty("aws-auto-tagging") + @ExcludeMissing + awsAutoTagging: JsonField = JsonMissing.of(), + @JsonProperty("google-auto-tagging") + @ExcludeMissing + googleAutoTagging: JsonField = JsonMissing.of(), + @JsonProperty("remove-bg") + @ExcludeMissing + removeBg: JsonField = JsonMissing.of(), + ) : this(aiAutoDescription, awsAutoTagging, googleAutoTagging, removeBg, mutableMapOf()) + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun aiAutoDescription(): Optional = + aiAutoDescription.getOptional("ai-auto-description") + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun awsAutoTagging(): Optional = + awsAutoTagging.getOptional("aws-auto-tagging") + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun googleAutoTagging(): Optional = + googleAutoTagging.getOptional("google-auto-tagging") + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun removeBg(): Optional = removeBg.getOptional("remove-bg") + + /** + * Returns the raw JSON value of [aiAutoDescription]. + * + * Unlike [aiAutoDescription], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("ai-auto-description") + @ExcludeMissing + fun _aiAutoDescription(): JsonField = aiAutoDescription + + /** + * Returns the raw JSON value of [awsAutoTagging]. + * + * Unlike [awsAutoTagging], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("aws-auto-tagging") + @ExcludeMissing + fun _awsAutoTagging(): JsonField = awsAutoTagging + + /** + * Returns the raw JSON value of [googleAutoTagging]. + * + * Unlike [googleAutoTagging], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("google-auto-tagging") + @ExcludeMissing + fun _googleAutoTagging(): JsonField = googleAutoTagging + + /** + * Returns the raw JSON value of [removeBg]. + * + * Unlike [removeBg], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("remove-bg") @ExcludeMissing fun _removeBg(): JsonField = removeBg + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [ExtensionStatus]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ExtensionStatus]. */ + class Builder internal constructor() { + + private var aiAutoDescription: JsonField = JsonMissing.of() + private var awsAutoTagging: JsonField = JsonMissing.of() + private var googleAutoTagging: JsonField = JsonMissing.of() + private var removeBg: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(extensionStatus: ExtensionStatus) = apply { + aiAutoDescription = extensionStatus.aiAutoDescription + awsAutoTagging = extensionStatus.awsAutoTagging + googleAutoTagging = extensionStatus.googleAutoTagging + removeBg = extensionStatus.removeBg + additionalProperties = extensionStatus.additionalProperties.toMutableMap() + } + + fun aiAutoDescription(aiAutoDescription: AiAutoDescription) = + aiAutoDescription(JsonField.of(aiAutoDescription)) + + /** + * Sets [Builder.aiAutoDescription] to an arbitrary JSON value. + * + * You should usually call [Builder.aiAutoDescription] with a well-typed + * [AiAutoDescription] value instead. This method is primarily for setting the field to + * an undocumented or not yet supported value. + */ + fun aiAutoDescription(aiAutoDescription: JsonField) = apply { + this.aiAutoDescription = aiAutoDescription + } + + fun awsAutoTagging(awsAutoTagging: AwsAutoTagging) = + awsAutoTagging(JsonField.of(awsAutoTagging)) + + /** + * Sets [Builder.awsAutoTagging] to an arbitrary JSON value. + * + * You should usually call [Builder.awsAutoTagging] with a well-typed [AwsAutoTagging] + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun awsAutoTagging(awsAutoTagging: JsonField) = apply { + this.awsAutoTagging = awsAutoTagging + } + + fun googleAutoTagging(googleAutoTagging: GoogleAutoTagging) = + googleAutoTagging(JsonField.of(googleAutoTagging)) + + /** + * Sets [Builder.googleAutoTagging] to an arbitrary JSON value. + * + * You should usually call [Builder.googleAutoTagging] with a well-typed + * [GoogleAutoTagging] value instead. This method is primarily for setting the field to + * an undocumented or not yet supported value. + */ + fun googleAutoTagging(googleAutoTagging: JsonField) = apply { + this.googleAutoTagging = googleAutoTagging + } + + fun removeBg(removeBg: RemoveBg) = removeBg(JsonField.of(removeBg)) + + /** + * Sets [Builder.removeBg] to an arbitrary JSON value. + * + * You should usually call [Builder.removeBg] with a well-typed [RemoveBg] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun removeBg(removeBg: JsonField) = apply { this.removeBg = removeBg } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ExtensionStatus]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): ExtensionStatus = + ExtensionStatus( + aiAutoDescription, + awsAutoTagging, + googleAutoTagging, + removeBg, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): ExtensionStatus = apply { + if (validated) { + return@apply + } + + aiAutoDescription().ifPresent { it.validate() } + awsAutoTagging().ifPresent { it.validate() } + googleAutoTagging().ifPresent { it.validate() } + removeBg().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (aiAutoDescription.asKnown().getOrNull()?.validity() ?: 0) + + (awsAutoTagging.asKnown().getOrNull()?.validity() ?: 0) + + (googleAutoTagging.asKnown().getOrNull()?.validity() ?: 0) + + (removeBg.asKnown().getOrNull()?.validity() ?: 0) + + class AiAutoDescription + @JsonCreator + private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is + * on an older version than the API, then the API may respond with new members that the + * SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val SUCCESS = of("success") + + @JvmField val PENDING = of("pending") + + @JvmField val FAILED = of("failed") + + @JvmStatic fun of(value: String) = AiAutoDescription(JsonField.of(value)) + } + + /** An enum containing [AiAutoDescription]'s known values. */ + enum class Known { + SUCCESS, + PENDING, + FAILED, + } + + /** + * An enum containing [AiAutoDescription]'s known values, as well as an [_UNKNOWN] + * member. + * + * An instance of [AiAutoDescription] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if + * the SDK is on an older version than the API, then the API may respond with new + * members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + SUCCESS, + PENDING, + FAILED, + /** + * An enum member indicating that [AiAutoDescription] was instantiated with an + * unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you + * want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + SUCCESS -> Value.SUCCESS + PENDING -> Value.PENDING + FAILED -> Value.FAILED + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and + * don't want to throw for the unknown case. + * + * @throws ImageKitInvalidDataException if this class instance's value is a not a known + * member. + */ + fun known(): Known = + when (this) { + SUCCESS -> Known.SUCCESS + PENDING -> Known.PENDING + FAILED -> Known.FAILED + else -> throw ImageKitInvalidDataException("Unknown AiAutoDescription: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for + * debugging and generally doesn't throw. + * + * @throws ImageKitInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + ImageKitInvalidDataException("Value is not a String") + } + + private var validated: Boolean = false + + fun validate(): AiAutoDescription = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is AiAutoDescription && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + class AwsAutoTagging + @JsonCreator + private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is + * on an older version than the API, then the API may respond with new members that the + * SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val SUCCESS = of("success") + + @JvmField val PENDING = of("pending") + + @JvmField val FAILED = of("failed") + + @JvmStatic fun of(value: String) = AwsAutoTagging(JsonField.of(value)) + } + + /** An enum containing [AwsAutoTagging]'s known values. */ + enum class Known { + SUCCESS, + PENDING, + FAILED, + } + + /** + * An enum containing [AwsAutoTagging]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [AwsAutoTagging] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if + * the SDK is on an older version than the API, then the API may respond with new + * members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + SUCCESS, + PENDING, + FAILED, + /** + * An enum member indicating that [AwsAutoTagging] was instantiated with an unknown + * value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you + * want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + SUCCESS -> Value.SUCCESS + PENDING -> Value.PENDING + FAILED -> Value.FAILED + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and + * don't want to throw for the unknown case. + * + * @throws ImageKitInvalidDataException if this class instance's value is a not a known + * member. + */ + fun known(): Known = + when (this) { + SUCCESS -> Known.SUCCESS + PENDING -> Known.PENDING + FAILED -> Known.FAILED + else -> throw ImageKitInvalidDataException("Unknown AwsAutoTagging: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for + * debugging and generally doesn't throw. + * + * @throws ImageKitInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + ImageKitInvalidDataException("Value is not a String") + } + + private var validated: Boolean = false + + fun validate(): AwsAutoTagging = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is AwsAutoTagging && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + class GoogleAutoTagging + @JsonCreator + private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is + * on an older version than the API, then the API may respond with new members that the + * SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val SUCCESS = of("success") + + @JvmField val PENDING = of("pending") + + @JvmField val FAILED = of("failed") + + @JvmStatic fun of(value: String) = GoogleAutoTagging(JsonField.of(value)) + } + + /** An enum containing [GoogleAutoTagging]'s known values. */ + enum class Known { + SUCCESS, + PENDING, + FAILED, + } + + /** + * An enum containing [GoogleAutoTagging]'s known values, as well as an [_UNKNOWN] + * member. + * + * An instance of [GoogleAutoTagging] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if + * the SDK is on an older version than the API, then the API may respond with new + * members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + SUCCESS, + PENDING, + FAILED, + /** + * An enum member indicating that [GoogleAutoTagging] was instantiated with an + * unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you + * want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + SUCCESS -> Value.SUCCESS + PENDING -> Value.PENDING + FAILED -> Value.FAILED + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and + * don't want to throw for the unknown case. + * + * @throws ImageKitInvalidDataException if this class instance's value is a not a known + * member. + */ + fun known(): Known = + when (this) { + SUCCESS -> Known.SUCCESS + PENDING -> Known.PENDING + FAILED -> Known.FAILED + else -> throw ImageKitInvalidDataException("Unknown GoogleAutoTagging: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for + * debugging and generally doesn't throw. + * + * @throws ImageKitInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + ImageKitInvalidDataException("Value is not a String") + } + + private var validated: Boolean = false + + fun validate(): GoogleAutoTagging = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is GoogleAutoTagging && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + class RemoveBg @JsonCreator private constructor(private val value: JsonField) : + Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is + * on an older version than the API, then the API may respond with new members that the + * SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val SUCCESS = of("success") + + @JvmField val PENDING = of("pending") + + @JvmField val FAILED = of("failed") + + @JvmStatic fun of(value: String) = RemoveBg(JsonField.of(value)) + } + + /** An enum containing [RemoveBg]'s known values. */ + enum class Known { + SUCCESS, + PENDING, + FAILED, + } + + /** + * An enum containing [RemoveBg]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [RemoveBg] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if + * the SDK is on an older version than the API, then the API may respond with new + * members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + SUCCESS, + PENDING, + FAILED, + /** + * An enum member indicating that [RemoveBg] was instantiated with an unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you + * want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + SUCCESS -> Value.SUCCESS + PENDING -> Value.PENDING + FAILED -> Value.FAILED + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and + * don't want to throw for the unknown case. + * + * @throws ImageKitInvalidDataException if this class instance's value is a not a known + * member. + */ + fun known(): Known = + when (this) { + SUCCESS -> Known.SUCCESS + PENDING -> Known.PENDING + FAILED -> Known.FAILED + else -> throw ImageKitInvalidDataException("Unknown RemoveBg: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for + * debugging and generally doesn't throw. + * + * @throws ImageKitInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + ImageKitInvalidDataException("Value is not a String") + } + + private var validated: Boolean = false + + fun validate(): RemoveBg = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is RemoveBg && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ExtensionStatus && + aiAutoDescription == other.aiAutoDescription && + awsAutoTagging == other.awsAutoTagging && + googleAutoTagging == other.googleAutoTagging && + removeBg == other.removeBg && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + aiAutoDescription, + awsAutoTagging, + googleAutoTagging, + removeBg, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ExtensionStatus{aiAutoDescription=$aiAutoDescription, awsAutoTagging=$awsAutoTagging, googleAutoTagging=$googleAutoTagging, removeBg=$removeBg, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is FileUpdateResponse && + aiTags == other.aiTags && + createdAt == other.createdAt && + customCoordinates == other.customCoordinates && + customMetadata == other.customMetadata && + description == other.description && + fileId == other.fileId && + filePath == other.filePath && + fileType == other.fileType && + hasAlpha == other.hasAlpha && + height == other.height && + isPrivateFile == other.isPrivateFile && + isPublished == other.isPublished && + mime == other.mime && + name == other.name && + size == other.size && + tags == other.tags && + thumbnail == other.thumbnail && + type == other.type && + updatedAt == other.updatedAt && + url == other.url && + versionInfo == other.versionInfo && + width == other.width && + extensionStatus == other.extensionStatus && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + aiTags, + createdAt, + customCoordinates, + customMetadata, + description, + fileId, + filePath, + fileType, + hasAlpha, + height, + isPrivateFile, + isPublished, + mime, + name, + size, + tags, + thumbnail, + type, + updatedAt, + url, + versionInfo, + width, + extensionStatus, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "FileUpdateResponse{aiTags=$aiTags, createdAt=$createdAt, customCoordinates=$customCoordinates, customMetadata=$customMetadata, description=$description, fileId=$fileId, filePath=$filePath, fileType=$fileType, hasAlpha=$hasAlpha, height=$height, isPrivateFile=$isPrivateFile, isPublished=$isPublished, mime=$mime, name=$name, size=$size, tags=$tags, thumbnail=$thumbnail, type=$type, updatedAt=$updatedAt, url=$url, versionInfo=$versionInfo, width=$width, extensionStatus=$extensionStatus, additionalProperties=$additionalProperties}" +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/files/FileUploadParams.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/files/FileUploadParams.kt new file mode 100644 index 0000000..5306b66 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/files/FileUploadParams.kt @@ -0,0 +1,5211 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.files + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.fasterxml.jackson.core.JsonGenerator +import com.fasterxml.jackson.core.ObjectCodec +import com.fasterxml.jackson.databind.JsonNode +import com.fasterxml.jackson.databind.SerializerProvider +import com.fasterxml.jackson.databind.annotation.JsonDeserialize +import com.fasterxml.jackson.databind.annotation.JsonSerialize +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.imagekit.api.core.BaseDeserializer +import com.imagekit.api.core.BaseSerializer +import com.imagekit.api.core.Enum +import com.imagekit.api.core.ExcludeMissing +import com.imagekit.api.core.JsonField +import com.imagekit.api.core.JsonMissing +import com.imagekit.api.core.JsonValue +import com.imagekit.api.core.MultipartField +import com.imagekit.api.core.Params +import com.imagekit.api.core.checkKnown +import com.imagekit.api.core.checkRequired +import com.imagekit.api.core.getOrThrow +import com.imagekit.api.core.http.Headers +import com.imagekit.api.core.http.QueryParams +import com.imagekit.api.core.toImmutable +import com.imagekit.api.errors.ImageKitInvalidDataException +import com.imagekit.api.models.UnnamedSchemaWithArrayParent3 +import java.io.InputStream +import java.nio.file.Path +import java.util.Collections +import java.util.Objects +import java.util.Optional +import kotlin.io.path.inputStream +import kotlin.io.path.name +import kotlin.jvm.optionals.getOrNull + +/** + * ImageKit.io allows you to upload files directly from both the server and client sides. For + * server-side uploads, private API key authentication is used. For client-side uploads, generate a + * one-time `token`, `signature`, and `expire` from your secure backend using private API. + * [Learn more](/docs/api-reference/upload-file/upload-file#how-to-implement-client-side-file-upload) + * about how to implement client-side file upload. + * + * The [V2 API](/docs/api-reference/upload-file/upload-file-v2) enhances security by verifying the + * entire payload using JWT. + * + * **File size limit** \ On the free plan, the maximum upload file sizes are 20MB for images, audio, + * and raw files and 100MB for videos. On the paid plan, these limits increase to 40MB for images, + * audio, and raw files and 2GB for videos. These limits can be further increased with higher-tier + * plans. + * + * **Version limit** \ A file can have a maximum of 100 versions. + * + * **Demo applications** + * - A full-fledged [upload widget using Uppy](https://github.com/imagekit-samples/uppy-uploader), + * supporting file selections from local storage, URL, Dropbox, Google Drive, Instagram, and more. + * - [Quick start guides](/docs/quick-start-guides) for various frameworks and technologies. + */ +class FileUploadParams +private constructor( + private val body: Body, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** + * The API accepts any of the following: + * - **Binary data** – send the raw bytes as `multipart/form-data`. + * - **HTTP / HTTPS URL** – a publicly reachable URL that ImageKit’s servers can fetch. + * - **Base64 string** – the file encoded as a Base64 data URI or plain Base64. + * + * When supplying a URL, the server must receive the response headers within 8 seconds; + * otherwise the request fails with 400 Bad Request. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun file(): InputStream = body.file() + + /** + * The name with which the file has to be uploaded. The file name can contain: + * - Alphanumeric Characters: `a-z`, `A-Z`, `0-9`. + * - Special Characters: `.`, `-` + * + * Any other character including space will be replaced by `_` + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun fileName(): String = body.fileName() + + /** + * A unique value that the ImageKit.io server will use to recognize and prevent subsequent + * retries for the same request. We suggest using V4 UUIDs, or another random string with enough + * entropy to avoid collisions. This field is only required for authentication when uploading a + * file from the client side. + * + * **Note**: Sending a value that has been used in the past will result in a validation error. + * Even if your previous request resulted in an error, you should always send a new value for + * this field. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun token(): Optional = body.token() + + /** + * Server-side checks to run on the asset. Read more about + * [Upload API checks](/docs/api-reference/upload-file/upload-file#upload-api-checks). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun checks(): Optional = body.checks() + + /** + * Define an important area in the image. This is only relevant for image type files. + * - To be passed as a string with the x and y coordinates of the top-left corner, and width and + * height of the area of interest in the format `x,y,width,height`. For example - + * `10,10,100,100` + * - Can be used with fo-customtransformation. + * - If this field is not specified and the file is overwritten, then customCoordinates will be + * removed. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun customCoordinates(): Optional = body.customCoordinates() + + /** + * JSON key-value pairs to associate with the asset. Create the custom metadata fields before + * setting these values. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun customMetadata(): Optional = body.customMetadata() + + /** + * Optional text to describe the contents of the file. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun description(): Optional = body.description() + + /** + * The time until your signature is valid. It must be a + * [Unix time](https://en.wikipedia.org/wiki/Unix_time) in less than 1 hour into the future. It + * should be in seconds. This field is only required for authentication when uploading a file + * from the client side. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun expire(): Optional = body.expire() + + /** + * Array of extensions to be applied to the asset. Each extension can be configured with + * specific parameters based on the extension type. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun extensions(): Optional> = body.extensions() + + /** + * The folder path in which the image has to be uploaded. If the folder(s) didn't exist before, + * a new folder(s) is created. + * + * The folder name can contain: + * - Alphanumeric Characters: `a-z` , `A-Z` , `0-9` + * - Special Characters: `/` , `_` , `-` + * + * Using multiple `/` creates a nested folder. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun folder(): Optional = body.folder() + + /** + * Whether to mark the file as private or not. + * + * If `true`, the file is marked as private and is accessible only using named transformation or + * signed URL. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun isPrivateFile(): Optional = body.isPrivateFile() + + /** + * Whether to upload file as published or not. + * + * If `false`, the file is marked as unpublished, which restricts access to the file only via + * the media library. Files in draft or unpublished state can only be publicly accessed after + * being published. + * + * The option to upload in draft state is only available in custom enterprise pricing plans. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun isPublished(): Optional = body.isPublished() + + /** + * If set to `true` and a file already exists at the exact location, its AITags will be removed. + * Set `overwriteAITags` to `false` to preserve AITags. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun overwriteAiTags(): Optional = body.overwriteAiTags() + + /** + * If the request does not have `customMetadata`, and a file already exists at the exact + * location, existing customMetadata will be removed. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun overwriteCustomMetadata(): Optional = body.overwriteCustomMetadata() + + /** + * If `false` and `useUniqueFileName` is also `false`, and a file already exists at the exact + * location, upload API will return an error immediately. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun overwriteFile(): Optional = body.overwriteFile() + + /** + * If the request does not have `tags`, and a file already exists at the exact location, + * existing tags will be removed. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun overwriteTags(): Optional = body.overwriteTags() + + /** + * Your ImageKit.io public key. This field is only required for authentication when uploading a + * file from the client side. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun publicKey(): Optional = body.publicKey() + + /** + * Array of response field keys to include in the API response body. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun responseFields(): Optional> = body.responseFields() + + /** + * HMAC-SHA1 digest of the token+expire using your ImageKit.io private API key as a key. Learn + * how to create a signature on the page below. This should be in lowercase. + * + * Signature must be calculated on the server-side. This field is only required for + * authentication when uploading a file from the client side. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun signature(): Optional = body.signature() + + /** + * Set the tags while uploading the file. Provide an array of tag strings (e.g. `["tag1", + * "tag2", "tag3"]`). The combined length of all tag characters must not exceed 500, and the `%` + * character is not allowed. If this field is not specified and the file is overwritten, the + * existing tags will be removed. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun tags(): Optional> = body.tags() + + /** + * Configure pre-processing (`pre`) and post-processing (`post`) transformations. + * - `pre` — applied before the file is uploaded to the Media Library. Useful for reducing file + * size or applying basic optimizations upfront (e.g., resize, compress). + * - `post` — applied immediately after upload. Ideal for generating transformed versions (like + * video encodes or thumbnails) in advance, so they're ready for delivery without delay. + * + * You can mix and match any combination of post-processing types. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun transformation(): Optional = body.transformation() + + /** + * Whether to use a unique filename for this file or not. + * + * If `true`, ImageKit.io will add a unique suffix to the filename parameter to get a unique + * filename. + * + * If `false`, then the image is uploaded with the provided filename parameter, and any existing + * file with the same name is replaced. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun useUniqueFileName(): Optional = body.useUniqueFileName() + + /** + * The final status of extensions after they have completed execution will be delivered to this + * endpoint as a POST request. + * [Learn more](/docs/api-reference/digital-asset-management-dam/managing-assets/update-file-details#webhook-payload-structure) + * about the webhook payload structure. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun webhookUrl(): Optional = body.webhookUrl() + + /** + * Returns the raw multipart value of [file]. + * + * Unlike [file], this method doesn't throw if the multipart field has an unexpected type. + */ + fun _file(): MultipartField = body._file() + + /** + * Returns the raw multipart value of [fileName]. + * + * Unlike [fileName], this method doesn't throw if the multipart field has an unexpected type. + */ + fun _fileName(): MultipartField = body._fileName() + + /** + * Returns the raw multipart value of [token]. + * + * Unlike [token], this method doesn't throw if the multipart field has an unexpected type. + */ + fun _token(): MultipartField = body._token() + + /** + * Returns the raw multipart value of [checks]. + * + * Unlike [checks], this method doesn't throw if the multipart field has an unexpected type. + */ + fun _checks(): MultipartField = body._checks() + + /** + * Returns the raw multipart value of [customCoordinates]. + * + * Unlike [customCoordinates], this method doesn't throw if the multipart field has an + * unexpected type. + */ + fun _customCoordinates(): MultipartField = body._customCoordinates() + + /** + * Returns the raw multipart value of [customMetadata]. + * + * Unlike [customMetadata], this method doesn't throw if the multipart field has an unexpected + * type. + */ + fun _customMetadata(): MultipartField = body._customMetadata() + + /** + * Returns the raw multipart value of [description]. + * + * Unlike [description], this method doesn't throw if the multipart field has an unexpected + * type. + */ + fun _description(): MultipartField = body._description() + + /** + * Returns the raw multipart value of [expire]. + * + * Unlike [expire], this method doesn't throw if the multipart field has an unexpected type. + */ + fun _expire(): MultipartField = body._expire() + + /** + * Returns the raw multipart value of [extensions]. + * + * Unlike [extensions], this method doesn't throw if the multipart field has an unexpected type. + */ + fun _extensions(): MultipartField> = body._extensions() + + /** + * Returns the raw multipart value of [folder]. + * + * Unlike [folder], this method doesn't throw if the multipart field has an unexpected type. + */ + fun _folder(): MultipartField = body._folder() + + /** + * Returns the raw multipart value of [isPrivateFile]. + * + * Unlike [isPrivateFile], this method doesn't throw if the multipart field has an unexpected + * type. + */ + fun _isPrivateFile(): MultipartField = body._isPrivateFile() + + /** + * Returns the raw multipart value of [isPublished]. + * + * Unlike [isPublished], this method doesn't throw if the multipart field has an unexpected + * type. + */ + fun _isPublished(): MultipartField = body._isPublished() + + /** + * Returns the raw multipart value of [overwriteAiTags]. + * + * Unlike [overwriteAiTags], this method doesn't throw if the multipart field has an unexpected + * type. + */ + fun _overwriteAiTags(): MultipartField = body._overwriteAiTags() + + /** + * Returns the raw multipart value of [overwriteCustomMetadata]. + * + * Unlike [overwriteCustomMetadata], this method doesn't throw if the multipart field has an + * unexpected type. + */ + fun _overwriteCustomMetadata(): MultipartField = body._overwriteCustomMetadata() + + /** + * Returns the raw multipart value of [overwriteFile]. + * + * Unlike [overwriteFile], this method doesn't throw if the multipart field has an unexpected + * type. + */ + fun _overwriteFile(): MultipartField = body._overwriteFile() + + /** + * Returns the raw multipart value of [overwriteTags]. + * + * Unlike [overwriteTags], this method doesn't throw if the multipart field has an unexpected + * type. + */ + fun _overwriteTags(): MultipartField = body._overwriteTags() + + /** + * Returns the raw multipart value of [publicKey]. + * + * Unlike [publicKey], this method doesn't throw if the multipart field has an unexpected type. + */ + fun _publicKey(): MultipartField = body._publicKey() + + /** + * Returns the raw multipart value of [responseFields]. + * + * Unlike [responseFields], this method doesn't throw if the multipart field has an unexpected + * type. + */ + fun _responseFields(): MultipartField> = body._responseFields() + + /** + * Returns the raw multipart value of [signature]. + * + * Unlike [signature], this method doesn't throw if the multipart field has an unexpected type. + */ + fun _signature(): MultipartField = body._signature() + + /** + * Returns the raw multipart value of [tags]. + * + * Unlike [tags], this method doesn't throw if the multipart field has an unexpected type. + */ + fun _tags(): MultipartField> = body._tags() + + /** + * Returns the raw multipart value of [transformation]. + * + * Unlike [transformation], this method doesn't throw if the multipart field has an unexpected + * type. + */ + fun _transformation(): MultipartField = body._transformation() + + /** + * Returns the raw multipart value of [useUniqueFileName]. + * + * Unlike [useUniqueFileName], this method doesn't throw if the multipart field has an + * unexpected type. + */ + fun _useUniqueFileName(): MultipartField = body._useUniqueFileName() + + /** + * Returns the raw multipart value of [webhookUrl]. + * + * Unlike [webhookUrl], this method doesn't throw if the multipart field has an unexpected type. + */ + fun _webhookUrl(): MultipartField = body._webhookUrl() + + fun _additionalBodyProperties(): Map = body._additionalProperties() + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [FileUploadParams]. + * + * The following fields are required: + * ```java + * .file() + * .fileName() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [FileUploadParams]. */ + class Builder internal constructor() { + + private var body: Body.Builder = Body.builder() + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + + @JvmSynthetic + internal fun from(fileUploadParams: FileUploadParams) = apply { + body = fileUploadParams.body.toBuilder() + additionalHeaders = fileUploadParams.additionalHeaders.toBuilder() + additionalQueryParams = fileUploadParams.additionalQueryParams.toBuilder() + } + + /** + * Sets the entire request body. + * + * This is generally only useful if you are already constructing the body separately. + * Otherwise, it's more convenient to use the top-level setters instead: + * - [file] + * - [fileName] + * - [token] + * - [checks] + * - [customCoordinates] + * - etc. + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } + + /** + * The API accepts any of the following: + * - **Binary data** – send the raw bytes as `multipart/form-data`. + * - **HTTP / HTTPS URL** – a publicly reachable URL that ImageKit’s servers can fetch. + * - **Base64 string** – the file encoded as a Base64 data URI or plain Base64. + * + * When supplying a URL, the server must receive the response headers within 8 seconds; + * otherwise the request fails with 400 Bad Request. + */ + fun file(file: InputStream) = apply { body.file(file) } + + /** + * Sets [Builder.file] to an arbitrary multipart value. + * + * You should usually call [Builder.file] with a well-typed [InputStream] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun file(file: MultipartField) = apply { body.file(file) } + + /** + * The API accepts any of the following: + * - **Binary data** – send the raw bytes as `multipart/form-data`. + * - **HTTP / HTTPS URL** – a publicly reachable URL that ImageKit’s servers can fetch. + * - **Base64 string** – the file encoded as a Base64 data URI or plain Base64. + * + * When supplying a URL, the server must receive the response headers within 8 seconds; + * otherwise the request fails with 400 Bad Request. + */ + fun file(file: ByteArray) = apply { body.file(file) } + + /** + * The API accepts any of the following: + * - **Binary data** – send the raw bytes as `multipart/form-data`. + * - **HTTP / HTTPS URL** – a publicly reachable URL that ImageKit’s servers can fetch. + * - **Base64 string** – the file encoded as a Base64 data URI or plain Base64. + * + * When supplying a URL, the server must receive the response headers within 8 seconds; + * otherwise the request fails with 400 Bad Request. + */ + fun file(path: Path) = apply { body.file(path) } + + /** + * The name with which the file has to be uploaded. The file name can contain: + * - Alphanumeric Characters: `a-z`, `A-Z`, `0-9`. + * - Special Characters: `.`, `-` + * + * Any other character including space will be replaced by `_` + */ + fun fileName(fileName: String) = apply { body.fileName(fileName) } + + /** + * Sets [Builder.fileName] to an arbitrary multipart value. + * + * You should usually call [Builder.fileName] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun fileName(fileName: MultipartField) = apply { body.fileName(fileName) } + + /** + * A unique value that the ImageKit.io server will use to recognize and prevent subsequent + * retries for the same request. We suggest using V4 UUIDs, or another random string with + * enough entropy to avoid collisions. This field is only required for authentication when + * uploading a file from the client side. + * + * **Note**: Sending a value that has been used in the past will result in a validation + * error. Even if your previous request resulted in an error, you should always send a new + * value for this field. + */ + fun token(token: String) = apply { body.token(token) } + + /** + * Sets [Builder.token] to an arbitrary multipart value. + * + * You should usually call [Builder.token] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun token(token: MultipartField) = apply { body.token(token) } + + /** + * Server-side checks to run on the asset. Read more about + * [Upload API checks](/docs/api-reference/upload-file/upload-file#upload-api-checks). + */ + fun checks(checks: String) = apply { body.checks(checks) } + + /** + * Sets [Builder.checks] to an arbitrary multipart value. + * + * You should usually call [Builder.checks] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun checks(checks: MultipartField) = apply { body.checks(checks) } + + /** + * Define an important area in the image. This is only relevant for image type files. + * - To be passed as a string with the x and y coordinates of the top-left corner, and width + * and height of the area of interest in the format `x,y,width,height`. For example - + * `10,10,100,100` + * - Can be used with fo-customtransformation. + * - If this field is not specified and the file is overwritten, then customCoordinates will + * be removed. + */ + fun customCoordinates(customCoordinates: String) = apply { + body.customCoordinates(customCoordinates) + } + + /** + * Sets [Builder.customCoordinates] to an arbitrary multipart value. + * + * You should usually call [Builder.customCoordinates] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun customCoordinates(customCoordinates: MultipartField) = apply { + body.customCoordinates(customCoordinates) + } + + /** + * JSON key-value pairs to associate with the asset. Create the custom metadata fields + * before setting these values. + */ + fun customMetadata(customMetadata: CustomMetadata) = apply { + body.customMetadata(customMetadata) + } + + /** + * Sets [Builder.customMetadata] to an arbitrary multipart value. + * + * You should usually call [Builder.customMetadata] with a well-typed [CustomMetadata] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun customMetadata(customMetadata: MultipartField) = apply { + body.customMetadata(customMetadata) + } + + /** Optional text to describe the contents of the file. */ + fun description(description: String) = apply { body.description(description) } + + /** + * Sets [Builder.description] to an arbitrary multipart value. + * + * You should usually call [Builder.description] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun description(description: MultipartField) = apply { + body.description(description) + } + + /** + * The time until your signature is valid. It must be a + * [Unix time](https://en.wikipedia.org/wiki/Unix_time) in less than 1 hour into the future. + * It should be in seconds. This field is only required for authentication when uploading a + * file from the client side. + */ + fun expire(expire: Long) = apply { body.expire(expire) } + + /** + * Sets [Builder.expire] to an arbitrary multipart value. + * + * You should usually call [Builder.expire] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun expire(expire: MultipartField) = apply { body.expire(expire) } + + /** + * Array of extensions to be applied to the asset. Each extension can be configured with + * specific parameters based on the extension type. + */ + fun extensions(extensions: List) = apply { + body.extensions(extensions) + } + + /** + * Sets [Builder.extensions] to an arbitrary multipart value. + * + * You should usually call [Builder.extensions] with a well-typed + * `List` value instead. This method is primarily for setting + * the field to an undocumented or not yet supported value. + */ + fun extensions(extensions: MultipartField>) = apply { + body.extensions(extensions) + } + + /** + * Adds a single [UnnamedSchemaWithArrayParent3] to [extensions]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addExtension(extension: UnnamedSchemaWithArrayParent3) = apply { + body.addExtension(extension) + } + + /** + * Alias for calling [addExtension] with + * `UnnamedSchemaWithArrayParent3.ofRemoveBg(removeBg)`. + */ + fun addExtension(removeBg: UnnamedSchemaWithArrayParent3.RemoveBg) = apply { + body.addExtension(removeBg) + } + + /** + * Alias for calling [addExtension] with + * `UnnamedSchemaWithArrayParent3.ofAutoTaggingExtension(autoTaggingExtension)`. + */ + fun addExtension(autoTaggingExtension: UnnamedSchemaWithArrayParent3.AutoTaggingExtension) = + apply { + body.addExtension(autoTaggingExtension) + } + + /** + * Alias for calling [addExtension] with + * `UnnamedSchemaWithArrayParent3.ofAiAutoDescription()`. + */ + fun addExtensionAiAutoDescription() = apply { body.addExtensionAiAutoDescription() } + + /** + * The folder path in which the image has to be uploaded. If the folder(s) didn't exist + * before, a new folder(s) is created. + * + * The folder name can contain: + * - Alphanumeric Characters: `a-z` , `A-Z` , `0-9` + * - Special Characters: `/` , `_` , `-` + * + * Using multiple `/` creates a nested folder. + */ + fun folder(folder: String) = apply { body.folder(folder) } + + /** + * Sets [Builder.folder] to an arbitrary multipart value. + * + * You should usually call [Builder.folder] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun folder(folder: MultipartField) = apply { body.folder(folder) } + + /** + * Whether to mark the file as private or not. + * + * If `true`, the file is marked as private and is accessible only using named + * transformation or signed URL. + */ + fun isPrivateFile(isPrivateFile: Boolean) = apply { body.isPrivateFile(isPrivateFile) } + + /** + * Sets [Builder.isPrivateFile] to an arbitrary multipart value. + * + * You should usually call [Builder.isPrivateFile] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun isPrivateFile(isPrivateFile: MultipartField) = apply { + body.isPrivateFile(isPrivateFile) + } + + /** + * Whether to upload file as published or not. + * + * If `false`, the file is marked as unpublished, which restricts access to the file only + * via the media library. Files in draft or unpublished state can only be publicly accessed + * after being published. + * + * The option to upload in draft state is only available in custom enterprise pricing plans. + */ + fun isPublished(isPublished: Boolean) = apply { body.isPublished(isPublished) } + + /** + * Sets [Builder.isPublished] to an arbitrary multipart value. + * + * You should usually call [Builder.isPublished] with a well-typed [Boolean] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun isPublished(isPublished: MultipartField) = apply { + body.isPublished(isPublished) + } + + /** + * If set to `true` and a file already exists at the exact location, its AITags will be + * removed. Set `overwriteAITags` to `false` to preserve AITags. + */ + fun overwriteAiTags(overwriteAiTags: Boolean) = apply { + body.overwriteAiTags(overwriteAiTags) + } + + /** + * Sets [Builder.overwriteAiTags] to an arbitrary multipart value. + * + * You should usually call [Builder.overwriteAiTags] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun overwriteAiTags(overwriteAiTags: MultipartField) = apply { + body.overwriteAiTags(overwriteAiTags) + } + + /** + * If the request does not have `customMetadata`, and a file already exists at the exact + * location, existing customMetadata will be removed. + */ + fun overwriteCustomMetadata(overwriteCustomMetadata: Boolean) = apply { + body.overwriteCustomMetadata(overwriteCustomMetadata) + } + + /** + * Sets [Builder.overwriteCustomMetadata] to an arbitrary multipart value. + * + * You should usually call [Builder.overwriteCustomMetadata] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun overwriteCustomMetadata(overwriteCustomMetadata: MultipartField) = apply { + body.overwriteCustomMetadata(overwriteCustomMetadata) + } + + /** + * If `false` and `useUniqueFileName` is also `false`, and a file already exists at the + * exact location, upload API will return an error immediately. + */ + fun overwriteFile(overwriteFile: Boolean) = apply { body.overwriteFile(overwriteFile) } + + /** + * Sets [Builder.overwriteFile] to an arbitrary multipart value. + * + * You should usually call [Builder.overwriteFile] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun overwriteFile(overwriteFile: MultipartField) = apply { + body.overwriteFile(overwriteFile) + } + + /** + * If the request does not have `tags`, and a file already exists at the exact location, + * existing tags will be removed. + */ + fun overwriteTags(overwriteTags: Boolean) = apply { body.overwriteTags(overwriteTags) } + + /** + * Sets [Builder.overwriteTags] to an arbitrary multipart value. + * + * You should usually call [Builder.overwriteTags] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun overwriteTags(overwriteTags: MultipartField) = apply { + body.overwriteTags(overwriteTags) + } + + /** + * Your ImageKit.io public key. This field is only required for authentication when + * uploading a file from the client side. + */ + fun publicKey(publicKey: String) = apply { body.publicKey(publicKey) } + + /** + * Sets [Builder.publicKey] to an arbitrary multipart value. + * + * You should usually call [Builder.publicKey] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun publicKey(publicKey: MultipartField) = apply { body.publicKey(publicKey) } + + /** Array of response field keys to include in the API response body. */ + fun responseFields(responseFields: List) = apply { + body.responseFields(responseFields) + } + + /** + * Sets [Builder.responseFields] to an arbitrary multipart value. + * + * You should usually call [Builder.responseFields] with a well-typed `List` + * value instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun responseFields(responseFields: MultipartField>) = apply { + body.responseFields(responseFields) + } + + /** + * Adds a single [ResponseField] to [responseFields]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addResponseField(responseField: ResponseField) = apply { + body.addResponseField(responseField) + } + + /** + * HMAC-SHA1 digest of the token+expire using your ImageKit.io private API key as a key. + * Learn how to create a signature on the page below. This should be in lowercase. + * + * Signature must be calculated on the server-side. This field is only required for + * authentication when uploading a file from the client side. + */ + fun signature(signature: String) = apply { body.signature(signature) } + + /** + * Sets [Builder.signature] to an arbitrary multipart value. + * + * You should usually call [Builder.signature] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun signature(signature: MultipartField) = apply { body.signature(signature) } + + /** + * Set the tags while uploading the file. Provide an array of tag strings (e.g. `["tag1", + * "tag2", "tag3"]`). The combined length of all tag characters must not exceed 500, and the + * `%` character is not allowed. If this field is not specified and the file is overwritten, + * the existing tags will be removed. + */ + fun tags(tags: List) = apply { body.tags(tags) } + + /** + * Sets [Builder.tags] to an arbitrary multipart value. + * + * You should usually call [Builder.tags] with a well-typed `List` value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun tags(tags: MultipartField>) = apply { body.tags(tags) } + + /** + * Adds a single [String] to [tags]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addTag(tag: String) = apply { body.addTag(tag) } + + /** + * Configure pre-processing (`pre`) and post-processing (`post`) transformations. + * - `pre` — applied before the file is uploaded to the Media Library. Useful for reducing + * file size or applying basic optimizations upfront (e.g., resize, compress). + * - `post` — applied immediately after upload. Ideal for generating transformed versions + * (like video encodes or thumbnails) in advance, so they're ready for delivery without + * delay. + * + * You can mix and match any combination of post-processing types. + */ + fun transformation(transformation: Transformation) = apply { + body.transformation(transformation) + } + + /** + * Sets [Builder.transformation] to an arbitrary multipart value. + * + * You should usually call [Builder.transformation] with a well-typed [Transformation] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun transformation(transformation: MultipartField) = apply { + body.transformation(transformation) + } + + /** + * Whether to use a unique filename for this file or not. + * + * If `true`, ImageKit.io will add a unique suffix to the filename parameter to get a unique + * filename. + * + * If `false`, then the image is uploaded with the provided filename parameter, and any + * existing file with the same name is replaced. + */ + fun useUniqueFileName(useUniqueFileName: Boolean) = apply { + body.useUniqueFileName(useUniqueFileName) + } + + /** + * Sets [Builder.useUniqueFileName] to an arbitrary multipart value. + * + * You should usually call [Builder.useUniqueFileName] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun useUniqueFileName(useUniqueFileName: MultipartField) = apply { + body.useUniqueFileName(useUniqueFileName) + } + + /** + * The final status of extensions after they have completed execution will be delivered to + * this endpoint as a POST request. + * [Learn more](/docs/api-reference/digital-asset-management-dam/managing-assets/update-file-details#webhook-payload-structure) + * about the webhook payload structure. + */ + fun webhookUrl(webhookUrl: String) = apply { body.webhookUrl(webhookUrl) } + + /** + * Sets [Builder.webhookUrl] to an arbitrary multipart value. + * + * You should usually call [Builder.webhookUrl] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun webhookUrl(webhookUrl: MultipartField) = apply { body.webhookUrl(webhookUrl) } + + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + body.additionalProperties(additionalBodyProperties) + } + + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + body.putAdditionalProperty(key, value) + } + + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + body.putAllAdditionalProperties(additionalBodyProperties) + } + + fun removeAdditionalBodyProperty(key: String) = apply { body.removeAdditionalProperty(key) } + + fun removeAllAdditionalBodyProperties(keys: Set) = apply { + body.removeAllAdditionalProperties(keys) + } + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + /** + * Returns an immutable instance of [FileUploadParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .file() + * .fileName() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): FileUploadParams = + FileUploadParams(body.build(), additionalHeaders.build(), additionalQueryParams.build()) + } + + fun _body(): Map> = + (mapOf( + "file" to _file(), + "fileName" to _fileName(), + "token" to _token(), + "checks" to _checks(), + "customCoordinates" to _customCoordinates(), + "customMetadata" to _customMetadata(), + "description" to _description(), + "expire" to _expire(), + "extensions" to _extensions(), + "folder" to _folder(), + "isPrivateFile" to _isPrivateFile(), + "isPublished" to _isPublished(), + "overwriteAITags" to _overwriteAiTags(), + "overwriteCustomMetadata" to _overwriteCustomMetadata(), + "overwriteFile" to _overwriteFile(), + "overwriteTags" to _overwriteTags(), + "publicKey" to _publicKey(), + "responseFields" to _responseFields(), + "signature" to _signature(), + "tags" to _tags(), + "transformation" to _transformation(), + "useUniqueFileName" to _useUniqueFileName(), + "webhookUrl" to _webhookUrl(), + ) + _additionalBodyProperties().mapValues { (_, value) -> MultipartField.of(value) }) + .toImmutable() + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + class Body + private constructor( + private val file: MultipartField, + private val fileName: MultipartField, + private val token: MultipartField, + private val checks: MultipartField, + private val customCoordinates: MultipartField, + private val customMetadata: MultipartField, + private val description: MultipartField, + private val expire: MultipartField, + private val extensions: MultipartField>, + private val folder: MultipartField, + private val isPrivateFile: MultipartField, + private val isPublished: MultipartField, + private val overwriteAiTags: MultipartField, + private val overwriteCustomMetadata: MultipartField, + private val overwriteFile: MultipartField, + private val overwriteTags: MultipartField, + private val publicKey: MultipartField, + private val responseFields: MultipartField>, + private val signature: MultipartField, + private val tags: MultipartField>, + private val transformation: MultipartField, + private val useUniqueFileName: MultipartField, + private val webhookUrl: MultipartField, + private val additionalProperties: MutableMap, + ) { + + /** + * The API accepts any of the following: + * - **Binary data** – send the raw bytes as `multipart/form-data`. + * - **HTTP / HTTPS URL** – a publicly reachable URL that ImageKit’s servers can fetch. + * - **Base64 string** – the file encoded as a Base64 data URI or plain Base64. + * + * When supplying a URL, the server must receive the response headers within 8 seconds; + * otherwise the request fails with 400 Bad Request. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun file(): InputStream = file.value.getRequired("file") + + /** + * The name with which the file has to be uploaded. The file name can contain: + * - Alphanumeric Characters: `a-z`, `A-Z`, `0-9`. + * - Special Characters: `.`, `-` + * + * Any other character including space will be replaced by `_` + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun fileName(): String = fileName.value.getRequired("fileName") + + /** + * A unique value that the ImageKit.io server will use to recognize and prevent subsequent + * retries for the same request. We suggest using V4 UUIDs, or another random string with + * enough entropy to avoid collisions. This field is only required for authentication when + * uploading a file from the client side. + * + * **Note**: Sending a value that has been used in the past will result in a validation + * error. Even if your previous request resulted in an error, you should always send a new + * value for this field. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun token(): Optional = token.value.getOptional("token") + + /** + * Server-side checks to run on the asset. Read more about + * [Upload API checks](/docs/api-reference/upload-file/upload-file#upload-api-checks). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun checks(): Optional = checks.value.getOptional("checks") + + /** + * Define an important area in the image. This is only relevant for image type files. + * - To be passed as a string with the x and y coordinates of the top-left corner, and width + * and height of the area of interest in the format `x,y,width,height`. For example - + * `10,10,100,100` + * - Can be used with fo-customtransformation. + * - If this field is not specified and the file is overwritten, then customCoordinates will + * be removed. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun customCoordinates(): Optional = + customCoordinates.value.getOptional("customCoordinates") + + /** + * JSON key-value pairs to associate with the asset. Create the custom metadata fields + * before setting these values. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun customMetadata(): Optional = + customMetadata.value.getOptional("customMetadata") + + /** + * Optional text to describe the contents of the file. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun description(): Optional = description.value.getOptional("description") + + /** + * The time until your signature is valid. It must be a + * [Unix time](https://en.wikipedia.org/wiki/Unix_time) in less than 1 hour into the future. + * It should be in seconds. This field is only required for authentication when uploading a + * file from the client side. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun expire(): Optional = expire.value.getOptional("expire") + + /** + * Array of extensions to be applied to the asset. Each extension can be configured with + * specific parameters based on the extension type. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun extensions(): Optional> = + extensions.value.getOptional("extensions") + + /** + * The folder path in which the image has to be uploaded. If the folder(s) didn't exist + * before, a new folder(s) is created. + * + * The folder name can contain: + * - Alphanumeric Characters: `a-z` , `A-Z` , `0-9` + * - Special Characters: `/` , `_` , `-` + * + * Using multiple `/` creates a nested folder. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun folder(): Optional = folder.value.getOptional("folder") + + /** + * Whether to mark the file as private or not. + * + * If `true`, the file is marked as private and is accessible only using named + * transformation or signed URL. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun isPrivateFile(): Optional = isPrivateFile.value.getOptional("isPrivateFile") + + /** + * Whether to upload file as published or not. + * + * If `false`, the file is marked as unpublished, which restricts access to the file only + * via the media library. Files in draft or unpublished state can only be publicly accessed + * after being published. + * + * The option to upload in draft state is only available in custom enterprise pricing plans. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun isPublished(): Optional = isPublished.value.getOptional("isPublished") + + /** + * If set to `true` and a file already exists at the exact location, its AITags will be + * removed. Set `overwriteAITags` to `false` to preserve AITags. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun overwriteAiTags(): Optional = + overwriteAiTags.value.getOptional("overwriteAITags") + + /** + * If the request does not have `customMetadata`, and a file already exists at the exact + * location, existing customMetadata will be removed. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun overwriteCustomMetadata(): Optional = + overwriteCustomMetadata.value.getOptional("overwriteCustomMetadata") + + /** + * If `false` and `useUniqueFileName` is also `false`, and a file already exists at the + * exact location, upload API will return an error immediately. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun overwriteFile(): Optional = overwriteFile.value.getOptional("overwriteFile") + + /** + * If the request does not have `tags`, and a file already exists at the exact location, + * existing tags will be removed. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun overwriteTags(): Optional = overwriteTags.value.getOptional("overwriteTags") + + /** + * Your ImageKit.io public key. This field is only required for authentication when + * uploading a file from the client side. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun publicKey(): Optional = publicKey.value.getOptional("publicKey") + + /** + * Array of response field keys to include in the API response body. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun responseFields(): Optional> = + responseFields.value.getOptional("responseFields") + + /** + * HMAC-SHA1 digest of the token+expire using your ImageKit.io private API key as a key. + * Learn how to create a signature on the page below. This should be in lowercase. + * + * Signature must be calculated on the server-side. This field is only required for + * authentication when uploading a file from the client side. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun signature(): Optional = signature.value.getOptional("signature") + + /** + * Set the tags while uploading the file. Provide an array of tag strings (e.g. `["tag1", + * "tag2", "tag3"]`). The combined length of all tag characters must not exceed 500, and the + * `%` character is not allowed. If this field is not specified and the file is overwritten, + * the existing tags will be removed. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun tags(): Optional> = tags.value.getOptional("tags") + + /** + * Configure pre-processing (`pre`) and post-processing (`post`) transformations. + * - `pre` — applied before the file is uploaded to the Media Library. Useful for reducing + * file size or applying basic optimizations upfront (e.g., resize, compress). + * - `post` — applied immediately after upload. Ideal for generating transformed versions + * (like video encodes or thumbnails) in advance, so they're ready for delivery without + * delay. + * + * You can mix and match any combination of post-processing types. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun transformation(): Optional = + transformation.value.getOptional("transformation") + + /** + * Whether to use a unique filename for this file or not. + * + * If `true`, ImageKit.io will add a unique suffix to the filename parameter to get a unique + * filename. + * + * If `false`, then the image is uploaded with the provided filename parameter, and any + * existing file with the same name is replaced. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun useUniqueFileName(): Optional = + useUniqueFileName.value.getOptional("useUniqueFileName") + + /** + * The final status of extensions after they have completed execution will be delivered to + * this endpoint as a POST request. + * [Learn more](/docs/api-reference/digital-asset-management-dam/managing-assets/update-file-details#webhook-payload-structure) + * about the webhook payload structure. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun webhookUrl(): Optional = webhookUrl.value.getOptional("webhookUrl") + + /** + * Returns the raw multipart value of [file]. + * + * Unlike [file], this method doesn't throw if the multipart field has an unexpected type. + */ + @JsonProperty("file") @ExcludeMissing fun _file(): MultipartField = file + + /** + * Returns the raw multipart value of [fileName]. + * + * Unlike [fileName], this method doesn't throw if the multipart field has an unexpected + * type. + */ + @JsonProperty("fileName") @ExcludeMissing fun _fileName(): MultipartField = fileName + + /** + * Returns the raw multipart value of [token]. + * + * Unlike [token], this method doesn't throw if the multipart field has an unexpected type. + */ + @JsonProperty("token") @ExcludeMissing fun _token(): MultipartField = token + + /** + * Returns the raw multipart value of [checks]. + * + * Unlike [checks], this method doesn't throw if the multipart field has an unexpected type. + */ + @JsonProperty("checks") @ExcludeMissing fun _checks(): MultipartField = checks + + /** + * Returns the raw multipart value of [customCoordinates]. + * + * Unlike [customCoordinates], this method doesn't throw if the multipart field has an + * unexpected type. + */ + @JsonProperty("customCoordinates") + @ExcludeMissing + fun _customCoordinates(): MultipartField = customCoordinates + + /** + * Returns the raw multipart value of [customMetadata]. + * + * Unlike [customMetadata], this method doesn't throw if the multipart field has an + * unexpected type. + */ + @JsonProperty("customMetadata") + @ExcludeMissing + fun _customMetadata(): MultipartField = customMetadata + + /** + * Returns the raw multipart value of [description]. + * + * Unlike [description], this method doesn't throw if the multipart field has an unexpected + * type. + */ + @JsonProperty("description") + @ExcludeMissing + fun _description(): MultipartField = description + + /** + * Returns the raw multipart value of [expire]. + * + * Unlike [expire], this method doesn't throw if the multipart field has an unexpected type. + */ + @JsonProperty("expire") @ExcludeMissing fun _expire(): MultipartField = expire + + /** + * Returns the raw multipart value of [extensions]. + * + * Unlike [extensions], this method doesn't throw if the multipart field has an unexpected + * type. + */ + @JsonProperty("extensions") + @ExcludeMissing + fun _extensions(): MultipartField> = extensions + + /** + * Returns the raw multipart value of [folder]. + * + * Unlike [folder], this method doesn't throw if the multipart field has an unexpected type. + */ + @JsonProperty("folder") @ExcludeMissing fun _folder(): MultipartField = folder + + /** + * Returns the raw multipart value of [isPrivateFile]. + * + * Unlike [isPrivateFile], this method doesn't throw if the multipart field has an + * unexpected type. + */ + @JsonProperty("isPrivateFile") + @ExcludeMissing + fun _isPrivateFile(): MultipartField = isPrivateFile + + /** + * Returns the raw multipart value of [isPublished]. + * + * Unlike [isPublished], this method doesn't throw if the multipart field has an unexpected + * type. + */ + @JsonProperty("isPublished") + @ExcludeMissing + fun _isPublished(): MultipartField = isPublished + + /** + * Returns the raw multipart value of [overwriteAiTags]. + * + * Unlike [overwriteAiTags], this method doesn't throw if the multipart field has an + * unexpected type. + */ + @JsonProperty("overwriteAITags") + @ExcludeMissing + fun _overwriteAiTags(): MultipartField = overwriteAiTags + + /** + * Returns the raw multipart value of [overwriteCustomMetadata]. + * + * Unlike [overwriteCustomMetadata], this method doesn't throw if the multipart field has an + * unexpected type. + */ + @JsonProperty("overwriteCustomMetadata") + @ExcludeMissing + fun _overwriteCustomMetadata(): MultipartField = overwriteCustomMetadata + + /** + * Returns the raw multipart value of [overwriteFile]. + * + * Unlike [overwriteFile], this method doesn't throw if the multipart field has an + * unexpected type. + */ + @JsonProperty("overwriteFile") + @ExcludeMissing + fun _overwriteFile(): MultipartField = overwriteFile + + /** + * Returns the raw multipart value of [overwriteTags]. + * + * Unlike [overwriteTags], this method doesn't throw if the multipart field has an + * unexpected type. + */ + @JsonProperty("overwriteTags") + @ExcludeMissing + fun _overwriteTags(): MultipartField = overwriteTags + + /** + * Returns the raw multipart value of [publicKey]. + * + * Unlike [publicKey], this method doesn't throw if the multipart field has an unexpected + * type. + */ + @JsonProperty("publicKey") + @ExcludeMissing + fun _publicKey(): MultipartField = publicKey + + /** + * Returns the raw multipart value of [responseFields]. + * + * Unlike [responseFields], this method doesn't throw if the multipart field has an + * unexpected type. + */ + @JsonProperty("responseFields") + @ExcludeMissing + fun _responseFields(): MultipartField> = responseFields + + /** + * Returns the raw multipart value of [signature]. + * + * Unlike [signature], this method doesn't throw if the multipart field has an unexpected + * type. + */ + @JsonProperty("signature") + @ExcludeMissing + fun _signature(): MultipartField = signature + + /** + * Returns the raw multipart value of [tags]. + * + * Unlike [tags], this method doesn't throw if the multipart field has an unexpected type. + */ + @JsonProperty("tags") @ExcludeMissing fun _tags(): MultipartField> = tags + + /** + * Returns the raw multipart value of [transformation]. + * + * Unlike [transformation], this method doesn't throw if the multipart field has an + * unexpected type. + */ + @JsonProperty("transformation") + @ExcludeMissing + fun _transformation(): MultipartField = transformation + + /** + * Returns the raw multipart value of [useUniqueFileName]. + * + * Unlike [useUniqueFileName], this method doesn't throw if the multipart field has an + * unexpected type. + */ + @JsonProperty("useUniqueFileName") + @ExcludeMissing + fun _useUniqueFileName(): MultipartField = useUniqueFileName + + /** + * Returns the raw multipart value of [webhookUrl]. + * + * Unlike [webhookUrl], this method doesn't throw if the multipart field has an unexpected + * type. + */ + @JsonProperty("webhookUrl") + @ExcludeMissing + fun _webhookUrl(): MultipartField = webhookUrl + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Body]. + * + * The following fields are required: + * ```java + * .file() + * .fileName() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Body]. */ + class Builder internal constructor() { + + private var file: MultipartField? = null + private var fileName: MultipartField? = null + private var token: MultipartField = MultipartField.of(null) + private var checks: MultipartField = MultipartField.of(null) + private var customCoordinates: MultipartField = MultipartField.of(null) + private var customMetadata: MultipartField = MultipartField.of(null) + private var description: MultipartField = MultipartField.of(null) + private var expire: MultipartField = MultipartField.of(null) + private var extensions: MultipartField>? = + null + private var folder: MultipartField = MultipartField.of(null) + private var isPrivateFile: MultipartField = MultipartField.of(null) + private var isPublished: MultipartField = MultipartField.of(null) + private var overwriteAiTags: MultipartField = MultipartField.of(null) + private var overwriteCustomMetadata: MultipartField = MultipartField.of(null) + private var overwriteFile: MultipartField = MultipartField.of(null) + private var overwriteTags: MultipartField = MultipartField.of(null) + private var publicKey: MultipartField = MultipartField.of(null) + private var responseFields: MultipartField>? = null + private var signature: MultipartField = MultipartField.of(null) + private var tags: MultipartField>? = null + private var transformation: MultipartField = MultipartField.of(null) + private var useUniqueFileName: MultipartField = MultipartField.of(null) + private var webhookUrl: MultipartField = MultipartField.of(null) + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(body: Body) = apply { + file = body.file + fileName = body.fileName + token = body.token + checks = body.checks + customCoordinates = body.customCoordinates + customMetadata = body.customMetadata + description = body.description + expire = body.expire + extensions = body.extensions.map { it.toMutableList() } + folder = body.folder + isPrivateFile = body.isPrivateFile + isPublished = body.isPublished + overwriteAiTags = body.overwriteAiTags + overwriteCustomMetadata = body.overwriteCustomMetadata + overwriteFile = body.overwriteFile + overwriteTags = body.overwriteTags + publicKey = body.publicKey + responseFields = body.responseFields.map { it.toMutableList() } + signature = body.signature + tags = body.tags.map { it.toMutableList() } + transformation = body.transformation + useUniqueFileName = body.useUniqueFileName + webhookUrl = body.webhookUrl + additionalProperties = body.additionalProperties.toMutableMap() + } + + /** + * The API accepts any of the following: + * - **Binary data** – send the raw bytes as `multipart/form-data`. + * - **HTTP / HTTPS URL** – a publicly reachable URL that ImageKit’s servers can fetch. + * - **Base64 string** – the file encoded as a Base64 data URI or plain Base64. + * + * When supplying a URL, the server must receive the response headers within 8 seconds; + * otherwise the request fails with 400 Bad Request. + */ + fun file(file: InputStream) = file(MultipartField.of(file)) + + /** + * Sets [Builder.file] to an arbitrary multipart value. + * + * You should usually call [Builder.file] with a well-typed [InputStream] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun file(file: MultipartField) = apply { this.file = file } + + /** + * The API accepts any of the following: + * - **Binary data** – send the raw bytes as `multipart/form-data`. + * - **HTTP / HTTPS URL** – a publicly reachable URL that ImageKit’s servers can fetch. + * - **Base64 string** – the file encoded as a Base64 data URI or plain Base64. + * + * When supplying a URL, the server must receive the response headers within 8 seconds; + * otherwise the request fails with 400 Bad Request. + */ + fun file(file: ByteArray) = file(file.inputStream()) + + /** + * The API accepts any of the following: + * - **Binary data** – send the raw bytes as `multipart/form-data`. + * - **HTTP / HTTPS URL** – a publicly reachable URL that ImageKit’s servers can fetch. + * - **Base64 string** – the file encoded as a Base64 data URI or plain Base64. + * + * When supplying a URL, the server must receive the response headers within 8 seconds; + * otherwise the request fails with 400 Bad Request. + */ + fun file(path: Path) = + file( + MultipartField.builder() + .value(path.inputStream()) + .filename(path.name) + .build() + ) + + /** + * The name with which the file has to be uploaded. The file name can contain: + * - Alphanumeric Characters: `a-z`, `A-Z`, `0-9`. + * - Special Characters: `.`, `-` + * + * Any other character including space will be replaced by `_` + */ + fun fileName(fileName: String) = fileName(MultipartField.of(fileName)) + + /** + * Sets [Builder.fileName] to an arbitrary multipart value. + * + * You should usually call [Builder.fileName] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun fileName(fileName: MultipartField) = apply { this.fileName = fileName } + + /** + * A unique value that the ImageKit.io server will use to recognize and prevent + * subsequent retries for the same request. We suggest using V4 UUIDs, or another random + * string with enough entropy to avoid collisions. This field is only required for + * authentication when uploading a file from the client side. + * + * **Note**: Sending a value that has been used in the past will result in a validation + * error. Even if your previous request resulted in an error, you should always send a + * new value for this field. + */ + fun token(token: String) = token(MultipartField.of(token)) + + /** + * Sets [Builder.token] to an arbitrary multipart value. + * + * You should usually call [Builder.token] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun token(token: MultipartField) = apply { this.token = token } + + /** + * Server-side checks to run on the asset. Read more about + * [Upload API checks](/docs/api-reference/upload-file/upload-file#upload-api-checks). + */ + fun checks(checks: String) = checks(MultipartField.of(checks)) + + /** + * Sets [Builder.checks] to an arbitrary multipart value. + * + * You should usually call [Builder.checks] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun checks(checks: MultipartField) = apply { this.checks = checks } + + /** + * Define an important area in the image. This is only relevant for image type files. + * - To be passed as a string with the x and y coordinates of the top-left corner, and + * width and height of the area of interest in the format `x,y,width,height`. For + * example - `10,10,100,100` + * - Can be used with fo-customtransformation. + * - If this field is not specified and the file is overwritten, then customCoordinates + * will be removed. + */ + fun customCoordinates(customCoordinates: String) = + customCoordinates(MultipartField.of(customCoordinates)) + + /** + * Sets [Builder.customCoordinates] to an arbitrary multipart value. + * + * You should usually call [Builder.customCoordinates] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun customCoordinates(customCoordinates: MultipartField) = apply { + this.customCoordinates = customCoordinates + } + + /** + * JSON key-value pairs to associate with the asset. Create the custom metadata fields + * before setting these values. + */ + fun customMetadata(customMetadata: CustomMetadata) = + customMetadata(MultipartField.of(customMetadata)) + + /** + * Sets [Builder.customMetadata] to an arbitrary multipart value. + * + * You should usually call [Builder.customMetadata] with a well-typed [CustomMetadata] + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun customMetadata(customMetadata: MultipartField) = apply { + this.customMetadata = customMetadata + } + + /** Optional text to describe the contents of the file. */ + fun description(description: String) = description(MultipartField.of(description)) + + /** + * Sets [Builder.description] to an arbitrary multipart value. + * + * You should usually call [Builder.description] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun description(description: MultipartField) = apply { + this.description = description + } + + /** + * The time until your signature is valid. It must be a + * [Unix time](https://en.wikipedia.org/wiki/Unix_time) in less than 1 hour into the + * future. It should be in seconds. This field is only required for authentication when + * uploading a file from the client side. + */ + fun expire(expire: Long) = expire(MultipartField.of(expire)) + + /** + * Sets [Builder.expire] to an arbitrary multipart value. + * + * You should usually call [Builder.expire] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun expire(expire: MultipartField) = apply { this.expire = expire } + + /** + * Array of extensions to be applied to the asset. Each extension can be configured with + * specific parameters based on the extension type. + */ + fun extensions(extensions: List) = + extensions(MultipartField.of(extensions)) + + /** + * Sets [Builder.extensions] to an arbitrary multipart value. + * + * You should usually call [Builder.extensions] with a well-typed + * `List` value instead. This method is primarily for + * setting the field to an undocumented or not yet supported value. + */ + fun extensions(extensions: MultipartField>) = + apply { + this.extensions = extensions.map { it.toMutableList() } + } + + /** + * Adds a single [UnnamedSchemaWithArrayParent3] to [extensions]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addExtension(extension: UnnamedSchemaWithArrayParent3) = apply { + extensions = + (extensions ?: MultipartField.of(mutableListOf())).also { + checkKnown("extensions", it).add(extension) + } + } + + /** + * Alias for calling [addExtension] with + * `UnnamedSchemaWithArrayParent3.ofRemoveBg(removeBg)`. + */ + fun addExtension(removeBg: UnnamedSchemaWithArrayParent3.RemoveBg) = + addExtension(UnnamedSchemaWithArrayParent3.ofRemoveBg(removeBg)) + + /** + * Alias for calling [addExtension] with + * `UnnamedSchemaWithArrayParent3.ofAutoTaggingExtension(autoTaggingExtension)`. + */ + fun addExtension( + autoTaggingExtension: UnnamedSchemaWithArrayParent3.AutoTaggingExtension + ) = + addExtension( + UnnamedSchemaWithArrayParent3.ofAutoTaggingExtension(autoTaggingExtension) + ) + + /** + * Alias for calling [addExtension] with + * `UnnamedSchemaWithArrayParent3.ofAiAutoDescription()`. + */ + fun addExtensionAiAutoDescription() = + addExtension(UnnamedSchemaWithArrayParent3.ofAiAutoDescription()) + + /** + * The folder path in which the image has to be uploaded. If the folder(s) didn't exist + * before, a new folder(s) is created. + * + * The folder name can contain: + * - Alphanumeric Characters: `a-z` , `A-Z` , `0-9` + * - Special Characters: `/` , `_` , `-` + * + * Using multiple `/` creates a nested folder. + */ + fun folder(folder: String) = folder(MultipartField.of(folder)) + + /** + * Sets [Builder.folder] to an arbitrary multipart value. + * + * You should usually call [Builder.folder] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun folder(folder: MultipartField) = apply { this.folder = folder } + + /** + * Whether to mark the file as private or not. + * + * If `true`, the file is marked as private and is accessible only using named + * transformation or signed URL. + */ + fun isPrivateFile(isPrivateFile: Boolean) = + isPrivateFile(MultipartField.of(isPrivateFile)) + + /** + * Sets [Builder.isPrivateFile] to an arbitrary multipart value. + * + * You should usually call [Builder.isPrivateFile] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun isPrivateFile(isPrivateFile: MultipartField) = apply { + this.isPrivateFile = isPrivateFile + } + + /** + * Whether to upload file as published or not. + * + * If `false`, the file is marked as unpublished, which restricts access to the file + * only via the media library. Files in draft or unpublished state can only be publicly + * accessed after being published. + * + * The option to upload in draft state is only available in custom enterprise pricing + * plans. + */ + fun isPublished(isPublished: Boolean) = isPublished(MultipartField.of(isPublished)) + + /** + * Sets [Builder.isPublished] to an arbitrary multipart value. + * + * You should usually call [Builder.isPublished] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun isPublished(isPublished: MultipartField) = apply { + this.isPublished = isPublished + } + + /** + * If set to `true` and a file already exists at the exact location, its AITags will be + * removed. Set `overwriteAITags` to `false` to preserve AITags. + */ + fun overwriteAiTags(overwriteAiTags: Boolean) = + overwriteAiTags(MultipartField.of(overwriteAiTags)) + + /** + * Sets [Builder.overwriteAiTags] to an arbitrary multipart value. + * + * You should usually call [Builder.overwriteAiTags] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun overwriteAiTags(overwriteAiTags: MultipartField) = apply { + this.overwriteAiTags = overwriteAiTags + } + + /** + * If the request does not have `customMetadata`, and a file already exists at the exact + * location, existing customMetadata will be removed. + */ + fun overwriteCustomMetadata(overwriteCustomMetadata: Boolean) = + overwriteCustomMetadata(MultipartField.of(overwriteCustomMetadata)) + + /** + * Sets [Builder.overwriteCustomMetadata] to an arbitrary multipart value. + * + * You should usually call [Builder.overwriteCustomMetadata] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun overwriteCustomMetadata(overwriteCustomMetadata: MultipartField) = apply { + this.overwriteCustomMetadata = overwriteCustomMetadata + } + + /** + * If `false` and `useUniqueFileName` is also `false`, and a file already exists at the + * exact location, upload API will return an error immediately. + */ + fun overwriteFile(overwriteFile: Boolean) = + overwriteFile(MultipartField.of(overwriteFile)) + + /** + * Sets [Builder.overwriteFile] to an arbitrary multipart value. + * + * You should usually call [Builder.overwriteFile] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun overwriteFile(overwriteFile: MultipartField) = apply { + this.overwriteFile = overwriteFile + } + + /** + * If the request does not have `tags`, and a file already exists at the exact location, + * existing tags will be removed. + */ + fun overwriteTags(overwriteTags: Boolean) = + overwriteTags(MultipartField.of(overwriteTags)) + + /** + * Sets [Builder.overwriteTags] to an arbitrary multipart value. + * + * You should usually call [Builder.overwriteTags] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun overwriteTags(overwriteTags: MultipartField) = apply { + this.overwriteTags = overwriteTags + } + + /** + * Your ImageKit.io public key. This field is only required for authentication when + * uploading a file from the client side. + */ + fun publicKey(publicKey: String) = publicKey(MultipartField.of(publicKey)) + + /** + * Sets [Builder.publicKey] to an arbitrary multipart value. + * + * You should usually call [Builder.publicKey] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun publicKey(publicKey: MultipartField) = apply { this.publicKey = publicKey } + + /** Array of response field keys to include in the API response body. */ + fun responseFields(responseFields: List) = + responseFields(MultipartField.of(responseFields)) + + /** + * Sets [Builder.responseFields] to an arbitrary multipart value. + * + * You should usually call [Builder.responseFields] with a well-typed + * `List` value instead. This method is primarily for setting the field + * to an undocumented or not yet supported value. + */ + fun responseFields(responseFields: MultipartField>) = apply { + this.responseFields = responseFields.map { it.toMutableList() } + } + + /** + * Adds a single [ResponseField] to [responseFields]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addResponseField(responseField: ResponseField) = apply { + responseFields = + (responseFields ?: MultipartField.of(mutableListOf())).also { + checkKnown("responseFields", it).add(responseField) + } + } + + /** + * HMAC-SHA1 digest of the token+expire using your ImageKit.io private API key as a key. + * Learn how to create a signature on the page below. This should be in lowercase. + * + * Signature must be calculated on the server-side. This field is only required for + * authentication when uploading a file from the client side. + */ + fun signature(signature: String) = signature(MultipartField.of(signature)) + + /** + * Sets [Builder.signature] to an arbitrary multipart value. + * + * You should usually call [Builder.signature] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun signature(signature: MultipartField) = apply { this.signature = signature } + + /** + * Set the tags while uploading the file. Provide an array of tag strings (e.g. + * `["tag1", "tag2", "tag3"]`). The combined length of all tag characters must not + * exceed 500, and the `%` character is not allowed. If this field is not specified and + * the file is overwritten, the existing tags will be removed. + */ + fun tags(tags: List) = tags(MultipartField.of(tags)) + + /** + * Sets [Builder.tags] to an arbitrary multipart value. + * + * You should usually call [Builder.tags] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun tags(tags: MultipartField>) = apply { + this.tags = tags.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [tags]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addTag(tag: String) = apply { + tags = + (tags ?: MultipartField.of(mutableListOf())).also { + checkKnown("tags", it).add(tag) + } + } + + /** + * Configure pre-processing (`pre`) and post-processing (`post`) transformations. + * - `pre` — applied before the file is uploaded to the Media Library. Useful for + * reducing file size or applying basic optimizations upfront (e.g., resize, + * compress). + * - `post` — applied immediately after upload. Ideal for generating transformed + * versions (like video encodes or thumbnails) in advance, so they're ready for + * delivery without delay. + * + * You can mix and match any combination of post-processing types. + */ + fun transformation(transformation: Transformation) = + transformation(MultipartField.of(transformation)) + + /** + * Sets [Builder.transformation] to an arbitrary multipart value. + * + * You should usually call [Builder.transformation] with a well-typed [Transformation] + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun transformation(transformation: MultipartField) = apply { + this.transformation = transformation + } + + /** + * Whether to use a unique filename for this file or not. + * + * If `true`, ImageKit.io will add a unique suffix to the filename parameter to get a + * unique filename. + * + * If `false`, then the image is uploaded with the provided filename parameter, and any + * existing file with the same name is replaced. + */ + fun useUniqueFileName(useUniqueFileName: Boolean) = + useUniqueFileName(MultipartField.of(useUniqueFileName)) + + /** + * Sets [Builder.useUniqueFileName] to an arbitrary multipart value. + * + * You should usually call [Builder.useUniqueFileName] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun useUniqueFileName(useUniqueFileName: MultipartField) = apply { + this.useUniqueFileName = useUniqueFileName + } + + /** + * The final status of extensions after they have completed execution will be delivered + * to this endpoint as a POST request. + * [Learn more](/docs/api-reference/digital-asset-management-dam/managing-assets/update-file-details#webhook-payload-structure) + * about the webhook payload structure. + */ + fun webhookUrl(webhookUrl: String) = webhookUrl(MultipartField.of(webhookUrl)) + + /** + * Sets [Builder.webhookUrl] to an arbitrary multipart value. + * + * You should usually call [Builder.webhookUrl] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun webhookUrl(webhookUrl: MultipartField) = apply { + this.webhookUrl = webhookUrl + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Body]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .file() + * .fileName() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Body = + Body( + checkRequired("file", file), + checkRequired("fileName", fileName), + token, + checks, + customCoordinates, + customMetadata, + description, + expire, + (extensions ?: MultipartField.of(null)).map { it.toImmutable() }, + folder, + isPrivateFile, + isPublished, + overwriteAiTags, + overwriteCustomMetadata, + overwriteFile, + overwriteTags, + publicKey, + (responseFields ?: MultipartField.of(null)).map { it.toImmutable() }, + signature, + (tags ?: MultipartField.of(null)).map { it.toImmutable() }, + transformation, + useUniqueFileName, + webhookUrl, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Body = apply { + if (validated) { + return@apply + } + + file() + fileName() + token() + checks() + customCoordinates() + customMetadata().ifPresent { it.validate() } + description() + expire() + extensions().ifPresent { it.forEach { it.validate() } } + folder() + isPrivateFile() + isPublished() + overwriteAiTags() + overwriteCustomMetadata() + overwriteFile() + overwriteTags() + publicKey() + responseFields().ifPresent { it.forEach { it.validate() } } + signature() + tags() + transformation().ifPresent { it.validate() } + useUniqueFileName() + webhookUrl() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Body && + file == other.file && + fileName == other.fileName && + token == other.token && + checks == other.checks && + customCoordinates == other.customCoordinates && + customMetadata == other.customMetadata && + description == other.description && + expire == other.expire && + extensions == other.extensions && + folder == other.folder && + isPrivateFile == other.isPrivateFile && + isPublished == other.isPublished && + overwriteAiTags == other.overwriteAiTags && + overwriteCustomMetadata == other.overwriteCustomMetadata && + overwriteFile == other.overwriteFile && + overwriteTags == other.overwriteTags && + publicKey == other.publicKey && + responseFields == other.responseFields && + signature == other.signature && + tags == other.tags && + transformation == other.transformation && + useUniqueFileName == other.useUniqueFileName && + webhookUrl == other.webhookUrl && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + file, + fileName, + token, + checks, + customCoordinates, + customMetadata, + description, + expire, + extensions, + folder, + isPrivateFile, + isPublished, + overwriteAiTags, + overwriteCustomMetadata, + overwriteFile, + overwriteTags, + publicKey, + responseFields, + signature, + tags, + transformation, + useUniqueFileName, + webhookUrl, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Body{file=$file, fileName=$fileName, token=$token, checks=$checks, customCoordinates=$customCoordinates, customMetadata=$customMetadata, description=$description, expire=$expire, extensions=$extensions, folder=$folder, isPrivateFile=$isPrivateFile, isPublished=$isPublished, overwriteAiTags=$overwriteAiTags, overwriteCustomMetadata=$overwriteCustomMetadata, overwriteFile=$overwriteFile, overwriteTags=$overwriteTags, publicKey=$publicKey, responseFields=$responseFields, signature=$signature, tags=$tags, transformation=$transformation, useUniqueFileName=$useUniqueFileName, webhookUrl=$webhookUrl, additionalProperties=$additionalProperties}" + } + + /** + * JSON key-value pairs to associate with the asset. Create the custom metadata fields before + * setting these values. + */ + class CustomMetadata + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [CustomMetadata]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [CustomMetadata]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(customMetadata: CustomMetadata) = apply { + additionalProperties = customMetadata.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [CustomMetadata]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): CustomMetadata = CustomMetadata(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): CustomMetadata = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is CustomMetadata && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "CustomMetadata{additionalProperties=$additionalProperties}" + } + + @JsonDeserialize(using = UnnamedSchemaWithArrayParent3.Deserializer::class) + @JsonSerialize(using = UnnamedSchemaWithArrayParent3.Serializer::class) + class UnnamedSchemaWithArrayParent3 + private constructor( + private val removeBg: RemoveBg? = null, + private val autoTaggingExtension: AutoTaggingExtension? = null, + private val aiAutoDescription: JsonValue? = null, + private val _json: JsonValue? = null, + ) { + + fun removeBg(): Optional = Optional.ofNullable(removeBg) + + fun autoTaggingExtension(): Optional = + Optional.ofNullable(autoTaggingExtension) + + fun aiAutoDescription(): Optional = Optional.ofNullable(aiAutoDescription) + + fun isRemoveBg(): Boolean = removeBg != null + + fun isAutoTaggingExtension(): Boolean = autoTaggingExtension != null + + fun isAiAutoDescription(): Boolean = aiAutoDescription != null + + fun asRemoveBg(): RemoveBg = removeBg.getOrThrow("removeBg") + + fun asAutoTaggingExtension(): AutoTaggingExtension = + autoTaggingExtension.getOrThrow("autoTaggingExtension") + + fun asAiAutoDescription(): JsonValue = aiAutoDescription.getOrThrow("aiAutoDescription") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + removeBg != null -> visitor.visitRemoveBg(removeBg) + autoTaggingExtension != null -> + visitor.visitAutoTaggingExtension(autoTaggingExtension) + aiAutoDescription != null -> visitor.visitAiAutoDescription(aiAutoDescription) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): UnnamedSchemaWithArrayParent3 = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitRemoveBg(removeBg: RemoveBg) { + removeBg.validate() + } + + override fun visitAutoTaggingExtension( + autoTaggingExtension: AutoTaggingExtension + ) { + autoTaggingExtension.validate() + } + + override fun visitAiAutoDescription(aiAutoDescription: JsonValue) { + aiAutoDescription.let { + if (it != JsonValue.from(mapOf("name" to "ai-auto-description"))) { + throw ImageKitInvalidDataException( + "'aiAutoDescription' is invalid, received $it" + ) + } + } + } + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitRemoveBg(removeBg: RemoveBg) = removeBg.validity() + + override fun visitAutoTaggingExtension( + autoTaggingExtension: AutoTaggingExtension + ) = autoTaggingExtension.validity() + + override fun visitAiAutoDescription(aiAutoDescription: JsonValue) = + aiAutoDescription.let { + if (it == JsonValue.from(mapOf("name" to "ai-auto-description"))) 1 + else 0 + } + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is UnnamedSchemaWithArrayParent3 && + removeBg == other.removeBg && + autoTaggingExtension == other.autoTaggingExtension && + aiAutoDescription == other.aiAutoDescription + } + + override fun hashCode(): Int = + Objects.hash(removeBg, autoTaggingExtension, aiAutoDescription) + + override fun toString(): String = + when { + removeBg != null -> "UnnamedSchemaWithArrayParent3{removeBg=$removeBg}" + autoTaggingExtension != null -> + "UnnamedSchemaWithArrayParent3{autoTaggingExtension=$autoTaggingExtension}" + aiAutoDescription != null -> + "UnnamedSchemaWithArrayParent3{aiAutoDescription=$aiAutoDescription}" + _json != null -> "UnnamedSchemaWithArrayParent3{_unknown=$_json}" + else -> throw IllegalStateException("Invalid UnnamedSchemaWithArrayParent3") + } + + companion object { + + @JvmStatic + fun ofRemoveBg(removeBg: RemoveBg) = UnnamedSchemaWithArrayParent3(removeBg = removeBg) + + @JvmStatic + fun ofAutoTaggingExtension(autoTaggingExtension: AutoTaggingExtension) = + UnnamedSchemaWithArrayParent3(autoTaggingExtension = autoTaggingExtension) + + @JvmStatic + fun ofAiAutoDescription() = + UnnamedSchemaWithArrayParent3( + aiAutoDescription = JsonValue.from(mapOf("name" to "ai-auto-description")) + ) + } + + /** + * An interface that defines how to map each variant of [UnnamedSchemaWithArrayParent3] to a + * value of type [T]. + */ + interface Visitor { + + fun visitRemoveBg(removeBg: RemoveBg): T + + fun visitAutoTaggingExtension(autoTaggingExtension: AutoTaggingExtension): T + + fun visitAiAutoDescription(aiAutoDescription: JsonValue): T + + /** + * Maps an unknown variant of [UnnamedSchemaWithArrayParent3] to a value of type [T]. + * + * An instance of [UnnamedSchemaWithArrayParent3] can contain an unknown variant if it + * was deserialized from data that doesn't match any known variant. For example, if the + * SDK is on an older version than the API, then the API may respond with new variants + * that the SDK is unaware of. + * + * @throws ImageKitInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw ImageKitInvalidDataException("Unknown UnnamedSchemaWithArrayParent3: $json") + } + } + + internal class Deserializer : + BaseDeserializer(UnnamedSchemaWithArrayParent3::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): UnnamedSchemaWithArrayParent3 { + val json = JsonValue.fromJsonNode(node) + val name = json.asObject().getOrNull()?.get("name")?.asString()?.getOrNull() + + when (name) { + "remove-bg" -> { + return tryDeserialize(node, jacksonTypeRef())?.let { + UnnamedSchemaWithArrayParent3(removeBg = it, _json = json) + } ?: UnnamedSchemaWithArrayParent3(_json = json) + } + "ai-auto-description" -> { + return tryDeserialize(node, jacksonTypeRef()) + ?.let { + UnnamedSchemaWithArrayParent3(aiAutoDescription = it, _json = json) + } + ?.takeIf { it.isValid() } ?: UnnamedSchemaWithArrayParent3(_json = json) + } + } + + return tryDeserialize(node, jacksonTypeRef())?.let { + UnnamedSchemaWithArrayParent3(autoTaggingExtension = it, _json = json) + } ?: UnnamedSchemaWithArrayParent3(_json = json) + } + } + + internal class Serializer : + BaseSerializer(UnnamedSchemaWithArrayParent3::class) { + + override fun serialize( + value: UnnamedSchemaWithArrayParent3, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.removeBg != null -> generator.writeObject(value.removeBg) + value.autoTaggingExtension != null -> + generator.writeObject(value.autoTaggingExtension) + value.aiAutoDescription != null -> + generator.writeObject(value.aiAutoDescription) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid UnnamedSchemaWithArrayParent3") + } + } + } + + class RemoveBg + private constructor( + private val name: JsonValue, + private val options: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("name") @ExcludeMissing name: JsonValue = JsonMissing.of(), + @JsonProperty("options") + @ExcludeMissing + options: JsonField = JsonMissing.of(), + ) : this(name, options, mutableMapOf()) + + /** + * Specifies the background removal extension. + * + * Expected to always return the following: + * ```java + * JsonValue.from("remove-bg") + * ``` + * + * However, this method can be useful for debugging and logging (e.g. if the server + * responded with an unexpected value). + */ + @JsonProperty("name") @ExcludeMissing fun _name(): JsonValue = name + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun options(): Optional = options.getOptional("options") + + /** + * Returns the raw JSON value of [options]. + * + * Unlike [options], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("options") @ExcludeMissing fun _options(): JsonField = options + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [RemoveBg]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [RemoveBg]. */ + class Builder internal constructor() { + + private var name: JsonValue = JsonValue.from("remove-bg") + private var options: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(removeBg: RemoveBg) = apply { + name = removeBg.name + options = removeBg.options + additionalProperties = removeBg.additionalProperties.toMutableMap() + } + + /** + * Sets the field to an arbitrary JSON value. + * + * It is usually unnecessary to call this method because the field defaults to the + * following: + * ```java + * JsonValue.from("remove-bg") + * ``` + * + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun name(name: JsonValue) = apply { this.name = name } + + fun options(options: Options) = options(JsonField.of(options)) + + /** + * Sets [Builder.options] to an arbitrary JSON value. + * + * You should usually call [Builder.options] with a well-typed [Options] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun options(options: JsonField) = apply { this.options = options } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [RemoveBg]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): RemoveBg = RemoveBg(name, options, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): RemoveBg = apply { + if (validated) { + return@apply + } + + _name().let { + if (it != JsonValue.from("remove-bg")) { + throw ImageKitInvalidDataException("'name' is invalid, received $it") + } + } + options().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + name.let { if (it == JsonValue.from("remove-bg")) 1 else 0 } + + (options.asKnown().getOrNull()?.validity() ?: 0) + + class Options + private constructor( + private val addShadow: JsonField, + private val bgColor: JsonField, + private val bgImageUrl: JsonField, + private val semitransparency: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("add_shadow") + @ExcludeMissing + addShadow: JsonField = JsonMissing.of(), + @JsonProperty("bg_color") + @ExcludeMissing + bgColor: JsonField = JsonMissing.of(), + @JsonProperty("bg_image_url") + @ExcludeMissing + bgImageUrl: JsonField = JsonMissing.of(), + @JsonProperty("semitransparency") + @ExcludeMissing + semitransparency: JsonField = JsonMissing.of(), + ) : this(addShadow, bgColor, bgImageUrl, semitransparency, mutableMapOf()) + + /** + * Whether to add an artificial shadow to the result. Default is false. Note: Adding + * shadows is currently only supported for car photos. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun addShadow(): Optional = addShadow.getOptional("add_shadow") + + /** + * Specifies a solid color background using hex code (e.g., "81d4fa", "fff") or + * color name (e.g., "green"). If this parameter is set, `bg_image_url` must be + * empty. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun bgColor(): Optional = bgColor.getOptional("bg_color") + + /** + * Sets a background image from a URL. If this parameter is set, `bg_color` must be + * empty. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun bgImageUrl(): Optional = bgImageUrl.getOptional("bg_image_url") + + /** + * Allows semi-transparent regions in the result. Default is true. Note: + * Semitransparency is currently only supported for car windows. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun semitransparency(): Optional = + semitransparency.getOptional("semitransparency") + + /** + * Returns the raw JSON value of [addShadow]. + * + * Unlike [addShadow], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("add_shadow") + @ExcludeMissing + fun _addShadow(): JsonField = addShadow + + /** + * Returns the raw JSON value of [bgColor]. + * + * Unlike [bgColor], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("bg_color") + @ExcludeMissing + fun _bgColor(): JsonField = bgColor + + /** + * Returns the raw JSON value of [bgImageUrl]. + * + * Unlike [bgImageUrl], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("bg_image_url") + @ExcludeMissing + fun _bgImageUrl(): JsonField = bgImageUrl + + /** + * Returns the raw JSON value of [semitransparency]. + * + * Unlike [semitransparency], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("semitransparency") + @ExcludeMissing + fun _semitransparency(): JsonField = semitransparency + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Options]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Options]. */ + class Builder internal constructor() { + + private var addShadow: JsonField = JsonMissing.of() + private var bgColor: JsonField = JsonMissing.of() + private var bgImageUrl: JsonField = JsonMissing.of() + private var semitransparency: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(options: Options) = apply { + addShadow = options.addShadow + bgColor = options.bgColor + bgImageUrl = options.bgImageUrl + semitransparency = options.semitransparency + additionalProperties = options.additionalProperties.toMutableMap() + } + + /** + * Whether to add an artificial shadow to the result. Default is false. Note: + * Adding shadows is currently only supported for car photos. + */ + fun addShadow(addShadow: Boolean) = addShadow(JsonField.of(addShadow)) + + /** + * Sets [Builder.addShadow] to an arbitrary JSON value. + * + * You should usually call [Builder.addShadow] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun addShadow(addShadow: JsonField) = apply { + this.addShadow = addShadow + } + + /** + * Specifies a solid color background using hex code (e.g., "81d4fa", "fff") or + * color name (e.g., "green"). If this parameter is set, `bg_image_url` must be + * empty. + */ + fun bgColor(bgColor: String) = bgColor(JsonField.of(bgColor)) + + /** + * Sets [Builder.bgColor] to an arbitrary JSON value. + * + * You should usually call [Builder.bgColor] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun bgColor(bgColor: JsonField) = apply { this.bgColor = bgColor } + + /** + * Sets a background image from a URL. If this parameter is set, `bg_color` must + * be empty. + */ + fun bgImageUrl(bgImageUrl: String) = bgImageUrl(JsonField.of(bgImageUrl)) + + /** + * Sets [Builder.bgImageUrl] to an arbitrary JSON value. + * + * You should usually call [Builder.bgImageUrl] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun bgImageUrl(bgImageUrl: JsonField) = apply { + this.bgImageUrl = bgImageUrl + } + + /** + * Allows semi-transparent regions in the result. Default is true. Note: + * Semitransparency is currently only supported for car windows. + */ + fun semitransparency(semitransparency: Boolean) = + semitransparency(JsonField.of(semitransparency)) + + /** + * Sets [Builder.semitransparency] to an arbitrary JSON value. + * + * You should usually call [Builder.semitransparency] with a well-typed + * [Boolean] value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun semitransparency(semitransparency: JsonField) = apply { + this.semitransparency = semitransparency + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Options]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Options = + Options( + addShadow, + bgColor, + bgImageUrl, + semitransparency, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Options = apply { + if (validated) { + return@apply + } + + addShadow() + bgColor() + bgImageUrl() + semitransparency() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (addShadow.asKnown().isPresent) 1 else 0) + + (if (bgColor.asKnown().isPresent) 1 else 0) + + (if (bgImageUrl.asKnown().isPresent) 1 else 0) + + (if (semitransparency.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Options && + addShadow == other.addShadow && + bgColor == other.bgColor && + bgImageUrl == other.bgImageUrl && + semitransparency == other.semitransparency && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + addShadow, + bgColor, + bgImageUrl, + semitransparency, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Options{addShadow=$addShadow, bgColor=$bgColor, bgImageUrl=$bgImageUrl, semitransparency=$semitransparency, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is RemoveBg && + name == other.name && + options == other.options && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(name, options, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "RemoveBg{name=$name, options=$options, additionalProperties=$additionalProperties}" + } + + class AutoTaggingExtension + private constructor( + private val maxTags: JsonField, + private val minConfidence: JsonField, + private val name: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("maxTags") + @ExcludeMissing + maxTags: JsonField = JsonMissing.of(), + @JsonProperty("minConfidence") + @ExcludeMissing + minConfidence: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + ) : this(maxTags, minConfidence, name, mutableMapOf()) + + /** + * Maximum number of tags to attach to the asset. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected + * value). + */ + fun maxTags(): Long = maxTags.getRequired("maxTags") + + /** + * Minimum confidence level for tags to be considered valid. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected + * value). + */ + fun minConfidence(): Long = minConfidence.getRequired("minConfidence") + + /** + * Specifies the auto-tagging extension used. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected + * value). + */ + fun name(): Name = name.getRequired("name") + + /** + * Returns the raw JSON value of [maxTags]. + * + * Unlike [maxTags], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("maxTags") @ExcludeMissing fun _maxTags(): JsonField = maxTags + + /** + * Returns the raw JSON value of [minConfidence]. + * + * Unlike [minConfidence], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("minConfidence") + @ExcludeMissing + fun _minConfidence(): JsonField = minConfidence + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [AutoTaggingExtension]. + * + * The following fields are required: + * ```java + * .maxTags() + * .minConfidence() + * .name() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [AutoTaggingExtension]. */ + class Builder internal constructor() { + + private var maxTags: JsonField? = null + private var minConfidence: JsonField? = null + private var name: JsonField? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(autoTaggingExtension: AutoTaggingExtension) = apply { + maxTags = autoTaggingExtension.maxTags + minConfidence = autoTaggingExtension.minConfidence + name = autoTaggingExtension.name + additionalProperties = autoTaggingExtension.additionalProperties.toMutableMap() + } + + /** Maximum number of tags to attach to the asset. */ + fun maxTags(maxTags: Long) = maxTags(JsonField.of(maxTags)) + + /** + * Sets [Builder.maxTags] to an arbitrary JSON value. + * + * You should usually call [Builder.maxTags] with a well-typed [Long] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun maxTags(maxTags: JsonField) = apply { this.maxTags = maxTags } + + /** Minimum confidence level for tags to be considered valid. */ + fun minConfidence(minConfidence: Long) = minConfidence(JsonField.of(minConfidence)) + + /** + * Sets [Builder.minConfidence] to an arbitrary JSON value. + * + * You should usually call [Builder.minConfidence] with a well-typed [Long] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun minConfidence(minConfidence: JsonField) = apply { + this.minConfidence = minConfidence + } + + /** Specifies the auto-tagging extension used. */ + fun name(name: Name) = name(JsonField.of(name)) + + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [Name] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun name(name: JsonField) = apply { this.name = name } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [AutoTaggingExtension]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .maxTags() + * .minConfidence() + * .name() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): AutoTaggingExtension = + AutoTaggingExtension( + checkRequired("maxTags", maxTags), + checkRequired("minConfidence", minConfidence), + checkRequired("name", name), + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): AutoTaggingExtension = apply { + if (validated) { + return@apply + } + + maxTags() + minConfidence() + name().validate() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (maxTags.asKnown().isPresent) 1 else 0) + + (if (minConfidence.asKnown().isPresent) 1 else 0) + + (name.asKnown().getOrNull()?.validity() ?: 0) + + /** Specifies the auto-tagging extension used. */ + class Name @JsonCreator private constructor(private val value: JsonField) : + Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that + * doesn't match any known member, and you want to know that value. For example, if + * the SDK is on an older version than the API, then the API may respond with new + * members that the SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val GOOGLE_AUTO_TAGGING = of("google-auto-tagging") + + @JvmField val AWS_AUTO_TAGGING = of("aws-auto-tagging") + + @JvmStatic fun of(value: String) = Name(JsonField.of(value)) + } + + /** An enum containing [Name]'s known values. */ + enum class Known { + GOOGLE_AUTO_TAGGING, + AWS_AUTO_TAGGING, + } + + /** + * An enum containing [Name]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [Name] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, + * if the SDK is on an older version than the API, then the API may respond with + * new members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + GOOGLE_AUTO_TAGGING, + AWS_AUTO_TAGGING, + /** + * An enum member indicating that [Name] was instantiated with an unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if + * you want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + GOOGLE_AUTO_TAGGING -> Value.GOOGLE_AUTO_TAGGING + AWS_AUTO_TAGGING -> Value.AWS_AUTO_TAGGING + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and + * don't want to throw for the unknown case. + * + * @throws ImageKitInvalidDataException if this class instance's value is a not a + * known member. + */ + fun known(): Known = + when (this) { + GOOGLE_AUTO_TAGGING -> Known.GOOGLE_AUTO_TAGGING + AWS_AUTO_TAGGING -> Known.AWS_AUTO_TAGGING + else -> throw ImageKitInvalidDataException("Unknown Name: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for + * debugging and generally doesn't throw. + * + * @throws ImageKitInvalidDataException if this class instance's value does not have + * the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + ImageKitInvalidDataException("Value is not a String") + } + + private var validated: Boolean = false + + fun validate(): Name = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Name && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is AutoTaggingExtension && + maxTags == other.maxTags && + minConfidence == other.minConfidence && + name == other.name && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(maxTags, minConfidence, name, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "AutoTaggingExtension{maxTags=$maxTags, minConfidence=$minConfidence, name=$name, additionalProperties=$additionalProperties}" + } + } + + class ResponseField @JsonCreator private constructor(private val value: JsonField) : + Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is on an + * older version than the API, then the API may respond with new members that the SDK is + * unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val TAGS = of("tags") + + @JvmField val CUSTOM_COORDINATES = of("customCoordinates") + + @JvmField val IS_PRIVATE_FILE = of("isPrivateFile") + + @JvmField val EMBEDDED_METADATA = of("embeddedMetadata") + + @JvmField val IS_PUBLISHED = of("isPublished") + + @JvmField val CUSTOM_METADATA = of("customMetadata") + + @JvmField val METADATA = of("metadata") + + @JvmStatic fun of(value: String) = ResponseField(JsonField.of(value)) + } + + /** An enum containing [ResponseField]'s known values. */ + enum class Known { + TAGS, + CUSTOM_COORDINATES, + IS_PRIVATE_FILE, + EMBEDDED_METADATA, + IS_PUBLISHED, + CUSTOM_METADATA, + METADATA, + } + + /** + * An enum containing [ResponseField]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [ResponseField] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if the + * SDK is on an older version than the API, then the API may respond with new members that + * the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + TAGS, + CUSTOM_COORDINATES, + IS_PRIVATE_FILE, + EMBEDDED_METADATA, + IS_PUBLISHED, + CUSTOM_METADATA, + METADATA, + /** + * An enum member indicating that [ResponseField] was instantiated with an unknown + * value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] + * if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you want + * to throw for the unknown case. + */ + fun value(): Value = + when (this) { + TAGS -> Value.TAGS + CUSTOM_COORDINATES -> Value.CUSTOM_COORDINATES + IS_PRIVATE_FILE -> Value.IS_PRIVATE_FILE + EMBEDDED_METADATA -> Value.EMBEDDED_METADATA + IS_PUBLISHED -> Value.IS_PUBLISHED + CUSTOM_METADATA -> Value.CUSTOM_METADATA + METADATA -> Value.METADATA + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and don't + * want to throw for the unknown case. + * + * @throws ImageKitInvalidDataException if this class instance's value is a not a known + * member. + */ + fun known(): Known = + when (this) { + TAGS -> Known.TAGS + CUSTOM_COORDINATES -> Known.CUSTOM_COORDINATES + IS_PRIVATE_FILE -> Known.IS_PRIVATE_FILE + EMBEDDED_METADATA -> Known.EMBEDDED_METADATA + IS_PUBLISHED -> Known.IS_PUBLISHED + CUSTOM_METADATA -> Known.CUSTOM_METADATA + METADATA -> Known.METADATA + else -> throw ImageKitInvalidDataException("Unknown ResponseField: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for debugging + * and generally doesn't throw. + * + * @throws ImageKitInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + ImageKitInvalidDataException("Value is not a String") + } + + private var validated: Boolean = false + + fun validate(): ResponseField = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ResponseField && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + /** + * Configure pre-processing (`pre`) and post-processing (`post`) transformations. + * - `pre` — applied before the file is uploaded to the Media Library. Useful for reducing file + * size or applying basic optimizations upfront (e.g., resize, compress). + * - `post` — applied immediately after upload. Ideal for generating transformed versions (like + * video encodes or thumbnails) in advance, so they're ready for delivery without delay. + * + * You can mix and match any combination of post-processing types. + */ + class Transformation + private constructor( + private val post: MultipartField>, + private val pre: MultipartField, + private val additionalProperties: MutableMap, + ) { + + /** + * List of transformations to apply _after_ the file is uploaded. Each item must match one + * of the following types: `transformation`, `gif-to-video`, `thumbnail`, `abs`. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun post(): Optional> = post.value.getOptional("post") + + /** + * Transformation string to apply before uploading the file to the Media Library. Useful for + * optimizing files at ingestion. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun pre(): Optional = pre.value.getOptional("pre") + + /** + * Returns the raw multipart value of [post]. + * + * Unlike [post], this method doesn't throw if the multipart field has an unexpected type. + */ + @JsonProperty("post") @ExcludeMissing fun _post(): MultipartField> = post + + /** + * Returns the raw multipart value of [pre]. + * + * Unlike [pre], this method doesn't throw if the multipart field has an unexpected type. + */ + @JsonProperty("pre") @ExcludeMissing fun _pre(): MultipartField = pre + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Transformation]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Transformation]. */ + class Builder internal constructor() { + + private var post: MultipartField>? = null + private var pre: MultipartField = MultipartField.of(null) + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(transformation: Transformation) = apply { + post = transformation.post.map { it.toMutableList() } + pre = transformation.pre + additionalProperties = transformation.additionalProperties.toMutableMap() + } + + /** + * List of transformations to apply _after_ the file is uploaded. Each item must match + * one of the following types: `transformation`, `gif-to-video`, `thumbnail`, `abs`. + */ + fun post(post: List) = post(MultipartField.of(post)) + + /** + * Sets [Builder.post] to an arbitrary multipart value. + * + * You should usually call [Builder.post] with a well-typed `List` value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun post(post: MultipartField>) = apply { + this.post = post.map { it.toMutableList() } + } + + /** + * Adds a single [Post] to [Builder.post]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addPost(post: Post) = apply { + this.post = + (this.post ?: MultipartField.of(mutableListOf())).also { + checkKnown("post", it).add(post) + } + } + + /** Alias for calling [addPost] with `Post.ofTransformation(transformation)`. */ + fun addPost(transformation: Post.InnerTransformation) = + addPost(Post.ofTransformation(transformation)) + + /** + * Alias for calling [addPost] with the following: + * ```java + * Post.InnerTransformation.builder() + * .value(value) + * .build() + * ``` + */ + fun addTransformationPost(value: String) = + addPost(Post.InnerTransformation.builder().value(value).build()) + + /** Alias for calling [addPost] with `Post.ofGifToVideo(gifToVideo)`. */ + fun addPost(gifToVideo: Post.GifToVideo) = addPost(Post.ofGifToVideo(gifToVideo)) + + /** Alias for calling [addPost] with `Post.ofThumbnail(thumbnail)`. */ + fun addPost(thumbnail: Post.Thumbnail) = addPost(Post.ofThumbnail(thumbnail)) + + /** Alias for calling [addPost] with `Post.ofAbs(abs)`. */ + fun addPost(abs: Post.Abs) = addPost(Post.ofAbs(abs)) + + /** + * Transformation string to apply before uploading the file to the Media Library. Useful + * for optimizing files at ingestion. + */ + fun pre(pre: String) = pre(MultipartField.of(pre)) + + /** + * Sets [Builder.pre] to an arbitrary multipart value. + * + * You should usually call [Builder.pre] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun pre(pre: MultipartField) = apply { this.pre = pre } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Transformation]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Transformation = + Transformation( + (post ?: MultipartField.of(null)).map { it.toImmutable() }, + pre, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Transformation = apply { + if (validated) { + return@apply + } + + post().ifPresent { it.forEach { it.validate() } } + pre() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + @JsonDeserialize(using = Post.Deserializer::class) + @JsonSerialize(using = Post.Serializer::class) + class Post + private constructor( + private val transformation: InnerTransformation? = null, + private val gifToVideo: GifToVideo? = null, + private val thumbnail: Thumbnail? = null, + private val abs: Abs? = null, + private val _json: JsonValue? = null, + ) { + + fun transformation(): Optional = + Optional.ofNullable(transformation) + + fun gifToVideo(): Optional = Optional.ofNullable(gifToVideo) + + fun thumbnail(): Optional = Optional.ofNullable(thumbnail) + + fun abs(): Optional = Optional.ofNullable(abs) + + fun isTransformation(): Boolean = transformation != null + + fun isGifToVideo(): Boolean = gifToVideo != null + + fun isThumbnail(): Boolean = thumbnail != null + + fun isAbs(): Boolean = abs != null + + fun asTransformation(): InnerTransformation = + transformation.getOrThrow("transformation") + + fun asGifToVideo(): GifToVideo = gifToVideo.getOrThrow("gifToVideo") + + fun asThumbnail(): Thumbnail = thumbnail.getOrThrow("thumbnail") + + fun asAbs(): Abs = abs.getOrThrow("abs") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + transformation != null -> visitor.visitTransformation(transformation) + gifToVideo != null -> visitor.visitGifToVideo(gifToVideo) + thumbnail != null -> visitor.visitThumbnail(thumbnail) + abs != null -> visitor.visitAbs(abs) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): Post = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitTransformation(transformation: InnerTransformation) { + transformation.validate() + } + + override fun visitGifToVideo(gifToVideo: GifToVideo) { + gifToVideo.validate() + } + + override fun visitThumbnail(thumbnail: Thumbnail) { + thumbnail.validate() + } + + override fun visitAbs(abs: Abs) { + abs.validate() + } + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitTransformation(transformation: InnerTransformation) = + transformation.validity() + + override fun visitGifToVideo(gifToVideo: GifToVideo) = gifToVideo.validity() + + override fun visitThumbnail(thumbnail: Thumbnail) = thumbnail.validity() + + override fun visitAbs(abs: Abs) = abs.validity() + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Post && + transformation == other.transformation && + gifToVideo == other.gifToVideo && + thumbnail == other.thumbnail && + abs == other.abs + } + + override fun hashCode(): Int = Objects.hash(transformation, gifToVideo, thumbnail, abs) + + override fun toString(): String = + when { + transformation != null -> "Post{transformation=$transformation}" + gifToVideo != null -> "Post{gifToVideo=$gifToVideo}" + thumbnail != null -> "Post{thumbnail=$thumbnail}" + abs != null -> "Post{abs=$abs}" + _json != null -> "Post{_unknown=$_json}" + else -> throw IllegalStateException("Invalid Post") + } + + companion object { + + @JvmStatic + fun ofTransformation(transformation: InnerTransformation) = + Post(transformation = transformation) + + @JvmStatic fun ofGifToVideo(gifToVideo: GifToVideo) = Post(gifToVideo = gifToVideo) + + @JvmStatic fun ofThumbnail(thumbnail: Thumbnail) = Post(thumbnail = thumbnail) + + @JvmStatic fun ofAbs(abs: Abs) = Post(abs = abs) + } + + /** + * An interface that defines how to map each variant of [Post] to a value of type [T]. + */ + interface Visitor { + + fun visitTransformation(transformation: InnerTransformation): T + + fun visitGifToVideo(gifToVideo: GifToVideo): T + + fun visitThumbnail(thumbnail: Thumbnail): T + + fun visitAbs(abs: Abs): T + + /** + * Maps an unknown variant of [Post] to a value of type [T]. + * + * An instance of [Post] can contain an unknown variant if it was deserialized from + * data that doesn't match any known variant. For example, if the SDK is on an older + * version than the API, then the API may respond with new variants that the SDK is + * unaware of. + * + * @throws ImageKitInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw ImageKitInvalidDataException("Unknown Post: $json") + } + } + + internal class Deserializer : BaseDeserializer(Post::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): Post { + val json = JsonValue.fromJsonNode(node) + val type = json.asObject().getOrNull()?.get("type")?.asString()?.getOrNull() + + when (type) { + "transformation" -> { + return tryDeserialize(node, jacksonTypeRef()) + ?.let { Post(transformation = it, _json = json) } + ?: Post(_json = json) + } + "gif-to-video" -> { + return tryDeserialize(node, jacksonTypeRef())?.let { + Post(gifToVideo = it, _json = json) + } ?: Post(_json = json) + } + "thumbnail" -> { + return tryDeserialize(node, jacksonTypeRef())?.let { + Post(thumbnail = it, _json = json) + } ?: Post(_json = json) + } + "abs" -> { + return tryDeserialize(node, jacksonTypeRef())?.let { + Post(abs = it, _json = json) + } ?: Post(_json = json) + } + } + + return Post(_json = json) + } + } + + internal class Serializer : BaseSerializer(Post::class) { + + override fun serialize( + value: Post, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.transformation != null -> generator.writeObject(value.transformation) + value.gifToVideo != null -> generator.writeObject(value.gifToVideo) + value.thumbnail != null -> generator.writeObject(value.thumbnail) + value.abs != null -> generator.writeObject(value.abs) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid Post") + } + } + } + + class InnerTransformation + private constructor( + private val type: JsonValue, + private val value: MultipartField, + private val additionalProperties: MutableMap, + ) { + + /** + * Transformation type. + * + * Expected to always return the following: + * ```java + * JsonValue.from("transformation") + * ``` + * + * However, this method can be useful for debugging and logging (e.g. if the server + * responded with an unexpected value). + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type + + /** + * Transformation string (e.g. `w-200,h-200`). Same syntax as ImageKit URL-based + * transformations. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or + * is unexpectedly missing or null (e.g. if the server responded with an + * unexpected value). + */ + fun value(): String = value.value.getRequired("value") + + /** + * Returns the raw multipart value of [value]. + * + * Unlike [value], this method doesn't throw if the multipart field has an + * unexpected type. + */ + @JsonProperty("value") @ExcludeMissing fun _value(): MultipartField = value + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [InnerTransformation]. + * + * The following fields are required: + * ```java + * .value() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [InnerTransformation]. */ + class Builder internal constructor() { + + private var type: JsonValue = JsonValue.from("transformation") + private var value: MultipartField? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(innerTransformation: InnerTransformation) = apply { + type = innerTransformation.type + value = innerTransformation.value + additionalProperties = + innerTransformation.additionalProperties.toMutableMap() + } + + /** + * Sets the field to an arbitrary JSON value. + * + * It is usually unnecessary to call this method because the field defaults to + * the following: + * ```java + * JsonValue.from("transformation") + * ``` + * + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun type(type: JsonValue) = apply { this.type = type } + + /** + * Transformation string (e.g. `w-200,h-200`). Same syntax as ImageKit URL-based + * transformations. + */ + fun value(value: String) = value(MultipartField.of(value)) + + /** + * Sets [Builder.value] to an arbitrary multipart value. + * + * You should usually call [Builder.value] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun value(value: MultipartField) = apply { this.value = value } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [InnerTransformation]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .value() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): InnerTransformation = + InnerTransformation( + type, + checkRequired("value", value), + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): InnerTransformation = apply { + if (validated) { + return@apply + } + + _type().let { + if (it != JsonValue.from("transformation")) { + throw ImageKitInvalidDataException("'type' is invalid, received $it") + } + } + value() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is InnerTransformation && + type == other.type && + value == other.value && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(type, value, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "InnerTransformation{type=$type, value=$value, additionalProperties=$additionalProperties}" + } + + class GifToVideo + private constructor( + private val type: JsonValue, + private val value: MultipartField, + private val additionalProperties: MutableMap, + ) { + + /** + * Converts an animated GIF into an MP4. + * + * Expected to always return the following: + * ```java + * JsonValue.from("gif-to-video") + * ``` + * + * However, this method can be useful for debugging and logging (e.g. if the server + * responded with an unexpected value). + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type + + /** + * Optional transformation string to apply to the output video. **Example**: `q-80` + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun value(): Optional = value.value.getOptional("value") + + /** + * Returns the raw multipart value of [value]. + * + * Unlike [value], this method doesn't throw if the multipart field has an + * unexpected type. + */ + @JsonProperty("value") @ExcludeMissing fun _value(): MultipartField = value + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [GifToVideo]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [GifToVideo]. */ + class Builder internal constructor() { + + private var type: JsonValue = JsonValue.from("gif-to-video") + private var value: MultipartField = MultipartField.of(null) + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(gifToVideo: GifToVideo) = apply { + type = gifToVideo.type + value = gifToVideo.value + additionalProperties = gifToVideo.additionalProperties.toMutableMap() + } + + /** + * Sets the field to an arbitrary JSON value. + * + * It is usually unnecessary to call this method because the field defaults to + * the following: + * ```java + * JsonValue.from("gif-to-video") + * ``` + * + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun type(type: JsonValue) = apply { this.type = type } + + /** + * Optional transformation string to apply to the output video. **Example**: + * `q-80` + */ + fun value(value: String) = value(MultipartField.of(value)) + + /** + * Sets [Builder.value] to an arbitrary multipart value. + * + * You should usually call [Builder.value] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun value(value: MultipartField) = apply { this.value = value } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [GifToVideo]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): GifToVideo = + GifToVideo(type, value, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): GifToVideo = apply { + if (validated) { + return@apply + } + + _type().let { + if (it != JsonValue.from("gif-to-video")) { + throw ImageKitInvalidDataException("'type' is invalid, received $it") + } + } + value() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is GifToVideo && + type == other.type && + value == other.value && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(type, value, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "GifToVideo{type=$type, value=$value, additionalProperties=$additionalProperties}" + } + + class Thumbnail + private constructor( + private val type: JsonValue, + private val value: MultipartField, + private val additionalProperties: MutableMap, + ) { + + /** + * Generates a thumbnail image. + * + * Expected to always return the following: + * ```java + * JsonValue.from("thumbnail") + * ``` + * + * However, this method can be useful for debugging and logging (e.g. if the server + * responded with an unexpected value). + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type + + /** + * Optional transformation string. **Example**: `w-150,h-150` + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun value(): Optional = value.value.getOptional("value") + + /** + * Returns the raw multipart value of [value]. + * + * Unlike [value], this method doesn't throw if the multipart field has an + * unexpected type. + */ + @JsonProperty("value") @ExcludeMissing fun _value(): MultipartField = value + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Thumbnail]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Thumbnail]. */ + class Builder internal constructor() { + + private var type: JsonValue = JsonValue.from("thumbnail") + private var value: MultipartField = MultipartField.of(null) + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(thumbnail: Thumbnail) = apply { + type = thumbnail.type + value = thumbnail.value + additionalProperties = thumbnail.additionalProperties.toMutableMap() + } + + /** + * Sets the field to an arbitrary JSON value. + * + * It is usually unnecessary to call this method because the field defaults to + * the following: + * ```java + * JsonValue.from("thumbnail") + * ``` + * + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun type(type: JsonValue) = apply { this.type = type } + + /** Optional transformation string. **Example**: `w-150,h-150` */ + fun value(value: String) = value(MultipartField.of(value)) + + /** + * Sets [Builder.value] to an arbitrary multipart value. + * + * You should usually call [Builder.value] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun value(value: MultipartField) = apply { this.value = value } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Thumbnail]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Thumbnail = + Thumbnail(type, value, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Thumbnail = apply { + if (validated) { + return@apply + } + + _type().let { + if (it != JsonValue.from("thumbnail")) { + throw ImageKitInvalidDataException("'type' is invalid, received $it") + } + } + value() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Thumbnail && + type == other.type && + value == other.value && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(type, value, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Thumbnail{type=$type, value=$value, additionalProperties=$additionalProperties}" + } + + class Abs + private constructor( + private val protocol: MultipartField, + private val type: JsonValue, + private val value: MultipartField, + private val additionalProperties: MutableMap, + ) { + + /** + * Streaming protocol to use (`hls` or `dash`). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or + * is unexpectedly missing or null (e.g. if the server responded with an + * unexpected value). + */ + fun protocol(): Protocol = protocol.value.getRequired("protocol") + + /** + * Adaptive Bitrate Streaming (ABS) setup. + * + * Expected to always return the following: + * ```java + * JsonValue.from("abs") + * ``` + * + * However, this method can be useful for debugging and logging (e.g. if the server + * responded with an unexpected value). + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type + + /** + * List of different representations you want to create separated by an underscore. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or + * is unexpectedly missing or null (e.g. if the server responded with an + * unexpected value). + */ + fun value(): String = value.value.getRequired("value") + + /** + * Returns the raw multipart value of [protocol]. + * + * Unlike [protocol], this method doesn't throw if the multipart field has an + * unexpected type. + */ + @JsonProperty("protocol") + @ExcludeMissing + fun _protocol(): MultipartField = protocol + + /** + * Returns the raw multipart value of [value]. + * + * Unlike [value], this method doesn't throw if the multipart field has an + * unexpected type. + */ + @JsonProperty("value") @ExcludeMissing fun _value(): MultipartField = value + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Abs]. + * + * The following fields are required: + * ```java + * .protocol() + * .value() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Abs]. */ + class Builder internal constructor() { + + private var protocol: MultipartField? = null + private var type: JsonValue = JsonValue.from("abs") + private var value: MultipartField? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(abs: Abs) = apply { + protocol = abs.protocol + type = abs.type + value = abs.value + additionalProperties = abs.additionalProperties.toMutableMap() + } + + /** Streaming protocol to use (`hls` or `dash`). */ + fun protocol(protocol: Protocol) = protocol(MultipartField.of(protocol)) + + /** + * Sets [Builder.protocol] to an arbitrary multipart value. + * + * You should usually call [Builder.protocol] with a well-typed [Protocol] value + * instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun protocol(protocol: MultipartField) = apply { + this.protocol = protocol + } + + /** + * Sets the field to an arbitrary JSON value. + * + * It is usually unnecessary to call this method because the field defaults to + * the following: + * ```java + * JsonValue.from("abs") + * ``` + * + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun type(type: JsonValue) = apply { this.type = type } + + /** + * List of different representations you want to create separated by an + * underscore. + */ + fun value(value: String) = value(MultipartField.of(value)) + + /** + * Sets [Builder.value] to an arbitrary multipart value. + * + * You should usually call [Builder.value] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun value(value: MultipartField) = apply { this.value = value } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Abs]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .protocol() + * .value() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Abs = + Abs( + checkRequired("protocol", protocol), + type, + checkRequired("value", value), + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Abs = apply { + if (validated) { + return@apply + } + + protocol().validate() + _type().let { + if (it != JsonValue.from("abs")) { + throw ImageKitInvalidDataException("'type' is invalid, received $it") + } + } + value() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** Streaming protocol to use (`hls` or `dash`). */ + class Protocol + @JsonCreator + private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that + * doesn't match any known member, and you want to know that value. For example, + * if the SDK is on an older version than the API, then the API may respond with + * new members that the SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue + fun _value(): JsonField = value + + companion object { + + @JvmField val HLS = of("hls") + + @JvmField val DASH = of("dash") + + @JvmStatic fun of(value: String) = Protocol(JsonField.of(value)) + } + + /** An enum containing [Protocol]'s known values. */ + enum class Known { + HLS, + DASH, + } + + /** + * An enum containing [Protocol]'s known values, as well as an [_UNKNOWN] + * member. + * + * An instance of [Protocol] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For + * example, if the SDK is on an older version than the API, then the API may + * respond with new members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + HLS, + DASH, + /** + * An enum member indicating that [Protocol] was instantiated with an + * unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or + * if you want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + HLS -> Value.HLS + DASH -> Value.DASH + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known + * and don't want to throw for the unknown case. + * + * @throws ImageKitInvalidDataException if this class instance's value is a not + * a known member. + */ + fun known(): Known = + when (this) { + HLS -> Known.HLS + DASH -> Known.DASH + else -> throw ImageKitInvalidDataException("Unknown Protocol: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for + * debugging and generally doesn't throw. + * + * @throws ImageKitInvalidDataException if this class instance's value does not + * have the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + ImageKitInvalidDataException("Value is not a String") + } + + private var validated: Boolean = false + + fun validate(): Protocol = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Protocol && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Abs && + protocol == other.protocol && + type == other.type && + value == other.value && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(protocol, type, value, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Abs{protocol=$protocol, type=$type, value=$value, additionalProperties=$additionalProperties}" + } + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Transformation && + post == other.post && + pre == other.pre && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(post, pre, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Transformation{post=$post, pre=$pre, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is FileUploadParams && + body == other.body && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = Objects.hash(body, additionalHeaders, additionalQueryParams) + + override fun toString() = + "FileUploadParams{body=$body, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/files/FileUploadResponse.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/files/FileUploadResponse.kt new file mode 100644 index 0000000..3323941 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/files/FileUploadResponse.kt @@ -0,0 +1,2619 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.files + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.imagekit.api.core.Enum +import com.imagekit.api.core.ExcludeMissing +import com.imagekit.api.core.JsonField +import com.imagekit.api.core.JsonMissing +import com.imagekit.api.core.JsonValue +import com.imagekit.api.core.checkKnown +import com.imagekit.api.core.toImmutable +import com.imagekit.api.errors.ImageKitInvalidDataException +import java.util.Collections +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** Object containing details of a successful upload. */ +class FileUploadResponse +private constructor( + private val aiTags: JsonField>, + private val audioCodec: JsonField, + private val bitRate: JsonField, + private val customCoordinates: JsonField, + private val customMetadata: JsonField, + private val description: JsonField, + private val duration: JsonField, + private val embeddedMetadata: JsonField, + private val extensionStatus: JsonField, + private val fileId: JsonField, + private val filePath: JsonField, + private val fileType: JsonField, + private val height: JsonField, + private val isPrivateFile: JsonField, + private val isPublished: JsonField, + private val metadata: JsonField, + private val name: JsonField, + private val size: JsonField, + private val tags: JsonField>, + private val thumbnailUrl: JsonField, + private val url: JsonField, + private val versionInfo: JsonField, + private val videoCodec: JsonField, + private val width: JsonField, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("AITags") @ExcludeMissing aiTags: JsonField> = JsonMissing.of(), + @JsonProperty("audioCodec") + @ExcludeMissing + audioCodec: JsonField = JsonMissing.of(), + @JsonProperty("bitRate") @ExcludeMissing bitRate: JsonField = JsonMissing.of(), + @JsonProperty("customCoordinates") + @ExcludeMissing + customCoordinates: JsonField = JsonMissing.of(), + @JsonProperty("customMetadata") + @ExcludeMissing + customMetadata: JsonField = JsonMissing.of(), + @JsonProperty("description") + @ExcludeMissing + description: JsonField = JsonMissing.of(), + @JsonProperty("duration") @ExcludeMissing duration: JsonField = JsonMissing.of(), + @JsonProperty("embeddedMetadata") + @ExcludeMissing + embeddedMetadata: JsonField = JsonMissing.of(), + @JsonProperty("extensionStatus") + @ExcludeMissing + extensionStatus: JsonField = JsonMissing.of(), + @JsonProperty("fileId") @ExcludeMissing fileId: JsonField = JsonMissing.of(), + @JsonProperty("filePath") @ExcludeMissing filePath: JsonField = JsonMissing.of(), + @JsonProperty("fileType") @ExcludeMissing fileType: JsonField = JsonMissing.of(), + @JsonProperty("height") @ExcludeMissing height: JsonField = JsonMissing.of(), + @JsonProperty("isPrivateFile") + @ExcludeMissing + isPrivateFile: JsonField = JsonMissing.of(), + @JsonProperty("isPublished") + @ExcludeMissing + isPublished: JsonField = JsonMissing.of(), + @JsonProperty("metadata") @ExcludeMissing metadata: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("size") @ExcludeMissing size: JsonField = JsonMissing.of(), + @JsonProperty("tags") @ExcludeMissing tags: JsonField> = JsonMissing.of(), + @JsonProperty("thumbnailUrl") + @ExcludeMissing + thumbnailUrl: JsonField = JsonMissing.of(), + @JsonProperty("url") @ExcludeMissing url: JsonField = JsonMissing.of(), + @JsonProperty("versionInfo") + @ExcludeMissing + versionInfo: JsonField = JsonMissing.of(), + @JsonProperty("videoCodec") + @ExcludeMissing + videoCodec: JsonField = JsonMissing.of(), + @JsonProperty("width") @ExcludeMissing width: JsonField = JsonMissing.of(), + ) : this( + aiTags, + audioCodec, + bitRate, + customCoordinates, + customMetadata, + description, + duration, + embeddedMetadata, + extensionStatus, + fileId, + filePath, + fileType, + height, + isPrivateFile, + isPublished, + metadata, + name, + size, + tags, + thumbnailUrl, + url, + versionInfo, + videoCodec, + width, + mutableMapOf(), + ) + + /** + * An array of tags assigned to the uploaded file by auto tagging. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun aiTags(): Optional> = aiTags.getOptional("AITags") + + /** + * The audio codec used in the video (only for video). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun audioCodec(): Optional = audioCodec.getOptional("audioCodec") + + /** + * The bit rate of the video in kbps (only for video). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun bitRate(): Optional = bitRate.getOptional("bitRate") + + /** + * Value of custom coordinates associated with the image in the format `x,y,width,height`. If + * `customCoordinates` are not defined, then it is `null`. Send `customCoordinates` in + * `responseFields` in API request to get the value of this field. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun customCoordinates(): Optional = customCoordinates.getOptional("customCoordinates") + + /** + * A key-value data associated with the asset. Use `responseField` in API request to get + * `customMetadata` in the upload API response. Before setting any custom metadata on an asset, + * you have to create the field using custom metadata fields API. Send `customMetadata` in + * `responseFields` in API request to get the value of this field. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun customMetadata(): Optional = customMetadata.getOptional("customMetadata") + + /** + * Optional text to describe the contents of the file. Can be set by the user or the + * ai-auto-description extension. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun description(): Optional = description.getOptional("description") + + /** + * The duration of the video in seconds (only for video). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun duration(): Optional = duration.getOptional("duration") + + /** + * Consolidated embedded metadata associated with the file. It includes exif, iptc, and xmp + * data. Send `embeddedMetadata` in `responseFields` in API request to get embeddedMetadata in + * the upload API response. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun embeddedMetadata(): Optional = + embeddedMetadata.getOptional("embeddedMetadata") + + /** + * Extension names with their processing status at the time of completion of the request. It + * could have one of the following status values: + * + * `success`: The extension has been successfully applied. `failed`: The extension has failed + * and will not be retried. `pending`: The extension will finish processing in some time. On + * completion, the final status (success / failed) will be sent to the `webhookUrl` provided. + * + * If no extension was requested, then this parameter is not returned. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun extensionStatus(): Optional = + extensionStatus.getOptional("extensionStatus") + + /** + * Unique fileId. Store this fileld in your database, as this will be used to perform update + * action on this file. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun fileId(): Optional = fileId.getOptional("fileId") + + /** + * The relative path of the file in the media library e.g. `/marketing-assets/new-banner.jpg`. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun filePath(): Optional = filePath.getOptional("filePath") + + /** + * Type of the uploaded file. Possible values are `image`, `non-image`. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun fileType(): Optional = fileType.getOptional("fileType") + + /** + * Height of the image in pixels (Only for images) + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun height(): Optional = height.getOptional("height") + + /** + * Is the file marked as private. It can be either `true` or `false`. Send `isPrivateFile` in + * `responseFields` in API request to get the value of this field. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun isPrivateFile(): Optional = isPrivateFile.getOptional("isPrivateFile") + + /** + * Is the file published or in draft state. It can be either `true` or `false`. Send + * `isPublished` in `responseFields` in API request to get the value of this field. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun isPublished(): Optional = isPublished.getOptional("isPublished") + + /** + * Legacy metadata. Send `metadata` in `responseFields` in API request to get metadata in the + * upload API response. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun metadata(): Optional = metadata.getOptional("metadata") + + /** + * Name of the asset. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun name(): Optional = name.getOptional("name") + + /** + * Size of the image file in Bytes. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun size(): Optional = size.getOptional("size") + + /** + * The array of tags associated with the asset. If no tags are set, it will be `null`. Send + * `tags` in `responseFields` in API request to get the value of this field. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun tags(): Optional> = tags.getOptional("tags") + + /** + * In the case of an image, a small thumbnail URL. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun thumbnailUrl(): Optional = thumbnailUrl.getOptional("thumbnailUrl") + + /** + * A publicly accessible URL of the file. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun url(): Optional = url.getOptional("url") + + /** + * An object containing the file or file version's `id` (versionId) and `name`. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun versionInfo(): Optional = versionInfo.getOptional("versionInfo") + + /** + * The video codec used in the video (only for video). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun videoCodec(): Optional = videoCodec.getOptional("videoCodec") + + /** + * Width of the image in pixels (Only for Images) + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun width(): Optional = width.getOptional("width") + + /** + * Returns the raw JSON value of [aiTags]. + * + * Unlike [aiTags], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("AITags") @ExcludeMissing fun _aiTags(): JsonField> = aiTags + + /** + * Returns the raw JSON value of [audioCodec]. + * + * Unlike [audioCodec], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("audioCodec") @ExcludeMissing fun _audioCodec(): JsonField = audioCodec + + /** + * Returns the raw JSON value of [bitRate]. + * + * Unlike [bitRate], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("bitRate") @ExcludeMissing fun _bitRate(): JsonField = bitRate + + /** + * Returns the raw JSON value of [customCoordinates]. + * + * Unlike [customCoordinates], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("customCoordinates") + @ExcludeMissing + fun _customCoordinates(): JsonField = customCoordinates + + /** + * Returns the raw JSON value of [customMetadata]. + * + * Unlike [customMetadata], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("customMetadata") + @ExcludeMissing + fun _customMetadata(): JsonField = customMetadata + + /** + * Returns the raw JSON value of [description]. + * + * Unlike [description], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("description") @ExcludeMissing fun _description(): JsonField = description + + /** + * Returns the raw JSON value of [duration]. + * + * Unlike [duration], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("duration") @ExcludeMissing fun _duration(): JsonField = duration + + /** + * Returns the raw JSON value of [embeddedMetadata]. + * + * Unlike [embeddedMetadata], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("embeddedMetadata") + @ExcludeMissing + fun _embeddedMetadata(): JsonField = embeddedMetadata + + /** + * Returns the raw JSON value of [extensionStatus]. + * + * Unlike [extensionStatus], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("extensionStatus") + @ExcludeMissing + fun _extensionStatus(): JsonField = extensionStatus + + /** + * Returns the raw JSON value of [fileId]. + * + * Unlike [fileId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("fileId") @ExcludeMissing fun _fileId(): JsonField = fileId + + /** + * Returns the raw JSON value of [filePath]. + * + * Unlike [filePath], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("filePath") @ExcludeMissing fun _filePath(): JsonField = filePath + + /** + * Returns the raw JSON value of [fileType]. + * + * Unlike [fileType], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("fileType") @ExcludeMissing fun _fileType(): JsonField = fileType + + /** + * Returns the raw JSON value of [height]. + * + * Unlike [height], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("height") @ExcludeMissing fun _height(): JsonField = height + + /** + * Returns the raw JSON value of [isPrivateFile]. + * + * Unlike [isPrivateFile], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("isPrivateFile") + @ExcludeMissing + fun _isPrivateFile(): JsonField = isPrivateFile + + /** + * Returns the raw JSON value of [isPublished]. + * + * Unlike [isPublished], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("isPublished") + @ExcludeMissing + fun _isPublished(): JsonField = isPublished + + /** + * Returns the raw JSON value of [metadata]. + * + * Unlike [metadata], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("metadata") @ExcludeMissing fun _metadata(): JsonField = metadata + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + + /** + * Returns the raw JSON value of [size]. + * + * Unlike [size], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("size") @ExcludeMissing fun _size(): JsonField = size + + /** + * Returns the raw JSON value of [tags]. + * + * Unlike [tags], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("tags") @ExcludeMissing fun _tags(): JsonField> = tags + + /** + * Returns the raw JSON value of [thumbnailUrl]. + * + * Unlike [thumbnailUrl], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("thumbnailUrl") + @ExcludeMissing + fun _thumbnailUrl(): JsonField = thumbnailUrl + + /** + * Returns the raw JSON value of [url]. + * + * Unlike [url], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("url") @ExcludeMissing fun _url(): JsonField = url + + /** + * Returns the raw JSON value of [versionInfo]. + * + * Unlike [versionInfo], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("versionInfo") + @ExcludeMissing + fun _versionInfo(): JsonField = versionInfo + + /** + * Returns the raw JSON value of [videoCodec]. + * + * Unlike [videoCodec], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("videoCodec") @ExcludeMissing fun _videoCodec(): JsonField = videoCodec + + /** + * Returns the raw JSON value of [width]. + * + * Unlike [width], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("width") @ExcludeMissing fun _width(): JsonField = width + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [FileUploadResponse]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [FileUploadResponse]. */ + class Builder internal constructor() { + + private var aiTags: JsonField>? = null + private var audioCodec: JsonField = JsonMissing.of() + private var bitRate: JsonField = JsonMissing.of() + private var customCoordinates: JsonField = JsonMissing.of() + private var customMetadata: JsonField = JsonMissing.of() + private var description: JsonField = JsonMissing.of() + private var duration: JsonField = JsonMissing.of() + private var embeddedMetadata: JsonField = JsonMissing.of() + private var extensionStatus: JsonField = JsonMissing.of() + private var fileId: JsonField = JsonMissing.of() + private var filePath: JsonField = JsonMissing.of() + private var fileType: JsonField = JsonMissing.of() + private var height: JsonField = JsonMissing.of() + private var isPrivateFile: JsonField = JsonMissing.of() + private var isPublished: JsonField = JsonMissing.of() + private var metadata: JsonField = JsonMissing.of() + private var name: JsonField = JsonMissing.of() + private var size: JsonField = JsonMissing.of() + private var tags: JsonField>? = null + private var thumbnailUrl: JsonField = JsonMissing.of() + private var url: JsonField = JsonMissing.of() + private var versionInfo: JsonField = JsonMissing.of() + private var videoCodec: JsonField = JsonMissing.of() + private var width: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(fileUploadResponse: FileUploadResponse) = apply { + aiTags = fileUploadResponse.aiTags.map { it.toMutableList() } + audioCodec = fileUploadResponse.audioCodec + bitRate = fileUploadResponse.bitRate + customCoordinates = fileUploadResponse.customCoordinates + customMetadata = fileUploadResponse.customMetadata + description = fileUploadResponse.description + duration = fileUploadResponse.duration + embeddedMetadata = fileUploadResponse.embeddedMetadata + extensionStatus = fileUploadResponse.extensionStatus + fileId = fileUploadResponse.fileId + filePath = fileUploadResponse.filePath + fileType = fileUploadResponse.fileType + height = fileUploadResponse.height + isPrivateFile = fileUploadResponse.isPrivateFile + isPublished = fileUploadResponse.isPublished + metadata = fileUploadResponse.metadata + name = fileUploadResponse.name + size = fileUploadResponse.size + tags = fileUploadResponse.tags.map { it.toMutableList() } + thumbnailUrl = fileUploadResponse.thumbnailUrl + url = fileUploadResponse.url + versionInfo = fileUploadResponse.versionInfo + videoCodec = fileUploadResponse.videoCodec + width = fileUploadResponse.width + additionalProperties = fileUploadResponse.additionalProperties.toMutableMap() + } + + /** An array of tags assigned to the uploaded file by auto tagging. */ + fun aiTags(aiTags: List?) = aiTags(JsonField.ofNullable(aiTags)) + + /** Alias for calling [Builder.aiTags] with `aiTags.orElse(null)`. */ + fun aiTags(aiTags: Optional>) = aiTags(aiTags.getOrNull()) + + /** + * Sets [Builder.aiTags] to an arbitrary JSON value. + * + * You should usually call [Builder.aiTags] with a well-typed `List` value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun aiTags(aiTags: JsonField>) = apply { + this.aiTags = aiTags.map { it.toMutableList() } + } + + /** + * Adds a single [AiTag] to [aiTags]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addAiTag(aiTag: AiTag) = apply { + aiTags = + (aiTags ?: JsonField.of(mutableListOf())).also { + checkKnown("aiTags", it).add(aiTag) + } + } + + /** The audio codec used in the video (only for video). */ + fun audioCodec(audioCodec: String) = audioCodec(JsonField.of(audioCodec)) + + /** + * Sets [Builder.audioCodec] to an arbitrary JSON value. + * + * You should usually call [Builder.audioCodec] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun audioCodec(audioCodec: JsonField) = apply { this.audioCodec = audioCodec } + + /** The bit rate of the video in kbps (only for video). */ + fun bitRate(bitRate: Long) = bitRate(JsonField.of(bitRate)) + + /** + * Sets [Builder.bitRate] to an arbitrary JSON value. + * + * You should usually call [Builder.bitRate] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun bitRate(bitRate: JsonField) = apply { this.bitRate = bitRate } + + /** + * Value of custom coordinates associated with the image in the format `x,y,width,height`. + * If `customCoordinates` are not defined, then it is `null`. Send `customCoordinates` in + * `responseFields` in API request to get the value of this field. + */ + fun customCoordinates(customCoordinates: String?) = + customCoordinates(JsonField.ofNullable(customCoordinates)) + + /** Alias for calling [Builder.customCoordinates] with `customCoordinates.orElse(null)`. */ + fun customCoordinates(customCoordinates: Optional) = + customCoordinates(customCoordinates.getOrNull()) + + /** + * Sets [Builder.customCoordinates] to an arbitrary JSON value. + * + * You should usually call [Builder.customCoordinates] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun customCoordinates(customCoordinates: JsonField) = apply { + this.customCoordinates = customCoordinates + } + + /** + * A key-value data associated with the asset. Use `responseField` in API request to get + * `customMetadata` in the upload API response. Before setting any custom metadata on an + * asset, you have to create the field using custom metadata fields API. Send + * `customMetadata` in `responseFields` in API request to get the value of this field. + */ + fun customMetadata(customMetadata: CustomMetadata) = + customMetadata(JsonField.of(customMetadata)) + + /** + * Sets [Builder.customMetadata] to an arbitrary JSON value. + * + * You should usually call [Builder.customMetadata] with a well-typed [CustomMetadata] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun customMetadata(customMetadata: JsonField) = apply { + this.customMetadata = customMetadata + } + + /** + * Optional text to describe the contents of the file. Can be set by the user or the + * ai-auto-description extension. + */ + fun description(description: String) = description(JsonField.of(description)) + + /** + * Sets [Builder.description] to an arbitrary JSON value. + * + * You should usually call [Builder.description] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun description(description: JsonField) = apply { this.description = description } + + /** The duration of the video in seconds (only for video). */ + fun duration(duration: Long) = duration(JsonField.of(duration)) + + /** + * Sets [Builder.duration] to an arbitrary JSON value. + * + * You should usually call [Builder.duration] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun duration(duration: JsonField) = apply { this.duration = duration } + + /** + * Consolidated embedded metadata associated with the file. It includes exif, iptc, and xmp + * data. Send `embeddedMetadata` in `responseFields` in API request to get embeddedMetadata + * in the upload API response. + */ + fun embeddedMetadata(embeddedMetadata: EmbeddedMetadata) = + embeddedMetadata(JsonField.of(embeddedMetadata)) + + /** + * Sets [Builder.embeddedMetadata] to an arbitrary JSON value. + * + * You should usually call [Builder.embeddedMetadata] with a well-typed [EmbeddedMetadata] + * value instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun embeddedMetadata(embeddedMetadata: JsonField) = apply { + this.embeddedMetadata = embeddedMetadata + } + + /** + * Extension names with their processing status at the time of completion of the request. It + * could have one of the following status values: + * + * `success`: The extension has been successfully applied. `failed`: The extension has + * failed and will not be retried. `pending`: The extension will finish processing in some + * time. On completion, the final status (success / failed) will be sent to the `webhookUrl` + * provided. + * + * If no extension was requested, then this parameter is not returned. + */ + fun extensionStatus(extensionStatus: ExtensionStatus) = + extensionStatus(JsonField.of(extensionStatus)) + + /** + * Sets [Builder.extensionStatus] to an arbitrary JSON value. + * + * You should usually call [Builder.extensionStatus] with a well-typed [ExtensionStatus] + * value instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun extensionStatus(extensionStatus: JsonField) = apply { + this.extensionStatus = extensionStatus + } + + /** + * Unique fileId. Store this fileld in your database, as this will be used to perform update + * action on this file. + */ + fun fileId(fileId: String) = fileId(JsonField.of(fileId)) + + /** + * Sets [Builder.fileId] to an arbitrary JSON value. + * + * You should usually call [Builder.fileId] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun fileId(fileId: JsonField) = apply { this.fileId = fileId } + + /** + * The relative path of the file in the media library e.g. + * `/marketing-assets/new-banner.jpg`. + */ + fun filePath(filePath: String) = filePath(JsonField.of(filePath)) + + /** + * Sets [Builder.filePath] to an arbitrary JSON value. + * + * You should usually call [Builder.filePath] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun filePath(filePath: JsonField) = apply { this.filePath = filePath } + + /** Type of the uploaded file. Possible values are `image`, `non-image`. */ + fun fileType(fileType: String) = fileType(JsonField.of(fileType)) + + /** + * Sets [Builder.fileType] to an arbitrary JSON value. + * + * You should usually call [Builder.fileType] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun fileType(fileType: JsonField) = apply { this.fileType = fileType } + + /** Height of the image in pixels (Only for images) */ + fun height(height: Double) = height(JsonField.of(height)) + + /** + * Sets [Builder.height] to an arbitrary JSON value. + * + * You should usually call [Builder.height] with a well-typed [Double] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun height(height: JsonField) = apply { this.height = height } + + /** + * Is the file marked as private. It can be either `true` or `false`. Send `isPrivateFile` + * in `responseFields` in API request to get the value of this field. + */ + fun isPrivateFile(isPrivateFile: Boolean) = isPrivateFile(JsonField.of(isPrivateFile)) + + /** + * Sets [Builder.isPrivateFile] to an arbitrary JSON value. + * + * You should usually call [Builder.isPrivateFile] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun isPrivateFile(isPrivateFile: JsonField) = apply { + this.isPrivateFile = isPrivateFile + } + + /** + * Is the file published or in draft state. It can be either `true` or `false`. Send + * `isPublished` in `responseFields` in API request to get the value of this field. + */ + fun isPublished(isPublished: Boolean) = isPublished(JsonField.of(isPublished)) + + /** + * Sets [Builder.isPublished] to an arbitrary JSON value. + * + * You should usually call [Builder.isPublished] with a well-typed [Boolean] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun isPublished(isPublished: JsonField) = apply { this.isPublished = isPublished } + + /** + * Legacy metadata. Send `metadata` in `responseFields` in API request to get metadata in + * the upload API response. + */ + fun metadata(metadata: Metadata) = metadata(JsonField.of(metadata)) + + /** + * Sets [Builder.metadata] to an arbitrary JSON value. + * + * You should usually call [Builder.metadata] with a well-typed [Metadata] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun metadata(metadata: JsonField) = apply { this.metadata = metadata } + + /** Name of the asset. */ + fun name(name: String) = name(JsonField.of(name)) + + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun name(name: JsonField) = apply { this.name = name } + + /** Size of the image file in Bytes. */ + fun size(size: Double) = size(JsonField.of(size)) + + /** + * Sets [Builder.size] to an arbitrary JSON value. + * + * You should usually call [Builder.size] with a well-typed [Double] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun size(size: JsonField) = apply { this.size = size } + + /** + * The array of tags associated with the asset. If no tags are set, it will be `null`. Send + * `tags` in `responseFields` in API request to get the value of this field. + */ + fun tags(tags: List?) = tags(JsonField.ofNullable(tags)) + + /** Alias for calling [Builder.tags] with `tags.orElse(null)`. */ + fun tags(tags: Optional>) = tags(tags.getOrNull()) + + /** + * Sets [Builder.tags] to an arbitrary JSON value. + * + * You should usually call [Builder.tags] with a well-typed `List` value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun tags(tags: JsonField>) = apply { + this.tags = tags.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [tags]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addTag(tag: String) = apply { + tags = (tags ?: JsonField.of(mutableListOf())).also { checkKnown("tags", it).add(tag) } + } + + /** In the case of an image, a small thumbnail URL. */ + fun thumbnailUrl(thumbnailUrl: String) = thumbnailUrl(JsonField.of(thumbnailUrl)) + + /** + * Sets [Builder.thumbnailUrl] to an arbitrary JSON value. + * + * You should usually call [Builder.thumbnailUrl] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun thumbnailUrl(thumbnailUrl: JsonField) = apply { + this.thumbnailUrl = thumbnailUrl + } + + /** A publicly accessible URL of the file. */ + fun url(url: String) = url(JsonField.of(url)) + + /** + * Sets [Builder.url] to an arbitrary JSON value. + * + * You should usually call [Builder.url] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun url(url: JsonField) = apply { this.url = url } + + /** An object containing the file or file version's `id` (versionId) and `name`. */ + fun versionInfo(versionInfo: VersionInfo) = versionInfo(JsonField.of(versionInfo)) + + /** + * Sets [Builder.versionInfo] to an arbitrary JSON value. + * + * You should usually call [Builder.versionInfo] with a well-typed [VersionInfo] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun versionInfo(versionInfo: JsonField) = apply { + this.versionInfo = versionInfo + } + + /** The video codec used in the video (only for video). */ + fun videoCodec(videoCodec: String) = videoCodec(JsonField.of(videoCodec)) + + /** + * Sets [Builder.videoCodec] to an arbitrary JSON value. + * + * You should usually call [Builder.videoCodec] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun videoCodec(videoCodec: JsonField) = apply { this.videoCodec = videoCodec } + + /** Width of the image in pixels (Only for Images) */ + fun width(width: Double) = width(JsonField.of(width)) + + /** + * Sets [Builder.width] to an arbitrary JSON value. + * + * You should usually call [Builder.width] with a well-typed [Double] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun width(width: JsonField) = apply { this.width = width } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [FileUploadResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): FileUploadResponse = + FileUploadResponse( + (aiTags ?: JsonMissing.of()).map { it.toImmutable() }, + audioCodec, + bitRate, + customCoordinates, + customMetadata, + description, + duration, + embeddedMetadata, + extensionStatus, + fileId, + filePath, + fileType, + height, + isPrivateFile, + isPublished, + metadata, + name, + size, + (tags ?: JsonMissing.of()).map { it.toImmutable() }, + thumbnailUrl, + url, + versionInfo, + videoCodec, + width, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): FileUploadResponse = apply { + if (validated) { + return@apply + } + + aiTags().ifPresent { it.forEach { it.validate() } } + audioCodec() + bitRate() + customCoordinates() + customMetadata().ifPresent { it.validate() } + description() + duration() + embeddedMetadata().ifPresent { it.validate() } + extensionStatus().ifPresent { it.validate() } + fileId() + filePath() + fileType() + height() + isPrivateFile() + isPublished() + metadata().ifPresent { it.validate() } + name() + size() + tags() + thumbnailUrl() + url() + versionInfo().ifPresent { it.validate() } + videoCodec() + width() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (aiTags.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + (if (audioCodec.asKnown().isPresent) 1 else 0) + + (if (bitRate.asKnown().isPresent) 1 else 0) + + (if (customCoordinates.asKnown().isPresent) 1 else 0) + + (customMetadata.asKnown().getOrNull()?.validity() ?: 0) + + (if (description.asKnown().isPresent) 1 else 0) + + (if (duration.asKnown().isPresent) 1 else 0) + + (embeddedMetadata.asKnown().getOrNull()?.validity() ?: 0) + + (extensionStatus.asKnown().getOrNull()?.validity() ?: 0) + + (if (fileId.asKnown().isPresent) 1 else 0) + + (if (filePath.asKnown().isPresent) 1 else 0) + + (if (fileType.asKnown().isPresent) 1 else 0) + + (if (height.asKnown().isPresent) 1 else 0) + + (if (isPrivateFile.asKnown().isPresent) 1 else 0) + + (if (isPublished.asKnown().isPresent) 1 else 0) + + (metadata.asKnown().getOrNull()?.validity() ?: 0) + + (if (name.asKnown().isPresent) 1 else 0) + + (if (size.asKnown().isPresent) 1 else 0) + + (tags.asKnown().getOrNull()?.size ?: 0) + + (if (thumbnailUrl.asKnown().isPresent) 1 else 0) + + (if (url.asKnown().isPresent) 1 else 0) + + (versionInfo.asKnown().getOrNull()?.validity() ?: 0) + + (if (videoCodec.asKnown().isPresent) 1 else 0) + + (if (width.asKnown().isPresent) 1 else 0) + + class AiTag + private constructor( + private val confidence: JsonField, + private val name: JsonField, + private val source: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("confidence") + @ExcludeMissing + confidence: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("source") @ExcludeMissing source: JsonField = JsonMissing.of(), + ) : this(confidence, name, source, mutableMapOf()) + + /** + * Confidence score of the tag. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun confidence(): Optional = confidence.getOptional("confidence") + + /** + * Name of the tag. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun name(): Optional = name.getOptional("name") + + /** + * Array of `AITags` associated with the image. If no `AITags` are set, it will be null. + * These tags can be added using the `google-auto-tagging` or `aws-auto-tagging` extensions. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun source(): Optional = source.getOptional("source") + + /** + * Returns the raw JSON value of [confidence]. + * + * Unlike [confidence], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("confidence") + @ExcludeMissing + fun _confidence(): JsonField = confidence + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + + /** + * Returns the raw JSON value of [source]. + * + * Unlike [source], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("source") @ExcludeMissing fun _source(): JsonField = source + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [AiTag]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [AiTag]. */ + class Builder internal constructor() { + + private var confidence: JsonField = JsonMissing.of() + private var name: JsonField = JsonMissing.of() + private var source: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(aiTag: AiTag) = apply { + confidence = aiTag.confidence + name = aiTag.name + source = aiTag.source + additionalProperties = aiTag.additionalProperties.toMutableMap() + } + + /** Confidence score of the tag. */ + fun confidence(confidence: Double) = confidence(JsonField.of(confidence)) + + /** + * Sets [Builder.confidence] to an arbitrary JSON value. + * + * You should usually call [Builder.confidence] with a well-typed [Double] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun confidence(confidence: JsonField) = apply { this.confidence = confidence } + + /** Name of the tag. */ + fun name(name: String) = name(JsonField.of(name)) + + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun name(name: JsonField) = apply { this.name = name } + + /** + * Array of `AITags` associated with the image. If no `AITags` are set, it will be null. + * These tags can be added using the `google-auto-tagging` or `aws-auto-tagging` + * extensions. + */ + fun source(source: String) = source(JsonField.of(source)) + + /** + * Sets [Builder.source] to an arbitrary JSON value. + * + * You should usually call [Builder.source] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun source(source: JsonField) = apply { this.source = source } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [AiTag]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): AiTag = + AiTag(confidence, name, source, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): AiTag = apply { + if (validated) { + return@apply + } + + confidence() + name() + source() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (confidence.asKnown().isPresent) 1 else 0) + + (if (name.asKnown().isPresent) 1 else 0) + + (if (source.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is AiTag && + confidence == other.confidence && + name == other.name && + source == other.source && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(confidence, name, source, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "AiTag{confidence=$confidence, name=$name, source=$source, additionalProperties=$additionalProperties}" + } + + /** + * A key-value data associated with the asset. Use `responseField` in API request to get + * `customMetadata` in the upload API response. Before setting any custom metadata on an asset, + * you have to create the field using custom metadata fields API. Send `customMetadata` in + * `responseFields` in API request to get the value of this field. + */ + class CustomMetadata + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [CustomMetadata]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [CustomMetadata]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(customMetadata: CustomMetadata) = apply { + additionalProperties = customMetadata.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [CustomMetadata]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): CustomMetadata = CustomMetadata(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): CustomMetadata = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is CustomMetadata && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "CustomMetadata{additionalProperties=$additionalProperties}" + } + + /** + * Consolidated embedded metadata associated with the file. It includes exif, iptc, and xmp + * data. Send `embeddedMetadata` in `responseFields` in API request to get embeddedMetadata in + * the upload API response. + */ + class EmbeddedMetadata + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [EmbeddedMetadata]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [EmbeddedMetadata]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(embeddedMetadata: EmbeddedMetadata) = apply { + additionalProperties = embeddedMetadata.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [EmbeddedMetadata]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): EmbeddedMetadata = EmbeddedMetadata(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): EmbeddedMetadata = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is EmbeddedMetadata && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "EmbeddedMetadata{additionalProperties=$additionalProperties}" + } + + /** + * Extension names with their processing status at the time of completion of the request. It + * could have one of the following status values: + * + * `success`: The extension has been successfully applied. `failed`: The extension has failed + * and will not be retried. `pending`: The extension will finish processing in some time. On + * completion, the final status (success / failed) will be sent to the `webhookUrl` provided. + * + * If no extension was requested, then this parameter is not returned. + */ + class ExtensionStatus + private constructor( + private val aiAutoDescription: JsonField, + private val awsAutoTagging: JsonField, + private val googleAutoTagging: JsonField, + private val removeBg: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("ai-auto-description") + @ExcludeMissing + aiAutoDescription: JsonField = JsonMissing.of(), + @JsonProperty("aws-auto-tagging") + @ExcludeMissing + awsAutoTagging: JsonField = JsonMissing.of(), + @JsonProperty("google-auto-tagging") + @ExcludeMissing + googleAutoTagging: JsonField = JsonMissing.of(), + @JsonProperty("remove-bg") + @ExcludeMissing + removeBg: JsonField = JsonMissing.of(), + ) : this(aiAutoDescription, awsAutoTagging, googleAutoTagging, removeBg, mutableMapOf()) + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun aiAutoDescription(): Optional = + aiAutoDescription.getOptional("ai-auto-description") + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun awsAutoTagging(): Optional = + awsAutoTagging.getOptional("aws-auto-tagging") + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun googleAutoTagging(): Optional = + googleAutoTagging.getOptional("google-auto-tagging") + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun removeBg(): Optional = removeBg.getOptional("remove-bg") + + /** + * Returns the raw JSON value of [aiAutoDescription]. + * + * Unlike [aiAutoDescription], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("ai-auto-description") + @ExcludeMissing + fun _aiAutoDescription(): JsonField = aiAutoDescription + + /** + * Returns the raw JSON value of [awsAutoTagging]. + * + * Unlike [awsAutoTagging], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("aws-auto-tagging") + @ExcludeMissing + fun _awsAutoTagging(): JsonField = awsAutoTagging + + /** + * Returns the raw JSON value of [googleAutoTagging]. + * + * Unlike [googleAutoTagging], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("google-auto-tagging") + @ExcludeMissing + fun _googleAutoTagging(): JsonField = googleAutoTagging + + /** + * Returns the raw JSON value of [removeBg]. + * + * Unlike [removeBg], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("remove-bg") @ExcludeMissing fun _removeBg(): JsonField = removeBg + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [ExtensionStatus]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ExtensionStatus]. */ + class Builder internal constructor() { + + private var aiAutoDescription: JsonField = JsonMissing.of() + private var awsAutoTagging: JsonField = JsonMissing.of() + private var googleAutoTagging: JsonField = JsonMissing.of() + private var removeBg: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(extensionStatus: ExtensionStatus) = apply { + aiAutoDescription = extensionStatus.aiAutoDescription + awsAutoTagging = extensionStatus.awsAutoTagging + googleAutoTagging = extensionStatus.googleAutoTagging + removeBg = extensionStatus.removeBg + additionalProperties = extensionStatus.additionalProperties.toMutableMap() + } + + fun aiAutoDescription(aiAutoDescription: AiAutoDescription) = + aiAutoDescription(JsonField.of(aiAutoDescription)) + + /** + * Sets [Builder.aiAutoDescription] to an arbitrary JSON value. + * + * You should usually call [Builder.aiAutoDescription] with a well-typed + * [AiAutoDescription] value instead. This method is primarily for setting the field to + * an undocumented or not yet supported value. + */ + fun aiAutoDescription(aiAutoDescription: JsonField) = apply { + this.aiAutoDescription = aiAutoDescription + } + + fun awsAutoTagging(awsAutoTagging: AwsAutoTagging) = + awsAutoTagging(JsonField.of(awsAutoTagging)) + + /** + * Sets [Builder.awsAutoTagging] to an arbitrary JSON value. + * + * You should usually call [Builder.awsAutoTagging] with a well-typed [AwsAutoTagging] + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun awsAutoTagging(awsAutoTagging: JsonField) = apply { + this.awsAutoTagging = awsAutoTagging + } + + fun googleAutoTagging(googleAutoTagging: GoogleAutoTagging) = + googleAutoTagging(JsonField.of(googleAutoTagging)) + + /** + * Sets [Builder.googleAutoTagging] to an arbitrary JSON value. + * + * You should usually call [Builder.googleAutoTagging] with a well-typed + * [GoogleAutoTagging] value instead. This method is primarily for setting the field to + * an undocumented or not yet supported value. + */ + fun googleAutoTagging(googleAutoTagging: JsonField) = apply { + this.googleAutoTagging = googleAutoTagging + } + + fun removeBg(removeBg: RemoveBg) = removeBg(JsonField.of(removeBg)) + + /** + * Sets [Builder.removeBg] to an arbitrary JSON value. + * + * You should usually call [Builder.removeBg] with a well-typed [RemoveBg] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun removeBg(removeBg: JsonField) = apply { this.removeBg = removeBg } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ExtensionStatus]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): ExtensionStatus = + ExtensionStatus( + aiAutoDescription, + awsAutoTagging, + googleAutoTagging, + removeBg, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): ExtensionStatus = apply { + if (validated) { + return@apply + } + + aiAutoDescription().ifPresent { it.validate() } + awsAutoTagging().ifPresent { it.validate() } + googleAutoTagging().ifPresent { it.validate() } + removeBg().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (aiAutoDescription.asKnown().getOrNull()?.validity() ?: 0) + + (awsAutoTagging.asKnown().getOrNull()?.validity() ?: 0) + + (googleAutoTagging.asKnown().getOrNull()?.validity() ?: 0) + + (removeBg.asKnown().getOrNull()?.validity() ?: 0) + + class AiAutoDescription + @JsonCreator + private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is + * on an older version than the API, then the API may respond with new members that the + * SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val SUCCESS = of("success") + + @JvmField val PENDING = of("pending") + + @JvmField val FAILED = of("failed") + + @JvmStatic fun of(value: String) = AiAutoDescription(JsonField.of(value)) + } + + /** An enum containing [AiAutoDescription]'s known values. */ + enum class Known { + SUCCESS, + PENDING, + FAILED, + } + + /** + * An enum containing [AiAutoDescription]'s known values, as well as an [_UNKNOWN] + * member. + * + * An instance of [AiAutoDescription] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if + * the SDK is on an older version than the API, then the API may respond with new + * members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + SUCCESS, + PENDING, + FAILED, + /** + * An enum member indicating that [AiAutoDescription] was instantiated with an + * unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you + * want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + SUCCESS -> Value.SUCCESS + PENDING -> Value.PENDING + FAILED -> Value.FAILED + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and + * don't want to throw for the unknown case. + * + * @throws ImageKitInvalidDataException if this class instance's value is a not a known + * member. + */ + fun known(): Known = + when (this) { + SUCCESS -> Known.SUCCESS + PENDING -> Known.PENDING + FAILED -> Known.FAILED + else -> throw ImageKitInvalidDataException("Unknown AiAutoDescription: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for + * debugging and generally doesn't throw. + * + * @throws ImageKitInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + ImageKitInvalidDataException("Value is not a String") + } + + private var validated: Boolean = false + + fun validate(): AiAutoDescription = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is AiAutoDescription && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + class AwsAutoTagging + @JsonCreator + private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is + * on an older version than the API, then the API may respond with new members that the + * SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val SUCCESS = of("success") + + @JvmField val PENDING = of("pending") + + @JvmField val FAILED = of("failed") + + @JvmStatic fun of(value: String) = AwsAutoTagging(JsonField.of(value)) + } + + /** An enum containing [AwsAutoTagging]'s known values. */ + enum class Known { + SUCCESS, + PENDING, + FAILED, + } + + /** + * An enum containing [AwsAutoTagging]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [AwsAutoTagging] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if + * the SDK is on an older version than the API, then the API may respond with new + * members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + SUCCESS, + PENDING, + FAILED, + /** + * An enum member indicating that [AwsAutoTagging] was instantiated with an unknown + * value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you + * want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + SUCCESS -> Value.SUCCESS + PENDING -> Value.PENDING + FAILED -> Value.FAILED + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and + * don't want to throw for the unknown case. + * + * @throws ImageKitInvalidDataException if this class instance's value is a not a known + * member. + */ + fun known(): Known = + when (this) { + SUCCESS -> Known.SUCCESS + PENDING -> Known.PENDING + FAILED -> Known.FAILED + else -> throw ImageKitInvalidDataException("Unknown AwsAutoTagging: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for + * debugging and generally doesn't throw. + * + * @throws ImageKitInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + ImageKitInvalidDataException("Value is not a String") + } + + private var validated: Boolean = false + + fun validate(): AwsAutoTagging = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is AwsAutoTagging && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + class GoogleAutoTagging + @JsonCreator + private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is + * on an older version than the API, then the API may respond with new members that the + * SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val SUCCESS = of("success") + + @JvmField val PENDING = of("pending") + + @JvmField val FAILED = of("failed") + + @JvmStatic fun of(value: String) = GoogleAutoTagging(JsonField.of(value)) + } + + /** An enum containing [GoogleAutoTagging]'s known values. */ + enum class Known { + SUCCESS, + PENDING, + FAILED, + } + + /** + * An enum containing [GoogleAutoTagging]'s known values, as well as an [_UNKNOWN] + * member. + * + * An instance of [GoogleAutoTagging] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if + * the SDK is on an older version than the API, then the API may respond with new + * members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + SUCCESS, + PENDING, + FAILED, + /** + * An enum member indicating that [GoogleAutoTagging] was instantiated with an + * unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you + * want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + SUCCESS -> Value.SUCCESS + PENDING -> Value.PENDING + FAILED -> Value.FAILED + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and + * don't want to throw for the unknown case. + * + * @throws ImageKitInvalidDataException if this class instance's value is a not a known + * member. + */ + fun known(): Known = + when (this) { + SUCCESS -> Known.SUCCESS + PENDING -> Known.PENDING + FAILED -> Known.FAILED + else -> throw ImageKitInvalidDataException("Unknown GoogleAutoTagging: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for + * debugging and generally doesn't throw. + * + * @throws ImageKitInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + ImageKitInvalidDataException("Value is not a String") + } + + private var validated: Boolean = false + + fun validate(): GoogleAutoTagging = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is GoogleAutoTagging && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + class RemoveBg @JsonCreator private constructor(private val value: JsonField) : + Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is + * on an older version than the API, then the API may respond with new members that the + * SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val SUCCESS = of("success") + + @JvmField val PENDING = of("pending") + + @JvmField val FAILED = of("failed") + + @JvmStatic fun of(value: String) = RemoveBg(JsonField.of(value)) + } + + /** An enum containing [RemoveBg]'s known values. */ + enum class Known { + SUCCESS, + PENDING, + FAILED, + } + + /** + * An enum containing [RemoveBg]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [RemoveBg] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if + * the SDK is on an older version than the API, then the API may respond with new + * members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + SUCCESS, + PENDING, + FAILED, + /** + * An enum member indicating that [RemoveBg] was instantiated with an unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you + * want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + SUCCESS -> Value.SUCCESS + PENDING -> Value.PENDING + FAILED -> Value.FAILED + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and + * don't want to throw for the unknown case. + * + * @throws ImageKitInvalidDataException if this class instance's value is a not a known + * member. + */ + fun known(): Known = + when (this) { + SUCCESS -> Known.SUCCESS + PENDING -> Known.PENDING + FAILED -> Known.FAILED + else -> throw ImageKitInvalidDataException("Unknown RemoveBg: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for + * debugging and generally doesn't throw. + * + * @throws ImageKitInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + ImageKitInvalidDataException("Value is not a String") + } + + private var validated: Boolean = false + + fun validate(): RemoveBg = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is RemoveBg && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ExtensionStatus && + aiAutoDescription == other.aiAutoDescription && + awsAutoTagging == other.awsAutoTagging && + googleAutoTagging == other.googleAutoTagging && + removeBg == other.removeBg && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + aiAutoDescription, + awsAutoTagging, + googleAutoTagging, + removeBg, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ExtensionStatus{aiAutoDescription=$aiAutoDescription, awsAutoTagging=$awsAutoTagging, googleAutoTagging=$googleAutoTagging, removeBg=$removeBg, additionalProperties=$additionalProperties}" + } + + /** An object containing the file or file version's `id` (versionId) and `name`. */ + class VersionInfo + private constructor( + private val id: JsonField, + private val name: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + ) : this(id, name, mutableMapOf()) + + /** + * Unique identifier of the file version. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun id(): Optional = id.getOptional("id") + + /** + * Name of the file version. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun name(): Optional = name.getOptional("name") + + /** + * Returns the raw JSON value of [id]. + * + * Unlike [id], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [VersionInfo]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [VersionInfo]. */ + class Builder internal constructor() { + + private var id: JsonField = JsonMissing.of() + private var name: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(versionInfo: VersionInfo) = apply { + id = versionInfo.id + name = versionInfo.name + additionalProperties = versionInfo.additionalProperties.toMutableMap() + } + + /** Unique identifier of the file version. */ + fun id(id: String) = id(JsonField.of(id)) + + /** + * Sets [Builder.id] to an arbitrary JSON value. + * + * You should usually call [Builder.id] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun id(id: JsonField) = apply { this.id = id } + + /** Name of the file version. */ + fun name(name: String) = name(JsonField.of(name)) + + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun name(name: JsonField) = apply { this.name = name } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [VersionInfo]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): VersionInfo = VersionInfo(id, name, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): VersionInfo = apply { + if (validated) { + return@apply + } + + id() + name() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (id.asKnown().isPresent) 1 else 0) + (if (name.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is VersionInfo && + id == other.id && + name == other.name && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(id, name, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "VersionInfo{id=$id, name=$name, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is FileUploadResponse && + aiTags == other.aiTags && + audioCodec == other.audioCodec && + bitRate == other.bitRate && + customCoordinates == other.customCoordinates && + customMetadata == other.customMetadata && + description == other.description && + duration == other.duration && + embeddedMetadata == other.embeddedMetadata && + extensionStatus == other.extensionStatus && + fileId == other.fileId && + filePath == other.filePath && + fileType == other.fileType && + height == other.height && + isPrivateFile == other.isPrivateFile && + isPublished == other.isPublished && + metadata == other.metadata && + name == other.name && + size == other.size && + tags == other.tags && + thumbnailUrl == other.thumbnailUrl && + url == other.url && + versionInfo == other.versionInfo && + videoCodec == other.videoCodec && + width == other.width && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + aiTags, + audioCodec, + bitRate, + customCoordinates, + customMetadata, + description, + duration, + embeddedMetadata, + extensionStatus, + fileId, + filePath, + fileType, + height, + isPrivateFile, + isPublished, + metadata, + name, + size, + tags, + thumbnailUrl, + url, + versionInfo, + videoCodec, + width, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "FileUploadResponse{aiTags=$aiTags, audioCodec=$audioCodec, bitRate=$bitRate, customCoordinates=$customCoordinates, customMetadata=$customMetadata, description=$description, duration=$duration, embeddedMetadata=$embeddedMetadata, extensionStatus=$extensionStatus, fileId=$fileId, filePath=$filePath, fileType=$fileType, height=$height, isPrivateFile=$isPrivateFile, isPublished=$isPublished, metadata=$metadata, name=$name, size=$size, tags=$tags, thumbnailUrl=$thumbnailUrl, url=$url, versionInfo=$versionInfo, videoCodec=$videoCodec, width=$width, additionalProperties=$additionalProperties}" +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/files/Folder.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/files/Folder.kt new file mode 100644 index 0000000..3e7c9a3 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/files/Folder.kt @@ -0,0 +1,478 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.files + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.imagekit.api.core.Enum +import com.imagekit.api.core.ExcludeMissing +import com.imagekit.api.core.JsonField +import com.imagekit.api.core.JsonMissing +import com.imagekit.api.core.JsonValue +import com.imagekit.api.errors.ImageKitInvalidDataException +import java.time.OffsetDateTime +import java.util.Collections +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +class Folder +private constructor( + private val createdAt: JsonField, + private val folderId: JsonField, + private val folderPath: JsonField, + private val name: JsonField, + private val type: JsonField, + private val updatedAt: JsonField, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("createdAt") + @ExcludeMissing + createdAt: JsonField = JsonMissing.of(), + @JsonProperty("folderId") @ExcludeMissing folderId: JsonField = JsonMissing.of(), + @JsonProperty("folderPath") + @ExcludeMissing + folderPath: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonField = JsonMissing.of(), + @JsonProperty("updatedAt") + @ExcludeMissing + updatedAt: JsonField = JsonMissing.of(), + ) : this(createdAt, folderId, folderPath, name, type, updatedAt, mutableMapOf()) + + /** + * Date and time when the folder was created. The date and time is in ISO8601 format. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun createdAt(): Optional = createdAt.getOptional("createdAt") + + /** + * Unique identifier of the asset. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun folderId(): Optional = folderId.getOptional("folderId") + + /** + * Path of the folder. This is the path you would use in the URL to access the folder. For + * example, if the folder is at the root of the media library, the path will be /folder. If the + * folder is inside another folder named images, the path will be /images/folder. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun folderPath(): Optional = folderPath.getOptional("folderPath") + + /** + * Name of the asset. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun name(): Optional = name.getOptional("name") + + /** + * Type of the asset. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun type(): Optional = type.getOptional("type") + + /** + * Date and time when the folder was last updated. The date and time is in ISO8601 format. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun updatedAt(): Optional = updatedAt.getOptional("updatedAt") + + /** + * Returns the raw JSON value of [createdAt]. + * + * Unlike [createdAt], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("createdAt") + @ExcludeMissing + fun _createdAt(): JsonField = createdAt + + /** + * Returns the raw JSON value of [folderId]. + * + * Unlike [folderId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("folderId") @ExcludeMissing fun _folderId(): JsonField = folderId + + /** + * Returns the raw JSON value of [folderPath]. + * + * Unlike [folderPath], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("folderPath") @ExcludeMissing fun _folderPath(): JsonField = folderPath + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + + /** + * Returns the raw JSON value of [updatedAt]. + * + * Unlike [updatedAt], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("updatedAt") + @ExcludeMissing + fun _updatedAt(): JsonField = updatedAt + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Folder]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Folder]. */ + class Builder internal constructor() { + + private var createdAt: JsonField = JsonMissing.of() + private var folderId: JsonField = JsonMissing.of() + private var folderPath: JsonField = JsonMissing.of() + private var name: JsonField = JsonMissing.of() + private var type: JsonField = JsonMissing.of() + private var updatedAt: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(folder: Folder) = apply { + createdAt = folder.createdAt + folderId = folder.folderId + folderPath = folder.folderPath + name = folder.name + type = folder.type + updatedAt = folder.updatedAt + additionalProperties = folder.additionalProperties.toMutableMap() + } + + /** Date and time when the folder was created. The date and time is in ISO8601 format. */ + fun createdAt(createdAt: OffsetDateTime) = createdAt(JsonField.of(createdAt)) + + /** + * Sets [Builder.createdAt] to an arbitrary JSON value. + * + * You should usually call [Builder.createdAt] with a well-typed [OffsetDateTime] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun createdAt(createdAt: JsonField) = apply { this.createdAt = createdAt } + + /** Unique identifier of the asset. */ + fun folderId(folderId: String) = folderId(JsonField.of(folderId)) + + /** + * Sets [Builder.folderId] to an arbitrary JSON value. + * + * You should usually call [Builder.folderId] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun folderId(folderId: JsonField) = apply { this.folderId = folderId } + + /** + * Path of the folder. This is the path you would use in the URL to access the folder. For + * example, if the folder is at the root of the media library, the path will be /folder. If + * the folder is inside another folder named images, the path will be /images/folder. + */ + fun folderPath(folderPath: String) = folderPath(JsonField.of(folderPath)) + + /** + * Sets [Builder.folderPath] to an arbitrary JSON value. + * + * You should usually call [Builder.folderPath] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun folderPath(folderPath: JsonField) = apply { this.folderPath = folderPath } + + /** Name of the asset. */ + fun name(name: String) = name(JsonField.of(name)) + + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun name(name: JsonField) = apply { this.name = name } + + /** Type of the asset. */ + fun type(type: Type) = type(JsonField.of(type)) + + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [Type] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun type(type: JsonField) = apply { this.type = type } + + /** + * Date and time when the folder was last updated. The date and time is in ISO8601 format. + */ + fun updatedAt(updatedAt: OffsetDateTime) = updatedAt(JsonField.of(updatedAt)) + + /** + * Sets [Builder.updatedAt] to an arbitrary JSON value. + * + * You should usually call [Builder.updatedAt] with a well-typed [OffsetDateTime] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun updatedAt(updatedAt: JsonField) = apply { this.updatedAt = updatedAt } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Folder]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Folder = + Folder( + createdAt, + folderId, + folderPath, + name, + type, + updatedAt, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Folder = apply { + if (validated) { + return@apply + } + + createdAt() + folderId() + folderPath() + name() + type().ifPresent { it.validate() } + updatedAt() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (createdAt.asKnown().isPresent) 1 else 0) + + (if (folderId.asKnown().isPresent) 1 else 0) + + (if (folderPath.asKnown().isPresent) 1 else 0) + + (if (name.asKnown().isPresent) 1 else 0) + + (type.asKnown().getOrNull()?.validity() ?: 0) + + (if (updatedAt.asKnown().isPresent) 1 else 0) + + /** Type of the asset. */ + class Type @JsonCreator private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is on an + * older version than the API, then the API may respond with new members that the SDK is + * unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val FOLDER = of("folder") + + @JvmStatic fun of(value: String) = Type(JsonField.of(value)) + } + + /** An enum containing [Type]'s known values. */ + enum class Known { + FOLDER + } + + /** + * An enum containing [Type]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [Type] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if the + * SDK is on an older version than the API, then the API may respond with new members that + * the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + FOLDER, + /** An enum member indicating that [Type] was instantiated with an unknown value. */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] + * if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you want + * to throw for the unknown case. + */ + fun value(): Value = + when (this) { + FOLDER -> Value.FOLDER + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and don't + * want to throw for the unknown case. + * + * @throws ImageKitInvalidDataException if this class instance's value is a not a known + * member. + */ + fun known(): Known = + when (this) { + FOLDER -> Known.FOLDER + else -> throw ImageKitInvalidDataException("Unknown Type: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for debugging + * and generally doesn't throw. + * + * @throws ImageKitInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + ImageKitInvalidDataException("Value is not a String") + } + + private var validated: Boolean = false + + fun validate(): Type = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Type && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Folder && + createdAt == other.createdAt && + folderId == other.folderId && + folderPath == other.folderPath && + name == other.name && + type == other.type && + updatedAt == other.updatedAt && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(createdAt, folderId, folderPath, name, type, updatedAt, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Folder{createdAt=$createdAt, folderId=$folderId, folderPath=$folderPath, name=$name, type=$type, updatedAt=$updatedAt, additionalProperties=$additionalProperties}" +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/files/Metadata.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/files/Metadata.kt new file mode 100644 index 0000000..69891ec --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/files/Metadata.kt @@ -0,0 +1,3574 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.files + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.imagekit.api.core.ExcludeMissing +import com.imagekit.api.core.JsonField +import com.imagekit.api.core.JsonMissing +import com.imagekit.api.core.JsonValue +import com.imagekit.api.core.checkKnown +import com.imagekit.api.core.toImmutable +import com.imagekit.api.errors.ImageKitInvalidDataException +import java.util.Collections +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** JSON object containing metadata. */ +class Metadata +private constructor( + private val audioCodec: JsonField, + private val bitRate: JsonField, + private val density: JsonField, + private val duration: JsonField, + private val exif: JsonField, + private val format: JsonField, + private val hasColorProfile: JsonField, + private val hasTransparency: JsonField, + private val height: JsonField, + private val pHash: JsonField, + private val quality: JsonField, + private val size: JsonField, + private val videoCodec: JsonField, + private val width: JsonField, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("audioCodec") + @ExcludeMissing + audioCodec: JsonField = JsonMissing.of(), + @JsonProperty("bitRate") @ExcludeMissing bitRate: JsonField = JsonMissing.of(), + @JsonProperty("density") @ExcludeMissing density: JsonField = JsonMissing.of(), + @JsonProperty("duration") @ExcludeMissing duration: JsonField = JsonMissing.of(), + @JsonProperty("exif") @ExcludeMissing exif: JsonField = JsonMissing.of(), + @JsonProperty("format") @ExcludeMissing format: JsonField = JsonMissing.of(), + @JsonProperty("hasColorProfile") + @ExcludeMissing + hasColorProfile: JsonField = JsonMissing.of(), + @JsonProperty("hasTransparency") + @ExcludeMissing + hasTransparency: JsonField = JsonMissing.of(), + @JsonProperty("height") @ExcludeMissing height: JsonField = JsonMissing.of(), + @JsonProperty("pHash") @ExcludeMissing pHash: JsonField = JsonMissing.of(), + @JsonProperty("quality") @ExcludeMissing quality: JsonField = JsonMissing.of(), + @JsonProperty("size") @ExcludeMissing size: JsonField = JsonMissing.of(), + @JsonProperty("videoCodec") + @ExcludeMissing + videoCodec: JsonField = JsonMissing.of(), + @JsonProperty("width") @ExcludeMissing width: JsonField = JsonMissing.of(), + ) : this( + audioCodec, + bitRate, + density, + duration, + exif, + format, + hasColorProfile, + hasTransparency, + height, + pHash, + quality, + size, + videoCodec, + width, + mutableMapOf(), + ) + + /** + * The audio codec used in the video (only for video). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun audioCodec(): Optional = audioCodec.getOptional("audioCodec") + + /** + * The bit rate of the video in kbps (only for video). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun bitRate(): Optional = bitRate.getOptional("bitRate") + + /** + * The density of the image in DPI. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun density(): Optional = density.getOptional("density") + + /** + * The duration of the video in seconds (only for video). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun duration(): Optional = duration.getOptional("duration") + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun exif(): Optional = exif.getOptional("exif") + + /** + * The format of the file (e.g., 'jpg', 'mp4'). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun format(): Optional = format.getOptional("format") + + /** + * Indicates if the image has a color profile. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun hasColorProfile(): Optional = hasColorProfile.getOptional("hasColorProfile") + + /** + * Indicates if the image contains transparent areas. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun hasTransparency(): Optional = hasTransparency.getOptional("hasTransparency") + + /** + * The height of the image or video in pixels. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun height(): Optional = height.getOptional("height") + + /** + * Perceptual hash of the image. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun pHash(): Optional = pHash.getOptional("pHash") + + /** + * The quality indicator of the image. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun quality(): Optional = quality.getOptional("quality") + + /** + * The file size in bytes. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun size(): Optional = size.getOptional("size") + + /** + * The video codec used in the video (only for video). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun videoCodec(): Optional = videoCodec.getOptional("videoCodec") + + /** + * The width of the image or video in pixels. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun width(): Optional = width.getOptional("width") + + /** + * Returns the raw JSON value of [audioCodec]. + * + * Unlike [audioCodec], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("audioCodec") @ExcludeMissing fun _audioCodec(): JsonField = audioCodec + + /** + * Returns the raw JSON value of [bitRate]. + * + * Unlike [bitRate], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("bitRate") @ExcludeMissing fun _bitRate(): JsonField = bitRate + + /** + * Returns the raw JSON value of [density]. + * + * Unlike [density], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("density") @ExcludeMissing fun _density(): JsonField = density + + /** + * Returns the raw JSON value of [duration]. + * + * Unlike [duration], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("duration") @ExcludeMissing fun _duration(): JsonField = duration + + /** + * Returns the raw JSON value of [exif]. + * + * Unlike [exif], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("exif") @ExcludeMissing fun _exif(): JsonField = exif + + /** + * Returns the raw JSON value of [format]. + * + * Unlike [format], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("format") @ExcludeMissing fun _format(): JsonField = format + + /** + * Returns the raw JSON value of [hasColorProfile]. + * + * Unlike [hasColorProfile], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("hasColorProfile") + @ExcludeMissing + fun _hasColorProfile(): JsonField = hasColorProfile + + /** + * Returns the raw JSON value of [hasTransparency]. + * + * Unlike [hasTransparency], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("hasTransparency") + @ExcludeMissing + fun _hasTransparency(): JsonField = hasTransparency + + /** + * Returns the raw JSON value of [height]. + * + * Unlike [height], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("height") @ExcludeMissing fun _height(): JsonField = height + + /** + * Returns the raw JSON value of [pHash]. + * + * Unlike [pHash], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("pHash") @ExcludeMissing fun _pHash(): JsonField = pHash + + /** + * Returns the raw JSON value of [quality]. + * + * Unlike [quality], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("quality") @ExcludeMissing fun _quality(): JsonField = quality + + /** + * Returns the raw JSON value of [size]. + * + * Unlike [size], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("size") @ExcludeMissing fun _size(): JsonField = size + + /** + * Returns the raw JSON value of [videoCodec]. + * + * Unlike [videoCodec], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("videoCodec") @ExcludeMissing fun _videoCodec(): JsonField = videoCodec + + /** + * Returns the raw JSON value of [width]. + * + * Unlike [width], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("width") @ExcludeMissing fun _width(): JsonField = width + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Metadata]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Metadata]. */ + class Builder internal constructor() { + + private var audioCodec: JsonField = JsonMissing.of() + private var bitRate: JsonField = JsonMissing.of() + private var density: JsonField = JsonMissing.of() + private var duration: JsonField = JsonMissing.of() + private var exif: JsonField = JsonMissing.of() + private var format: JsonField = JsonMissing.of() + private var hasColorProfile: JsonField = JsonMissing.of() + private var hasTransparency: JsonField = JsonMissing.of() + private var height: JsonField = JsonMissing.of() + private var pHash: JsonField = JsonMissing.of() + private var quality: JsonField = JsonMissing.of() + private var size: JsonField = JsonMissing.of() + private var videoCodec: JsonField = JsonMissing.of() + private var width: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(metadata: Metadata) = apply { + audioCodec = metadata.audioCodec + bitRate = metadata.bitRate + density = metadata.density + duration = metadata.duration + exif = metadata.exif + format = metadata.format + hasColorProfile = metadata.hasColorProfile + hasTransparency = metadata.hasTransparency + height = metadata.height + pHash = metadata.pHash + quality = metadata.quality + size = metadata.size + videoCodec = metadata.videoCodec + width = metadata.width + additionalProperties = metadata.additionalProperties.toMutableMap() + } + + /** The audio codec used in the video (only for video). */ + fun audioCodec(audioCodec: String) = audioCodec(JsonField.of(audioCodec)) + + /** + * Sets [Builder.audioCodec] to an arbitrary JSON value. + * + * You should usually call [Builder.audioCodec] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun audioCodec(audioCodec: JsonField) = apply { this.audioCodec = audioCodec } + + /** The bit rate of the video in kbps (only for video). */ + fun bitRate(bitRate: Long) = bitRate(JsonField.of(bitRate)) + + /** + * Sets [Builder.bitRate] to an arbitrary JSON value. + * + * You should usually call [Builder.bitRate] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun bitRate(bitRate: JsonField) = apply { this.bitRate = bitRate } + + /** The density of the image in DPI. */ + fun density(density: Long) = density(JsonField.of(density)) + + /** + * Sets [Builder.density] to an arbitrary JSON value. + * + * You should usually call [Builder.density] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun density(density: JsonField) = apply { this.density = density } + + /** The duration of the video in seconds (only for video). */ + fun duration(duration: Long) = duration(JsonField.of(duration)) + + /** + * Sets [Builder.duration] to an arbitrary JSON value. + * + * You should usually call [Builder.duration] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun duration(duration: JsonField) = apply { this.duration = duration } + + fun exif(exif: Exif) = exif(JsonField.of(exif)) + + /** + * Sets [Builder.exif] to an arbitrary JSON value. + * + * You should usually call [Builder.exif] with a well-typed [Exif] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun exif(exif: JsonField) = apply { this.exif = exif } + + /** The format of the file (e.g., 'jpg', 'mp4'). */ + fun format(format: String) = format(JsonField.of(format)) + + /** + * Sets [Builder.format] to an arbitrary JSON value. + * + * You should usually call [Builder.format] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun format(format: JsonField) = apply { this.format = format } + + /** Indicates if the image has a color profile. */ + fun hasColorProfile(hasColorProfile: Boolean) = + hasColorProfile(JsonField.of(hasColorProfile)) + + /** + * Sets [Builder.hasColorProfile] to an arbitrary JSON value. + * + * You should usually call [Builder.hasColorProfile] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun hasColorProfile(hasColorProfile: JsonField) = apply { + this.hasColorProfile = hasColorProfile + } + + /** Indicates if the image contains transparent areas. */ + fun hasTransparency(hasTransparency: Boolean) = + hasTransparency(JsonField.of(hasTransparency)) + + /** + * Sets [Builder.hasTransparency] to an arbitrary JSON value. + * + * You should usually call [Builder.hasTransparency] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun hasTransparency(hasTransparency: JsonField) = apply { + this.hasTransparency = hasTransparency + } + + /** The height of the image or video in pixels. */ + fun height(height: Long) = height(JsonField.of(height)) + + /** + * Sets [Builder.height] to an arbitrary JSON value. + * + * You should usually call [Builder.height] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun height(height: JsonField) = apply { this.height = height } + + /** Perceptual hash of the image. */ + fun pHash(pHash: String) = pHash(JsonField.of(pHash)) + + /** + * Sets [Builder.pHash] to an arbitrary JSON value. + * + * You should usually call [Builder.pHash] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun pHash(pHash: JsonField) = apply { this.pHash = pHash } + + /** The quality indicator of the image. */ + fun quality(quality: Long) = quality(JsonField.of(quality)) + + /** + * Sets [Builder.quality] to an arbitrary JSON value. + * + * You should usually call [Builder.quality] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun quality(quality: JsonField) = apply { this.quality = quality } + + /** The file size in bytes. */ + fun size(size: Long) = size(JsonField.of(size)) + + /** + * Sets [Builder.size] to an arbitrary JSON value. + * + * You should usually call [Builder.size] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun size(size: JsonField) = apply { this.size = size } + + /** The video codec used in the video (only for video). */ + fun videoCodec(videoCodec: String) = videoCodec(JsonField.of(videoCodec)) + + /** + * Sets [Builder.videoCodec] to an arbitrary JSON value. + * + * You should usually call [Builder.videoCodec] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun videoCodec(videoCodec: JsonField) = apply { this.videoCodec = videoCodec } + + /** The width of the image or video in pixels. */ + fun width(width: Long) = width(JsonField.of(width)) + + /** + * Sets [Builder.width] to an arbitrary JSON value. + * + * You should usually call [Builder.width] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun width(width: JsonField) = apply { this.width = width } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Metadata]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Metadata = + Metadata( + audioCodec, + bitRate, + density, + duration, + exif, + format, + hasColorProfile, + hasTransparency, + height, + pHash, + quality, + size, + videoCodec, + width, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Metadata = apply { + if (validated) { + return@apply + } + + audioCodec() + bitRate() + density() + duration() + exif().ifPresent { it.validate() } + format() + hasColorProfile() + hasTransparency() + height() + pHash() + quality() + size() + videoCodec() + width() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (audioCodec.asKnown().isPresent) 1 else 0) + + (if (bitRate.asKnown().isPresent) 1 else 0) + + (if (density.asKnown().isPresent) 1 else 0) + + (if (duration.asKnown().isPresent) 1 else 0) + + (exif.asKnown().getOrNull()?.validity() ?: 0) + + (if (format.asKnown().isPresent) 1 else 0) + + (if (hasColorProfile.asKnown().isPresent) 1 else 0) + + (if (hasTransparency.asKnown().isPresent) 1 else 0) + + (if (height.asKnown().isPresent) 1 else 0) + + (if (pHash.asKnown().isPresent) 1 else 0) + + (if (quality.asKnown().isPresent) 1 else 0) + + (if (size.asKnown().isPresent) 1 else 0) + + (if (videoCodec.asKnown().isPresent) 1 else 0) + + (if (width.asKnown().isPresent) 1 else 0) + + class Exif + private constructor( + private val exif: JsonField, + private val gps: JsonField, + private val image: JsonField, + private val interoperability: JsonField, + private val makernote: JsonField, + private val thumbnail: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("exif") @ExcludeMissing exif: JsonField = JsonMissing.of(), + @JsonProperty("gps") @ExcludeMissing gps: JsonField = JsonMissing.of(), + @JsonProperty("image") @ExcludeMissing image: JsonField = JsonMissing.of(), + @JsonProperty("interoperability") + @ExcludeMissing + interoperability: JsonField = JsonMissing.of(), + @JsonProperty("makernote") + @ExcludeMissing + makernote: JsonField = JsonMissing.of(), + @JsonProperty("thumbnail") + @ExcludeMissing + thumbnail: JsonField = JsonMissing.of(), + ) : this(exif, gps, image, interoperability, makernote, thumbnail, mutableMapOf()) + + /** + * Object containing Exif details. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun exif(): Optional = exif.getOptional("exif") + + /** + * Object containing GPS information. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun gps(): Optional = gps.getOptional("gps") + + /** + * Object containing EXIF image information. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun image(): Optional = image.getOptional("image") + + /** + * JSON object. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun interoperability(): Optional = + interoperability.getOptional("interoperability") + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun makernote(): Optional = makernote.getOptional("makernote") + + /** + * Object containing Thumbnail information. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun thumbnail(): Optional = thumbnail.getOptional("thumbnail") + + /** + * Returns the raw JSON value of [exif]. + * + * Unlike [exif], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("exif") @ExcludeMissing fun _exif(): JsonField = exif + + /** + * Returns the raw JSON value of [gps]. + * + * Unlike [gps], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("gps") @ExcludeMissing fun _gps(): JsonField = gps + + /** + * Returns the raw JSON value of [image]. + * + * Unlike [image], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("image") @ExcludeMissing fun _image(): JsonField = image + + /** + * Returns the raw JSON value of [interoperability]. + * + * Unlike [interoperability], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("interoperability") + @ExcludeMissing + fun _interoperability(): JsonField = interoperability + + /** + * Returns the raw JSON value of [makernote]. + * + * Unlike [makernote], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("makernote") + @ExcludeMissing + fun _makernote(): JsonField = makernote + + /** + * Returns the raw JSON value of [thumbnail]. + * + * Unlike [thumbnail], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("thumbnail") + @ExcludeMissing + fun _thumbnail(): JsonField = thumbnail + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Exif]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Exif]. */ + class Builder internal constructor() { + + private var exif: JsonField = JsonMissing.of() + private var gps: JsonField = JsonMissing.of() + private var image: JsonField = JsonMissing.of() + private var interoperability: JsonField = JsonMissing.of() + private var makernote: JsonField = JsonMissing.of() + private var thumbnail: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(exif: Exif) = apply { + this.exif = exif.exif + gps = exif.gps + image = exif.image + interoperability = exif.interoperability + makernote = exif.makernote + thumbnail = exif.thumbnail + additionalProperties = exif.additionalProperties.toMutableMap() + } + + /** Object containing Exif details. */ + fun exif(exif: InnerExif) = exif(JsonField.of(exif)) + + /** + * Sets [Builder.exif] to an arbitrary JSON value. + * + * You should usually call [Builder.exif] with a well-typed [InnerExif] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun exif(exif: JsonField) = apply { this.exif = exif } + + /** Object containing GPS information. */ + fun gps(gps: Gps) = gps(JsonField.of(gps)) + + /** + * Sets [Builder.gps] to an arbitrary JSON value. + * + * You should usually call [Builder.gps] with a well-typed [Gps] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun gps(gps: JsonField) = apply { this.gps = gps } + + /** Object containing EXIF image information. */ + fun image(image: Image) = image(JsonField.of(image)) + + /** + * Sets [Builder.image] to an arbitrary JSON value. + * + * You should usually call [Builder.image] with a well-typed [Image] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun image(image: JsonField) = apply { this.image = image } + + /** JSON object. */ + fun interoperability(interoperability: Interoperability) = + interoperability(JsonField.of(interoperability)) + + /** + * Sets [Builder.interoperability] to an arbitrary JSON value. + * + * You should usually call [Builder.interoperability] with a well-typed + * [Interoperability] value instead. This method is primarily for setting the field to + * an undocumented or not yet supported value. + */ + fun interoperability(interoperability: JsonField) = apply { + this.interoperability = interoperability + } + + fun makernote(makernote: Makernote) = makernote(JsonField.of(makernote)) + + /** + * Sets [Builder.makernote] to an arbitrary JSON value. + * + * You should usually call [Builder.makernote] with a well-typed [Makernote] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun makernote(makernote: JsonField) = apply { this.makernote = makernote } + + /** Object containing Thumbnail information. */ + fun thumbnail(thumbnail: Thumbnail) = thumbnail(JsonField.of(thumbnail)) + + /** + * Sets [Builder.thumbnail] to an arbitrary JSON value. + * + * You should usually call [Builder.thumbnail] with a well-typed [Thumbnail] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun thumbnail(thumbnail: JsonField) = apply { this.thumbnail = thumbnail } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Exif]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Exif = + Exif( + exif, + gps, + image, + interoperability, + makernote, + thumbnail, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Exif = apply { + if (validated) { + return@apply + } + + exif().ifPresent { it.validate() } + gps().ifPresent { it.validate() } + image().ifPresent { it.validate() } + interoperability().ifPresent { it.validate() } + makernote().ifPresent { it.validate() } + thumbnail().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (exif.asKnown().getOrNull()?.validity() ?: 0) + + (gps.asKnown().getOrNull()?.validity() ?: 0) + + (image.asKnown().getOrNull()?.validity() ?: 0) + + (interoperability.asKnown().getOrNull()?.validity() ?: 0) + + (makernote.asKnown().getOrNull()?.validity() ?: 0) + + (thumbnail.asKnown().getOrNull()?.validity() ?: 0) + + /** Object containing Exif details. */ + class InnerExif + private constructor( + private val apertureValue: JsonField, + private val colorSpace: JsonField, + private val createDate: JsonField, + private val customRendered: JsonField, + private val dateTimeOriginal: JsonField, + private val exifImageHeight: JsonField, + private val exifImageWidth: JsonField, + private val exifVersion: JsonField, + private val exposureCompensation: JsonField, + private val exposureMode: JsonField, + private val exposureProgram: JsonField, + private val exposureTime: JsonField, + private val flash: JsonField, + private val flashpixVersion: JsonField, + private val fNumber: JsonField, + private val focalLength: JsonField, + private val focalPlaneResolutionUnit: JsonField, + private val focalPlaneXResolution: JsonField, + private val focalPlaneYResolution: JsonField, + private val interopOffset: JsonField, + private val iso: JsonField, + private val meteringMode: JsonField, + private val sceneCaptureType: JsonField, + private val shutterSpeedValue: JsonField, + private val subSecTime: JsonField, + private val whiteBalance: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("ApertureValue") + @ExcludeMissing + apertureValue: JsonField = JsonMissing.of(), + @JsonProperty("ColorSpace") + @ExcludeMissing + colorSpace: JsonField = JsonMissing.of(), + @JsonProperty("CreateDate") + @ExcludeMissing + createDate: JsonField = JsonMissing.of(), + @JsonProperty("CustomRendered") + @ExcludeMissing + customRendered: JsonField = JsonMissing.of(), + @JsonProperty("DateTimeOriginal") + @ExcludeMissing + dateTimeOriginal: JsonField = JsonMissing.of(), + @JsonProperty("ExifImageHeight") + @ExcludeMissing + exifImageHeight: JsonField = JsonMissing.of(), + @JsonProperty("ExifImageWidth") + @ExcludeMissing + exifImageWidth: JsonField = JsonMissing.of(), + @JsonProperty("ExifVersion") + @ExcludeMissing + exifVersion: JsonField = JsonMissing.of(), + @JsonProperty("ExposureCompensation") + @ExcludeMissing + exposureCompensation: JsonField = JsonMissing.of(), + @JsonProperty("ExposureMode") + @ExcludeMissing + exposureMode: JsonField = JsonMissing.of(), + @JsonProperty("ExposureProgram") + @ExcludeMissing + exposureProgram: JsonField = JsonMissing.of(), + @JsonProperty("ExposureTime") + @ExcludeMissing + exposureTime: JsonField = JsonMissing.of(), + @JsonProperty("Flash") @ExcludeMissing flash: JsonField = JsonMissing.of(), + @JsonProperty("FlashpixVersion") + @ExcludeMissing + flashpixVersion: JsonField = JsonMissing.of(), + @JsonProperty("FNumber") + @ExcludeMissing + fNumber: JsonField = JsonMissing.of(), + @JsonProperty("FocalLength") + @ExcludeMissing + focalLength: JsonField = JsonMissing.of(), + @JsonProperty("FocalPlaneResolutionUnit") + @ExcludeMissing + focalPlaneResolutionUnit: JsonField = JsonMissing.of(), + @JsonProperty("FocalPlaneXResolution") + @ExcludeMissing + focalPlaneXResolution: JsonField = JsonMissing.of(), + @JsonProperty("FocalPlaneYResolution") + @ExcludeMissing + focalPlaneYResolution: JsonField = JsonMissing.of(), + @JsonProperty("InteropOffset") + @ExcludeMissing + interopOffset: JsonField = JsonMissing.of(), + @JsonProperty("ISO") @ExcludeMissing iso: JsonField = JsonMissing.of(), + @JsonProperty("MeteringMode") + @ExcludeMissing + meteringMode: JsonField = JsonMissing.of(), + @JsonProperty("SceneCaptureType") + @ExcludeMissing + sceneCaptureType: JsonField = JsonMissing.of(), + @JsonProperty("ShutterSpeedValue") + @ExcludeMissing + shutterSpeedValue: JsonField = JsonMissing.of(), + @JsonProperty("SubSecTime") + @ExcludeMissing + subSecTime: JsonField = JsonMissing.of(), + @JsonProperty("WhiteBalance") + @ExcludeMissing + whiteBalance: JsonField = JsonMissing.of(), + ) : this( + apertureValue, + colorSpace, + createDate, + customRendered, + dateTimeOriginal, + exifImageHeight, + exifImageWidth, + exifVersion, + exposureCompensation, + exposureMode, + exposureProgram, + exposureTime, + flash, + flashpixVersion, + fNumber, + focalLength, + focalPlaneResolutionUnit, + focalPlaneXResolution, + focalPlaneYResolution, + interopOffset, + iso, + meteringMode, + sceneCaptureType, + shutterSpeedValue, + subSecTime, + whiteBalance, + mutableMapOf(), + ) + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun apertureValue(): Optional = apertureValue.getOptional("ApertureValue") + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun colorSpace(): Optional = colorSpace.getOptional("ColorSpace") + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun createDate(): Optional = createDate.getOptional("CreateDate") + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun customRendered(): Optional = customRendered.getOptional("CustomRendered") + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun dateTimeOriginal(): Optional = + dateTimeOriginal.getOptional("DateTimeOriginal") + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun exifImageHeight(): Optional = exifImageHeight.getOptional("ExifImageHeight") + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun exifImageWidth(): Optional = exifImageWidth.getOptional("ExifImageWidth") + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun exifVersion(): Optional = exifVersion.getOptional("ExifVersion") + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun exposureCompensation(): Optional = + exposureCompensation.getOptional("ExposureCompensation") + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun exposureMode(): Optional = exposureMode.getOptional("ExposureMode") + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun exposureProgram(): Optional = exposureProgram.getOptional("ExposureProgram") + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun exposureTime(): Optional = exposureTime.getOptional("ExposureTime") + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun flash(): Optional = flash.getOptional("Flash") + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun flashpixVersion(): Optional = flashpixVersion.getOptional("FlashpixVersion") + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun fNumber(): Optional = fNumber.getOptional("FNumber") + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun focalLength(): Optional = focalLength.getOptional("FocalLength") + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun focalPlaneResolutionUnit(): Optional = + focalPlaneResolutionUnit.getOptional("FocalPlaneResolutionUnit") + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun focalPlaneXResolution(): Optional = + focalPlaneXResolution.getOptional("FocalPlaneXResolution") + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun focalPlaneYResolution(): Optional = + focalPlaneYResolution.getOptional("FocalPlaneYResolution") + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun interopOffset(): Optional = interopOffset.getOptional("InteropOffset") + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun iso(): Optional = iso.getOptional("ISO") + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun meteringMode(): Optional = meteringMode.getOptional("MeteringMode") + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun sceneCaptureType(): Optional = + sceneCaptureType.getOptional("SceneCaptureType") + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun shutterSpeedValue(): Optional = + shutterSpeedValue.getOptional("ShutterSpeedValue") + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun subSecTime(): Optional = subSecTime.getOptional("SubSecTime") + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun whiteBalance(): Optional = whiteBalance.getOptional("WhiteBalance") + + /** + * Returns the raw JSON value of [apertureValue]. + * + * Unlike [apertureValue], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("ApertureValue") + @ExcludeMissing + fun _apertureValue(): JsonField = apertureValue + + /** + * Returns the raw JSON value of [colorSpace]. + * + * Unlike [colorSpace], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("ColorSpace") + @ExcludeMissing + fun _colorSpace(): JsonField = colorSpace + + /** + * Returns the raw JSON value of [createDate]. + * + * Unlike [createDate], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("CreateDate") + @ExcludeMissing + fun _createDate(): JsonField = createDate + + /** + * Returns the raw JSON value of [customRendered]. + * + * Unlike [customRendered], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("CustomRendered") + @ExcludeMissing + fun _customRendered(): JsonField = customRendered + + /** + * Returns the raw JSON value of [dateTimeOriginal]. + * + * Unlike [dateTimeOriginal], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("DateTimeOriginal") + @ExcludeMissing + fun _dateTimeOriginal(): JsonField = dateTimeOriginal + + /** + * Returns the raw JSON value of [exifImageHeight]. + * + * Unlike [exifImageHeight], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("ExifImageHeight") + @ExcludeMissing + fun _exifImageHeight(): JsonField = exifImageHeight + + /** + * Returns the raw JSON value of [exifImageWidth]. + * + * Unlike [exifImageWidth], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("ExifImageWidth") + @ExcludeMissing + fun _exifImageWidth(): JsonField = exifImageWidth + + /** + * Returns the raw JSON value of [exifVersion]. + * + * Unlike [exifVersion], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("ExifVersion") + @ExcludeMissing + fun _exifVersion(): JsonField = exifVersion + + /** + * Returns the raw JSON value of [exposureCompensation]. + * + * Unlike [exposureCompensation], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("ExposureCompensation") + @ExcludeMissing + fun _exposureCompensation(): JsonField = exposureCompensation + + /** + * Returns the raw JSON value of [exposureMode]. + * + * Unlike [exposureMode], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("ExposureMode") + @ExcludeMissing + fun _exposureMode(): JsonField = exposureMode + + /** + * Returns the raw JSON value of [exposureProgram]. + * + * Unlike [exposureProgram], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("ExposureProgram") + @ExcludeMissing + fun _exposureProgram(): JsonField = exposureProgram + + /** + * Returns the raw JSON value of [exposureTime]. + * + * Unlike [exposureTime], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("ExposureTime") + @ExcludeMissing + fun _exposureTime(): JsonField = exposureTime + + /** + * Returns the raw JSON value of [flash]. + * + * Unlike [flash], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("Flash") @ExcludeMissing fun _flash(): JsonField = flash + + /** + * Returns the raw JSON value of [flashpixVersion]. + * + * Unlike [flashpixVersion], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("FlashpixVersion") + @ExcludeMissing + fun _flashpixVersion(): JsonField = flashpixVersion + + /** + * Returns the raw JSON value of [fNumber]. + * + * Unlike [fNumber], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("FNumber") @ExcludeMissing fun _fNumber(): JsonField = fNumber + + /** + * Returns the raw JSON value of [focalLength]. + * + * Unlike [focalLength], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("FocalLength") + @ExcludeMissing + fun _focalLength(): JsonField = focalLength + + /** + * Returns the raw JSON value of [focalPlaneResolutionUnit]. + * + * Unlike [focalPlaneResolutionUnit], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("FocalPlaneResolutionUnit") + @ExcludeMissing + fun _focalPlaneResolutionUnit(): JsonField = focalPlaneResolutionUnit + + /** + * Returns the raw JSON value of [focalPlaneXResolution]. + * + * Unlike [focalPlaneXResolution], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("FocalPlaneXResolution") + @ExcludeMissing + fun _focalPlaneXResolution(): JsonField = focalPlaneXResolution + + /** + * Returns the raw JSON value of [focalPlaneYResolution]. + * + * Unlike [focalPlaneYResolution], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("FocalPlaneYResolution") + @ExcludeMissing + fun _focalPlaneYResolution(): JsonField = focalPlaneYResolution + + /** + * Returns the raw JSON value of [interopOffset]. + * + * Unlike [interopOffset], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("InteropOffset") + @ExcludeMissing + fun _interopOffset(): JsonField = interopOffset + + /** + * Returns the raw JSON value of [iso]. + * + * Unlike [iso], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("ISO") @ExcludeMissing fun _iso(): JsonField = iso + + /** + * Returns the raw JSON value of [meteringMode]. + * + * Unlike [meteringMode], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("MeteringMode") + @ExcludeMissing + fun _meteringMode(): JsonField = meteringMode + + /** + * Returns the raw JSON value of [sceneCaptureType]. + * + * Unlike [sceneCaptureType], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("SceneCaptureType") + @ExcludeMissing + fun _sceneCaptureType(): JsonField = sceneCaptureType + + /** + * Returns the raw JSON value of [shutterSpeedValue]. + * + * Unlike [shutterSpeedValue], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("ShutterSpeedValue") + @ExcludeMissing + fun _shutterSpeedValue(): JsonField = shutterSpeedValue + + /** + * Returns the raw JSON value of [subSecTime]. + * + * Unlike [subSecTime], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("SubSecTime") + @ExcludeMissing + fun _subSecTime(): JsonField = subSecTime + + /** + * Returns the raw JSON value of [whiteBalance]. + * + * Unlike [whiteBalance], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("WhiteBalance") + @ExcludeMissing + fun _whiteBalance(): JsonField = whiteBalance + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [InnerExif]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [InnerExif]. */ + class Builder internal constructor() { + + private var apertureValue: JsonField = JsonMissing.of() + private var colorSpace: JsonField = JsonMissing.of() + private var createDate: JsonField = JsonMissing.of() + private var customRendered: JsonField = JsonMissing.of() + private var dateTimeOriginal: JsonField = JsonMissing.of() + private var exifImageHeight: JsonField = JsonMissing.of() + private var exifImageWidth: JsonField = JsonMissing.of() + private var exifVersion: JsonField = JsonMissing.of() + private var exposureCompensation: JsonField = JsonMissing.of() + private var exposureMode: JsonField = JsonMissing.of() + private var exposureProgram: JsonField = JsonMissing.of() + private var exposureTime: JsonField = JsonMissing.of() + private var flash: JsonField = JsonMissing.of() + private var flashpixVersion: JsonField = JsonMissing.of() + private var fNumber: JsonField = JsonMissing.of() + private var focalLength: JsonField = JsonMissing.of() + private var focalPlaneResolutionUnit: JsonField = JsonMissing.of() + private var focalPlaneXResolution: JsonField = JsonMissing.of() + private var focalPlaneYResolution: JsonField = JsonMissing.of() + private var interopOffset: JsonField = JsonMissing.of() + private var iso: JsonField = JsonMissing.of() + private var meteringMode: JsonField = JsonMissing.of() + private var sceneCaptureType: JsonField = JsonMissing.of() + private var shutterSpeedValue: JsonField = JsonMissing.of() + private var subSecTime: JsonField = JsonMissing.of() + private var whiteBalance: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(innerExif: InnerExif) = apply { + apertureValue = innerExif.apertureValue + colorSpace = innerExif.colorSpace + createDate = innerExif.createDate + customRendered = innerExif.customRendered + dateTimeOriginal = innerExif.dateTimeOriginal + exifImageHeight = innerExif.exifImageHeight + exifImageWidth = innerExif.exifImageWidth + exifVersion = innerExif.exifVersion + exposureCompensation = innerExif.exposureCompensation + exposureMode = innerExif.exposureMode + exposureProgram = innerExif.exposureProgram + exposureTime = innerExif.exposureTime + flash = innerExif.flash + flashpixVersion = innerExif.flashpixVersion + fNumber = innerExif.fNumber + focalLength = innerExif.focalLength + focalPlaneResolutionUnit = innerExif.focalPlaneResolutionUnit + focalPlaneXResolution = innerExif.focalPlaneXResolution + focalPlaneYResolution = innerExif.focalPlaneYResolution + interopOffset = innerExif.interopOffset + iso = innerExif.iso + meteringMode = innerExif.meteringMode + sceneCaptureType = innerExif.sceneCaptureType + shutterSpeedValue = innerExif.shutterSpeedValue + subSecTime = innerExif.subSecTime + whiteBalance = innerExif.whiteBalance + additionalProperties = innerExif.additionalProperties.toMutableMap() + } + + fun apertureValue(apertureValue: Double) = + apertureValue(JsonField.of(apertureValue)) + + /** + * Sets [Builder.apertureValue] to an arbitrary JSON value. + * + * You should usually call [Builder.apertureValue] with a well-typed [Double] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun apertureValue(apertureValue: JsonField) = apply { + this.apertureValue = apertureValue + } + + fun colorSpace(colorSpace: Long) = colorSpace(JsonField.of(colorSpace)) + + /** + * Sets [Builder.colorSpace] to an arbitrary JSON value. + * + * You should usually call [Builder.colorSpace] with a well-typed [Long] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun colorSpace(colorSpace: JsonField) = apply { this.colorSpace = colorSpace } + + fun createDate(createDate: String) = createDate(JsonField.of(createDate)) + + /** + * Sets [Builder.createDate] to an arbitrary JSON value. + * + * You should usually call [Builder.createDate] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun createDate(createDate: JsonField) = apply { + this.createDate = createDate + } + + fun customRendered(customRendered: Long) = + customRendered(JsonField.of(customRendered)) + + /** + * Sets [Builder.customRendered] to an arbitrary JSON value. + * + * You should usually call [Builder.customRendered] with a well-typed [Long] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun customRendered(customRendered: JsonField) = apply { + this.customRendered = customRendered + } + + fun dateTimeOriginal(dateTimeOriginal: String) = + dateTimeOriginal(JsonField.of(dateTimeOriginal)) + + /** + * Sets [Builder.dateTimeOriginal] to an arbitrary JSON value. + * + * You should usually call [Builder.dateTimeOriginal] with a well-typed [String] + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun dateTimeOriginal(dateTimeOriginal: JsonField) = apply { + this.dateTimeOriginal = dateTimeOriginal + } + + fun exifImageHeight(exifImageHeight: Long) = + exifImageHeight(JsonField.of(exifImageHeight)) + + /** + * Sets [Builder.exifImageHeight] to an arbitrary JSON value. + * + * You should usually call [Builder.exifImageHeight] with a well-typed [Long] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun exifImageHeight(exifImageHeight: JsonField) = apply { + this.exifImageHeight = exifImageHeight + } + + fun exifImageWidth(exifImageWidth: Long) = + exifImageWidth(JsonField.of(exifImageWidth)) + + /** + * Sets [Builder.exifImageWidth] to an arbitrary JSON value. + * + * You should usually call [Builder.exifImageWidth] with a well-typed [Long] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun exifImageWidth(exifImageWidth: JsonField) = apply { + this.exifImageWidth = exifImageWidth + } + + fun exifVersion(exifVersion: String) = exifVersion(JsonField.of(exifVersion)) + + /** + * Sets [Builder.exifVersion] to an arbitrary JSON value. + * + * You should usually call [Builder.exifVersion] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun exifVersion(exifVersion: JsonField) = apply { + this.exifVersion = exifVersion + } + + fun exposureCompensation(exposureCompensation: Double) = + exposureCompensation(JsonField.of(exposureCompensation)) + + /** + * Sets [Builder.exposureCompensation] to an arbitrary JSON value. + * + * You should usually call [Builder.exposureCompensation] with a well-typed [Double] + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun exposureCompensation(exposureCompensation: JsonField) = apply { + this.exposureCompensation = exposureCompensation + } + + fun exposureMode(exposureMode: Long) = exposureMode(JsonField.of(exposureMode)) + + /** + * Sets [Builder.exposureMode] to an arbitrary JSON value. + * + * You should usually call [Builder.exposureMode] with a well-typed [Long] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun exposureMode(exposureMode: JsonField) = apply { + this.exposureMode = exposureMode + } + + fun exposureProgram(exposureProgram: Long) = + exposureProgram(JsonField.of(exposureProgram)) + + /** + * Sets [Builder.exposureProgram] to an arbitrary JSON value. + * + * You should usually call [Builder.exposureProgram] with a well-typed [Long] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun exposureProgram(exposureProgram: JsonField) = apply { + this.exposureProgram = exposureProgram + } + + fun exposureTime(exposureTime: Double) = exposureTime(JsonField.of(exposureTime)) + + /** + * Sets [Builder.exposureTime] to an arbitrary JSON value. + * + * You should usually call [Builder.exposureTime] with a well-typed [Double] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun exposureTime(exposureTime: JsonField) = apply { + this.exposureTime = exposureTime + } + + fun flash(flash: Long) = flash(JsonField.of(flash)) + + /** + * Sets [Builder.flash] to an arbitrary JSON value. + * + * You should usually call [Builder.flash] with a well-typed [Long] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun flash(flash: JsonField) = apply { this.flash = flash } + + fun flashpixVersion(flashpixVersion: String) = + flashpixVersion(JsonField.of(flashpixVersion)) + + /** + * Sets [Builder.flashpixVersion] to an arbitrary JSON value. + * + * You should usually call [Builder.flashpixVersion] with a well-typed [String] + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun flashpixVersion(flashpixVersion: JsonField) = apply { + this.flashpixVersion = flashpixVersion + } + + fun fNumber(fNumber: Double) = fNumber(JsonField.of(fNumber)) + + /** + * Sets [Builder.fNumber] to an arbitrary JSON value. + * + * You should usually call [Builder.fNumber] with a well-typed [Double] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun fNumber(fNumber: JsonField) = apply { this.fNumber = fNumber } + + fun focalLength(focalLength: Long) = focalLength(JsonField.of(focalLength)) + + /** + * Sets [Builder.focalLength] to an arbitrary JSON value. + * + * You should usually call [Builder.focalLength] with a well-typed [Long] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun focalLength(focalLength: JsonField) = apply { + this.focalLength = focalLength + } + + fun focalPlaneResolutionUnit(focalPlaneResolutionUnit: Long) = + focalPlaneResolutionUnit(JsonField.of(focalPlaneResolutionUnit)) + + /** + * Sets [Builder.focalPlaneResolutionUnit] to an arbitrary JSON value. + * + * You should usually call [Builder.focalPlaneResolutionUnit] with a well-typed + * [Long] value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun focalPlaneResolutionUnit(focalPlaneResolutionUnit: JsonField) = apply { + this.focalPlaneResolutionUnit = focalPlaneResolutionUnit + } + + fun focalPlaneXResolution(focalPlaneXResolution: Double) = + focalPlaneXResolution(JsonField.of(focalPlaneXResolution)) + + /** + * Sets [Builder.focalPlaneXResolution] to an arbitrary JSON value. + * + * You should usually call [Builder.focalPlaneXResolution] with a well-typed + * [Double] value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun focalPlaneXResolution(focalPlaneXResolution: JsonField) = apply { + this.focalPlaneXResolution = focalPlaneXResolution + } + + fun focalPlaneYResolution(focalPlaneYResolution: Double) = + focalPlaneYResolution(JsonField.of(focalPlaneYResolution)) + + /** + * Sets [Builder.focalPlaneYResolution] to an arbitrary JSON value. + * + * You should usually call [Builder.focalPlaneYResolution] with a well-typed + * [Double] value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun focalPlaneYResolution(focalPlaneYResolution: JsonField) = apply { + this.focalPlaneYResolution = focalPlaneYResolution + } + + fun interopOffset(interopOffset: Long) = interopOffset(JsonField.of(interopOffset)) + + /** + * Sets [Builder.interopOffset] to an arbitrary JSON value. + * + * You should usually call [Builder.interopOffset] with a well-typed [Long] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun interopOffset(interopOffset: JsonField) = apply { + this.interopOffset = interopOffset + } + + fun iso(iso: Long) = iso(JsonField.of(iso)) + + /** + * Sets [Builder.iso] to an arbitrary JSON value. + * + * You should usually call [Builder.iso] with a well-typed [Long] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun iso(iso: JsonField) = apply { this.iso = iso } + + fun meteringMode(meteringMode: Long) = meteringMode(JsonField.of(meteringMode)) + + /** + * Sets [Builder.meteringMode] to an arbitrary JSON value. + * + * You should usually call [Builder.meteringMode] with a well-typed [Long] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun meteringMode(meteringMode: JsonField) = apply { + this.meteringMode = meteringMode + } + + fun sceneCaptureType(sceneCaptureType: Long) = + sceneCaptureType(JsonField.of(sceneCaptureType)) + + /** + * Sets [Builder.sceneCaptureType] to an arbitrary JSON value. + * + * You should usually call [Builder.sceneCaptureType] with a well-typed [Long] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun sceneCaptureType(sceneCaptureType: JsonField) = apply { + this.sceneCaptureType = sceneCaptureType + } + + fun shutterSpeedValue(shutterSpeedValue: Double) = + shutterSpeedValue(JsonField.of(shutterSpeedValue)) + + /** + * Sets [Builder.shutterSpeedValue] to an arbitrary JSON value. + * + * You should usually call [Builder.shutterSpeedValue] with a well-typed [Double] + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun shutterSpeedValue(shutterSpeedValue: JsonField) = apply { + this.shutterSpeedValue = shutterSpeedValue + } + + fun subSecTime(subSecTime: String) = subSecTime(JsonField.of(subSecTime)) + + /** + * Sets [Builder.subSecTime] to an arbitrary JSON value. + * + * You should usually call [Builder.subSecTime] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun subSecTime(subSecTime: JsonField) = apply { + this.subSecTime = subSecTime + } + + fun whiteBalance(whiteBalance: Long) = whiteBalance(JsonField.of(whiteBalance)) + + /** + * Sets [Builder.whiteBalance] to an arbitrary JSON value. + * + * You should usually call [Builder.whiteBalance] with a well-typed [Long] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun whiteBalance(whiteBalance: JsonField) = apply { + this.whiteBalance = whiteBalance + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [InnerExif]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): InnerExif = + InnerExif( + apertureValue, + colorSpace, + createDate, + customRendered, + dateTimeOriginal, + exifImageHeight, + exifImageWidth, + exifVersion, + exposureCompensation, + exposureMode, + exposureProgram, + exposureTime, + flash, + flashpixVersion, + fNumber, + focalLength, + focalPlaneResolutionUnit, + focalPlaneXResolution, + focalPlaneYResolution, + interopOffset, + iso, + meteringMode, + sceneCaptureType, + shutterSpeedValue, + subSecTime, + whiteBalance, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): InnerExif = apply { + if (validated) { + return@apply + } + + apertureValue() + colorSpace() + createDate() + customRendered() + dateTimeOriginal() + exifImageHeight() + exifImageWidth() + exifVersion() + exposureCompensation() + exposureMode() + exposureProgram() + exposureTime() + flash() + flashpixVersion() + fNumber() + focalLength() + focalPlaneResolutionUnit() + focalPlaneXResolution() + focalPlaneYResolution() + interopOffset() + iso() + meteringMode() + sceneCaptureType() + shutterSpeedValue() + subSecTime() + whiteBalance() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (apertureValue.asKnown().isPresent) 1 else 0) + + (if (colorSpace.asKnown().isPresent) 1 else 0) + + (if (createDate.asKnown().isPresent) 1 else 0) + + (if (customRendered.asKnown().isPresent) 1 else 0) + + (if (dateTimeOriginal.asKnown().isPresent) 1 else 0) + + (if (exifImageHeight.asKnown().isPresent) 1 else 0) + + (if (exifImageWidth.asKnown().isPresent) 1 else 0) + + (if (exifVersion.asKnown().isPresent) 1 else 0) + + (if (exposureCompensation.asKnown().isPresent) 1 else 0) + + (if (exposureMode.asKnown().isPresent) 1 else 0) + + (if (exposureProgram.asKnown().isPresent) 1 else 0) + + (if (exposureTime.asKnown().isPresent) 1 else 0) + + (if (flash.asKnown().isPresent) 1 else 0) + + (if (flashpixVersion.asKnown().isPresent) 1 else 0) + + (if (fNumber.asKnown().isPresent) 1 else 0) + + (if (focalLength.asKnown().isPresent) 1 else 0) + + (if (focalPlaneResolutionUnit.asKnown().isPresent) 1 else 0) + + (if (focalPlaneXResolution.asKnown().isPresent) 1 else 0) + + (if (focalPlaneYResolution.asKnown().isPresent) 1 else 0) + + (if (interopOffset.asKnown().isPresent) 1 else 0) + + (if (iso.asKnown().isPresent) 1 else 0) + + (if (meteringMode.asKnown().isPresent) 1 else 0) + + (if (sceneCaptureType.asKnown().isPresent) 1 else 0) + + (if (shutterSpeedValue.asKnown().isPresent) 1 else 0) + + (if (subSecTime.asKnown().isPresent) 1 else 0) + + (if (whiteBalance.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is InnerExif && + apertureValue == other.apertureValue && + colorSpace == other.colorSpace && + createDate == other.createDate && + customRendered == other.customRendered && + dateTimeOriginal == other.dateTimeOriginal && + exifImageHeight == other.exifImageHeight && + exifImageWidth == other.exifImageWidth && + exifVersion == other.exifVersion && + exposureCompensation == other.exposureCompensation && + exposureMode == other.exposureMode && + exposureProgram == other.exposureProgram && + exposureTime == other.exposureTime && + flash == other.flash && + flashpixVersion == other.flashpixVersion && + fNumber == other.fNumber && + focalLength == other.focalLength && + focalPlaneResolutionUnit == other.focalPlaneResolutionUnit && + focalPlaneXResolution == other.focalPlaneXResolution && + focalPlaneYResolution == other.focalPlaneYResolution && + interopOffset == other.interopOffset && + iso == other.iso && + meteringMode == other.meteringMode && + sceneCaptureType == other.sceneCaptureType && + shutterSpeedValue == other.shutterSpeedValue && + subSecTime == other.subSecTime && + whiteBalance == other.whiteBalance && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + apertureValue, + colorSpace, + createDate, + customRendered, + dateTimeOriginal, + exifImageHeight, + exifImageWidth, + exifVersion, + exposureCompensation, + exposureMode, + exposureProgram, + exposureTime, + flash, + flashpixVersion, + fNumber, + focalLength, + focalPlaneResolutionUnit, + focalPlaneXResolution, + focalPlaneYResolution, + interopOffset, + iso, + meteringMode, + sceneCaptureType, + shutterSpeedValue, + subSecTime, + whiteBalance, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "InnerExif{apertureValue=$apertureValue, colorSpace=$colorSpace, createDate=$createDate, customRendered=$customRendered, dateTimeOriginal=$dateTimeOriginal, exifImageHeight=$exifImageHeight, exifImageWidth=$exifImageWidth, exifVersion=$exifVersion, exposureCompensation=$exposureCompensation, exposureMode=$exposureMode, exposureProgram=$exposureProgram, exposureTime=$exposureTime, flash=$flash, flashpixVersion=$flashpixVersion, fNumber=$fNumber, focalLength=$focalLength, focalPlaneResolutionUnit=$focalPlaneResolutionUnit, focalPlaneXResolution=$focalPlaneXResolution, focalPlaneYResolution=$focalPlaneYResolution, interopOffset=$interopOffset, iso=$iso, meteringMode=$meteringMode, sceneCaptureType=$sceneCaptureType, shutterSpeedValue=$shutterSpeedValue, subSecTime=$subSecTime, whiteBalance=$whiteBalance, additionalProperties=$additionalProperties}" + } + + /** Object containing GPS information. */ + class Gps + private constructor( + private val gpsVersionId: JsonField>, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("GPSVersionID") + @ExcludeMissing + gpsVersionId: JsonField> = JsonMissing.of() + ) : this(gpsVersionId, mutableMapOf()) + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun gpsVersionId(): Optional> = gpsVersionId.getOptional("GPSVersionID") + + /** + * Returns the raw JSON value of [gpsVersionId]. + * + * Unlike [gpsVersionId], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("GPSVersionID") + @ExcludeMissing + fun _gpsVersionId(): JsonField> = gpsVersionId + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Gps]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Gps]. */ + class Builder internal constructor() { + + private var gpsVersionId: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(gps: Gps) = apply { + gpsVersionId = gps.gpsVersionId.map { it.toMutableList() } + additionalProperties = gps.additionalProperties.toMutableMap() + } + + fun gpsVersionId(gpsVersionId: List) = + gpsVersionId(JsonField.of(gpsVersionId)) + + /** + * Sets [Builder.gpsVersionId] to an arbitrary JSON value. + * + * You should usually call [Builder.gpsVersionId] with a well-typed `List` + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun gpsVersionId(gpsVersionId: JsonField>) = apply { + this.gpsVersionId = gpsVersionId.map { it.toMutableList() } + } + + /** + * Adds a single [Long] to [Builder.gpsVersionId]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addGpsVersionId(gpsVersionId: Long) = apply { + this.gpsVersionId = + (this.gpsVersionId ?: JsonField.of(mutableListOf())).also { + checkKnown("gpsVersionId", it).add(gpsVersionId) + } + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Gps]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Gps = + Gps( + (gpsVersionId ?: JsonMissing.of()).map { it.toImmutable() }, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Gps = apply { + if (validated) { + return@apply + } + + gpsVersionId() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = (gpsVersionId.asKnown().getOrNull()?.size ?: 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Gps && + gpsVersionId == other.gpsVersionId && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(gpsVersionId, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Gps{gpsVersionId=$gpsVersionId, additionalProperties=$additionalProperties}" + } + + /** Object containing EXIF image information. */ + class Image + private constructor( + private val exifOffset: JsonField, + private val gpsInfo: JsonField, + private val make: JsonField, + private val model: JsonField, + private val modifyDate: JsonField, + private val orientation: JsonField, + private val resolutionUnit: JsonField, + private val software: JsonField, + private val xResolution: JsonField, + private val yCbCrPositioning: JsonField, + private val yResolution: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("ExifOffset") + @ExcludeMissing + exifOffset: JsonField = JsonMissing.of(), + @JsonProperty("GPSInfo") + @ExcludeMissing + gpsInfo: JsonField = JsonMissing.of(), + @JsonProperty("Make") @ExcludeMissing make: JsonField = JsonMissing.of(), + @JsonProperty("Model") @ExcludeMissing model: JsonField = JsonMissing.of(), + @JsonProperty("ModifyDate") + @ExcludeMissing + modifyDate: JsonField = JsonMissing.of(), + @JsonProperty("Orientation") + @ExcludeMissing + orientation: JsonField = JsonMissing.of(), + @JsonProperty("ResolutionUnit") + @ExcludeMissing + resolutionUnit: JsonField = JsonMissing.of(), + @JsonProperty("Software") + @ExcludeMissing + software: JsonField = JsonMissing.of(), + @JsonProperty("XResolution") + @ExcludeMissing + xResolution: JsonField = JsonMissing.of(), + @JsonProperty("YCbCrPositioning") + @ExcludeMissing + yCbCrPositioning: JsonField = JsonMissing.of(), + @JsonProperty("YResolution") + @ExcludeMissing + yResolution: JsonField = JsonMissing.of(), + ) : this( + exifOffset, + gpsInfo, + make, + model, + modifyDate, + orientation, + resolutionUnit, + software, + xResolution, + yCbCrPositioning, + yResolution, + mutableMapOf(), + ) + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun exifOffset(): Optional = exifOffset.getOptional("ExifOffset") + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun gpsInfo(): Optional = gpsInfo.getOptional("GPSInfo") + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun make(): Optional = make.getOptional("Make") + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun model(): Optional = model.getOptional("Model") + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun modifyDate(): Optional = modifyDate.getOptional("ModifyDate") + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun orientation(): Optional = orientation.getOptional("Orientation") + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun resolutionUnit(): Optional = resolutionUnit.getOptional("ResolutionUnit") + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun software(): Optional = software.getOptional("Software") + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun xResolution(): Optional = xResolution.getOptional("XResolution") + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun yCbCrPositioning(): Optional = + yCbCrPositioning.getOptional("YCbCrPositioning") + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun yResolution(): Optional = yResolution.getOptional("YResolution") + + /** + * Returns the raw JSON value of [exifOffset]. + * + * Unlike [exifOffset], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("ExifOffset") + @ExcludeMissing + fun _exifOffset(): JsonField = exifOffset + + /** + * Returns the raw JSON value of [gpsInfo]. + * + * Unlike [gpsInfo], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("GPSInfo") @ExcludeMissing fun _gpsInfo(): JsonField = gpsInfo + + /** + * Returns the raw JSON value of [make]. + * + * Unlike [make], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("Make") @ExcludeMissing fun _make(): JsonField = make + + /** + * Returns the raw JSON value of [model]. + * + * Unlike [model], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("Model") @ExcludeMissing fun _model(): JsonField = model + + /** + * Returns the raw JSON value of [modifyDate]. + * + * Unlike [modifyDate], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("ModifyDate") + @ExcludeMissing + fun _modifyDate(): JsonField = modifyDate + + /** + * Returns the raw JSON value of [orientation]. + * + * Unlike [orientation], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("Orientation") + @ExcludeMissing + fun _orientation(): JsonField = orientation + + /** + * Returns the raw JSON value of [resolutionUnit]. + * + * Unlike [resolutionUnit], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("ResolutionUnit") + @ExcludeMissing + fun _resolutionUnit(): JsonField = resolutionUnit + + /** + * Returns the raw JSON value of [software]. + * + * Unlike [software], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("Software") @ExcludeMissing fun _software(): JsonField = software + + /** + * Returns the raw JSON value of [xResolution]. + * + * Unlike [xResolution], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("XResolution") + @ExcludeMissing + fun _xResolution(): JsonField = xResolution + + /** + * Returns the raw JSON value of [yCbCrPositioning]. + * + * Unlike [yCbCrPositioning], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("YCbCrPositioning") + @ExcludeMissing + fun _yCbCrPositioning(): JsonField = yCbCrPositioning + + /** + * Returns the raw JSON value of [yResolution]. + * + * Unlike [yResolution], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("YResolution") + @ExcludeMissing + fun _yResolution(): JsonField = yResolution + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Image]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Image]. */ + class Builder internal constructor() { + + private var exifOffset: JsonField = JsonMissing.of() + private var gpsInfo: JsonField = JsonMissing.of() + private var make: JsonField = JsonMissing.of() + private var model: JsonField = JsonMissing.of() + private var modifyDate: JsonField = JsonMissing.of() + private var orientation: JsonField = JsonMissing.of() + private var resolutionUnit: JsonField = JsonMissing.of() + private var software: JsonField = JsonMissing.of() + private var xResolution: JsonField = JsonMissing.of() + private var yCbCrPositioning: JsonField = JsonMissing.of() + private var yResolution: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(image: Image) = apply { + exifOffset = image.exifOffset + gpsInfo = image.gpsInfo + make = image.make + model = image.model + modifyDate = image.modifyDate + orientation = image.orientation + resolutionUnit = image.resolutionUnit + software = image.software + xResolution = image.xResolution + yCbCrPositioning = image.yCbCrPositioning + yResolution = image.yResolution + additionalProperties = image.additionalProperties.toMutableMap() + } + + fun exifOffset(exifOffset: Long) = exifOffset(JsonField.of(exifOffset)) + + /** + * Sets [Builder.exifOffset] to an arbitrary JSON value. + * + * You should usually call [Builder.exifOffset] with a well-typed [Long] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun exifOffset(exifOffset: JsonField) = apply { this.exifOffset = exifOffset } + + fun gpsInfo(gpsInfo: Long) = gpsInfo(JsonField.of(gpsInfo)) + + /** + * Sets [Builder.gpsInfo] to an arbitrary JSON value. + * + * You should usually call [Builder.gpsInfo] with a well-typed [Long] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun gpsInfo(gpsInfo: JsonField) = apply { this.gpsInfo = gpsInfo } + + fun make(make: String) = make(JsonField.of(make)) + + /** + * Sets [Builder.make] to an arbitrary JSON value. + * + * You should usually call [Builder.make] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun make(make: JsonField) = apply { this.make = make } + + fun model(model: String) = model(JsonField.of(model)) + + /** + * Sets [Builder.model] to an arbitrary JSON value. + * + * You should usually call [Builder.model] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun model(model: JsonField) = apply { this.model = model } + + fun modifyDate(modifyDate: String) = modifyDate(JsonField.of(modifyDate)) + + /** + * Sets [Builder.modifyDate] to an arbitrary JSON value. + * + * You should usually call [Builder.modifyDate] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun modifyDate(modifyDate: JsonField) = apply { + this.modifyDate = modifyDate + } + + fun orientation(orientation: Long) = orientation(JsonField.of(orientation)) + + /** + * Sets [Builder.orientation] to an arbitrary JSON value. + * + * You should usually call [Builder.orientation] with a well-typed [Long] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun orientation(orientation: JsonField) = apply { + this.orientation = orientation + } + + fun resolutionUnit(resolutionUnit: Long) = + resolutionUnit(JsonField.of(resolutionUnit)) + + /** + * Sets [Builder.resolutionUnit] to an arbitrary JSON value. + * + * You should usually call [Builder.resolutionUnit] with a well-typed [Long] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun resolutionUnit(resolutionUnit: JsonField) = apply { + this.resolutionUnit = resolutionUnit + } + + fun software(software: String) = software(JsonField.of(software)) + + /** + * Sets [Builder.software] to an arbitrary JSON value. + * + * You should usually call [Builder.software] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun software(software: JsonField) = apply { this.software = software } + + fun xResolution(xResolution: Long) = xResolution(JsonField.of(xResolution)) + + /** + * Sets [Builder.xResolution] to an arbitrary JSON value. + * + * You should usually call [Builder.xResolution] with a well-typed [Long] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun xResolution(xResolution: JsonField) = apply { + this.xResolution = xResolution + } + + fun yCbCrPositioning(yCbCrPositioning: Long) = + yCbCrPositioning(JsonField.of(yCbCrPositioning)) + + /** + * Sets [Builder.yCbCrPositioning] to an arbitrary JSON value. + * + * You should usually call [Builder.yCbCrPositioning] with a well-typed [Long] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun yCbCrPositioning(yCbCrPositioning: JsonField) = apply { + this.yCbCrPositioning = yCbCrPositioning + } + + fun yResolution(yResolution: Long) = yResolution(JsonField.of(yResolution)) + + /** + * Sets [Builder.yResolution] to an arbitrary JSON value. + * + * You should usually call [Builder.yResolution] with a well-typed [Long] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun yResolution(yResolution: JsonField) = apply { + this.yResolution = yResolution + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Image]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Image = + Image( + exifOffset, + gpsInfo, + make, + model, + modifyDate, + orientation, + resolutionUnit, + software, + xResolution, + yCbCrPositioning, + yResolution, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Image = apply { + if (validated) { + return@apply + } + + exifOffset() + gpsInfo() + make() + model() + modifyDate() + orientation() + resolutionUnit() + software() + xResolution() + yCbCrPositioning() + yResolution() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (exifOffset.asKnown().isPresent) 1 else 0) + + (if (gpsInfo.asKnown().isPresent) 1 else 0) + + (if (make.asKnown().isPresent) 1 else 0) + + (if (model.asKnown().isPresent) 1 else 0) + + (if (modifyDate.asKnown().isPresent) 1 else 0) + + (if (orientation.asKnown().isPresent) 1 else 0) + + (if (resolutionUnit.asKnown().isPresent) 1 else 0) + + (if (software.asKnown().isPresent) 1 else 0) + + (if (xResolution.asKnown().isPresent) 1 else 0) + + (if (yCbCrPositioning.asKnown().isPresent) 1 else 0) + + (if (yResolution.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Image && + exifOffset == other.exifOffset && + gpsInfo == other.gpsInfo && + make == other.make && + model == other.model && + modifyDate == other.modifyDate && + orientation == other.orientation && + resolutionUnit == other.resolutionUnit && + software == other.software && + xResolution == other.xResolution && + yCbCrPositioning == other.yCbCrPositioning && + yResolution == other.yResolution && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + exifOffset, + gpsInfo, + make, + model, + modifyDate, + orientation, + resolutionUnit, + software, + xResolution, + yCbCrPositioning, + yResolution, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Image{exifOffset=$exifOffset, gpsInfo=$gpsInfo, make=$make, model=$model, modifyDate=$modifyDate, orientation=$orientation, resolutionUnit=$resolutionUnit, software=$software, xResolution=$xResolution, yCbCrPositioning=$yCbCrPositioning, yResolution=$yResolution, additionalProperties=$additionalProperties}" + } + + /** JSON object. */ + class Interoperability + private constructor( + private val interopIndex: JsonField, + private val interopVersion: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("InteropIndex") + @ExcludeMissing + interopIndex: JsonField = JsonMissing.of(), + @JsonProperty("InteropVersion") + @ExcludeMissing + interopVersion: JsonField = JsonMissing.of(), + ) : this(interopIndex, interopVersion, mutableMapOf()) + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun interopIndex(): Optional = interopIndex.getOptional("InteropIndex") + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun interopVersion(): Optional = interopVersion.getOptional("InteropVersion") + + /** + * Returns the raw JSON value of [interopIndex]. + * + * Unlike [interopIndex], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("InteropIndex") + @ExcludeMissing + fun _interopIndex(): JsonField = interopIndex + + /** + * Returns the raw JSON value of [interopVersion]. + * + * Unlike [interopVersion], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("InteropVersion") + @ExcludeMissing + fun _interopVersion(): JsonField = interopVersion + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Interoperability]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Interoperability]. */ + class Builder internal constructor() { + + private var interopIndex: JsonField = JsonMissing.of() + private var interopVersion: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(interoperability: Interoperability) = apply { + interopIndex = interoperability.interopIndex + interopVersion = interoperability.interopVersion + additionalProperties = interoperability.additionalProperties.toMutableMap() + } + + fun interopIndex(interopIndex: String) = interopIndex(JsonField.of(interopIndex)) + + /** + * Sets [Builder.interopIndex] to an arbitrary JSON value. + * + * You should usually call [Builder.interopIndex] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun interopIndex(interopIndex: JsonField) = apply { + this.interopIndex = interopIndex + } + + fun interopVersion(interopVersion: String) = + interopVersion(JsonField.of(interopVersion)) + + /** + * Sets [Builder.interopVersion] to an arbitrary JSON value. + * + * You should usually call [Builder.interopVersion] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun interopVersion(interopVersion: JsonField) = apply { + this.interopVersion = interopVersion + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Interoperability]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Interoperability = + Interoperability( + interopIndex, + interopVersion, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Interoperability = apply { + if (validated) { + return@apply + } + + interopIndex() + interopVersion() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (interopIndex.asKnown().isPresent) 1 else 0) + + (if (interopVersion.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Interoperability && + interopIndex == other.interopIndex && + interopVersion == other.interopVersion && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(interopIndex, interopVersion, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Interoperability{interopIndex=$interopIndex, interopVersion=$interopVersion, additionalProperties=$additionalProperties}" + } + + class Makernote + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Makernote]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Makernote]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(makernote: Makernote) = apply { + additionalProperties = makernote.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Makernote]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Makernote = Makernote(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): Makernote = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Makernote && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "Makernote{additionalProperties=$additionalProperties}" + } + + /** Object containing Thumbnail information. */ + class Thumbnail + private constructor( + private val compression: JsonField, + private val resolutionUnit: JsonField, + private val thumbnailLength: JsonField, + private val thumbnailOffset: JsonField, + private val xResolution: JsonField, + private val yResolution: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("Compression") + @ExcludeMissing + compression: JsonField = JsonMissing.of(), + @JsonProperty("ResolutionUnit") + @ExcludeMissing + resolutionUnit: JsonField = JsonMissing.of(), + @JsonProperty("ThumbnailLength") + @ExcludeMissing + thumbnailLength: JsonField = JsonMissing.of(), + @JsonProperty("ThumbnailOffset") + @ExcludeMissing + thumbnailOffset: JsonField = JsonMissing.of(), + @JsonProperty("XResolution") + @ExcludeMissing + xResolution: JsonField = JsonMissing.of(), + @JsonProperty("YResolution") + @ExcludeMissing + yResolution: JsonField = JsonMissing.of(), + ) : this( + compression, + resolutionUnit, + thumbnailLength, + thumbnailOffset, + xResolution, + yResolution, + mutableMapOf(), + ) + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun compression(): Optional = compression.getOptional("Compression") + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun resolutionUnit(): Optional = resolutionUnit.getOptional("ResolutionUnit") + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun thumbnailLength(): Optional = thumbnailLength.getOptional("ThumbnailLength") + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun thumbnailOffset(): Optional = thumbnailOffset.getOptional("ThumbnailOffset") + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun xResolution(): Optional = xResolution.getOptional("XResolution") + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun yResolution(): Optional = yResolution.getOptional("YResolution") + + /** + * Returns the raw JSON value of [compression]. + * + * Unlike [compression], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("Compression") + @ExcludeMissing + fun _compression(): JsonField = compression + + /** + * Returns the raw JSON value of [resolutionUnit]. + * + * Unlike [resolutionUnit], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("ResolutionUnit") + @ExcludeMissing + fun _resolutionUnit(): JsonField = resolutionUnit + + /** + * Returns the raw JSON value of [thumbnailLength]. + * + * Unlike [thumbnailLength], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("ThumbnailLength") + @ExcludeMissing + fun _thumbnailLength(): JsonField = thumbnailLength + + /** + * Returns the raw JSON value of [thumbnailOffset]. + * + * Unlike [thumbnailOffset], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("ThumbnailOffset") + @ExcludeMissing + fun _thumbnailOffset(): JsonField = thumbnailOffset + + /** + * Returns the raw JSON value of [xResolution]. + * + * Unlike [xResolution], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("XResolution") + @ExcludeMissing + fun _xResolution(): JsonField = xResolution + + /** + * Returns the raw JSON value of [yResolution]. + * + * Unlike [yResolution], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("YResolution") + @ExcludeMissing + fun _yResolution(): JsonField = yResolution + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Thumbnail]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Thumbnail]. */ + class Builder internal constructor() { + + private var compression: JsonField = JsonMissing.of() + private var resolutionUnit: JsonField = JsonMissing.of() + private var thumbnailLength: JsonField = JsonMissing.of() + private var thumbnailOffset: JsonField = JsonMissing.of() + private var xResolution: JsonField = JsonMissing.of() + private var yResolution: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(thumbnail: Thumbnail) = apply { + compression = thumbnail.compression + resolutionUnit = thumbnail.resolutionUnit + thumbnailLength = thumbnail.thumbnailLength + thumbnailOffset = thumbnail.thumbnailOffset + xResolution = thumbnail.xResolution + yResolution = thumbnail.yResolution + additionalProperties = thumbnail.additionalProperties.toMutableMap() + } + + fun compression(compression: Long) = compression(JsonField.of(compression)) + + /** + * Sets [Builder.compression] to an arbitrary JSON value. + * + * You should usually call [Builder.compression] with a well-typed [Long] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun compression(compression: JsonField) = apply { + this.compression = compression + } + + fun resolutionUnit(resolutionUnit: Long) = + resolutionUnit(JsonField.of(resolutionUnit)) + + /** + * Sets [Builder.resolutionUnit] to an arbitrary JSON value. + * + * You should usually call [Builder.resolutionUnit] with a well-typed [Long] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun resolutionUnit(resolutionUnit: JsonField) = apply { + this.resolutionUnit = resolutionUnit + } + + fun thumbnailLength(thumbnailLength: Long) = + thumbnailLength(JsonField.of(thumbnailLength)) + + /** + * Sets [Builder.thumbnailLength] to an arbitrary JSON value. + * + * You should usually call [Builder.thumbnailLength] with a well-typed [Long] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun thumbnailLength(thumbnailLength: JsonField) = apply { + this.thumbnailLength = thumbnailLength + } + + fun thumbnailOffset(thumbnailOffset: Long) = + thumbnailOffset(JsonField.of(thumbnailOffset)) + + /** + * Sets [Builder.thumbnailOffset] to an arbitrary JSON value. + * + * You should usually call [Builder.thumbnailOffset] with a well-typed [Long] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun thumbnailOffset(thumbnailOffset: JsonField) = apply { + this.thumbnailOffset = thumbnailOffset + } + + fun xResolution(xResolution: Long) = xResolution(JsonField.of(xResolution)) + + /** + * Sets [Builder.xResolution] to an arbitrary JSON value. + * + * You should usually call [Builder.xResolution] with a well-typed [Long] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun xResolution(xResolution: JsonField) = apply { + this.xResolution = xResolution + } + + fun yResolution(yResolution: Long) = yResolution(JsonField.of(yResolution)) + + /** + * Sets [Builder.yResolution] to an arbitrary JSON value. + * + * You should usually call [Builder.yResolution] with a well-typed [Long] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun yResolution(yResolution: JsonField) = apply { + this.yResolution = yResolution + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Thumbnail]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Thumbnail = + Thumbnail( + compression, + resolutionUnit, + thumbnailLength, + thumbnailOffset, + xResolution, + yResolution, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Thumbnail = apply { + if (validated) { + return@apply + } + + compression() + resolutionUnit() + thumbnailLength() + thumbnailOffset() + xResolution() + yResolution() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (compression.asKnown().isPresent) 1 else 0) + + (if (resolutionUnit.asKnown().isPresent) 1 else 0) + + (if (thumbnailLength.asKnown().isPresent) 1 else 0) + + (if (thumbnailOffset.asKnown().isPresent) 1 else 0) + + (if (xResolution.asKnown().isPresent) 1 else 0) + + (if (yResolution.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Thumbnail && + compression == other.compression && + resolutionUnit == other.resolutionUnit && + thumbnailLength == other.thumbnailLength && + thumbnailOffset == other.thumbnailOffset && + xResolution == other.xResolution && + yResolution == other.yResolution && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + compression, + resolutionUnit, + thumbnailLength, + thumbnailOffset, + xResolution, + yResolution, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Thumbnail{compression=$compression, resolutionUnit=$resolutionUnit, thumbnailLength=$thumbnailLength, thumbnailOffset=$thumbnailOffset, xResolution=$xResolution, yResolution=$yResolution, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Exif && + exif == other.exif && + gps == other.gps && + image == other.image && + interoperability == other.interoperability && + makernote == other.makernote && + thumbnail == other.thumbnail && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + exif, + gps, + image, + interoperability, + makernote, + thumbnail, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Exif{exif=$exif, gps=$gps, image=$image, interoperability=$interoperability, makernote=$makernote, thumbnail=$thumbnail, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Metadata && + audioCodec == other.audioCodec && + bitRate == other.bitRate && + density == other.density && + duration == other.duration && + exif == other.exif && + format == other.format && + hasColorProfile == other.hasColorProfile && + hasTransparency == other.hasTransparency && + height == other.height && + pHash == other.pHash && + quality == other.quality && + size == other.size && + videoCodec == other.videoCodec && + width == other.width && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + audioCodec, + bitRate, + density, + duration, + exif, + format, + hasColorProfile, + hasTransparency, + height, + pHash, + quality, + size, + videoCodec, + width, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Metadata{audioCodec=$audioCodec, bitRate=$bitRate, density=$density, duration=$duration, exif=$exif, format=$format, hasColorProfile=$hasColorProfile, hasTransparency=$hasTransparency, height=$height, pHash=$pHash, quality=$quality, size=$size, videoCodec=$videoCodec, width=$width, additionalProperties=$additionalProperties}" +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/files/bulk/BulkAddTagsParams.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/files/bulk/BulkAddTagsParams.kt new file mode 100644 index 0000000..c59c520 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/files/bulk/BulkAddTagsParams.kt @@ -0,0 +1,533 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.files.bulk + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.imagekit.api.core.ExcludeMissing +import com.imagekit.api.core.JsonField +import com.imagekit.api.core.JsonMissing +import com.imagekit.api.core.JsonValue +import com.imagekit.api.core.Params +import com.imagekit.api.core.checkKnown +import com.imagekit.api.core.checkRequired +import com.imagekit.api.core.http.Headers +import com.imagekit.api.core.http.QueryParams +import com.imagekit.api.core.toImmutable +import com.imagekit.api.errors.ImageKitInvalidDataException +import java.util.Collections +import java.util.Objects +import kotlin.jvm.optionals.getOrNull + +/** + * This API adds tags to multiple files in bulk. A maximum of 50 files can be specified at a time. + */ +class BulkAddTagsParams +private constructor( + private val body: Body, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** + * An array of fileIds to which you want to add tags. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun fileIds(): List = body.fileIds() + + /** + * An array of tags that you want to add to the files. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun tags(): List = body.tags() + + /** + * Returns the raw JSON value of [fileIds]. + * + * Unlike [fileIds], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _fileIds(): JsonField> = body._fileIds() + + /** + * Returns the raw JSON value of [tags]. + * + * Unlike [tags], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _tags(): JsonField> = body._tags() + + fun _additionalBodyProperties(): Map = body._additionalProperties() + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [BulkAddTagsParams]. + * + * The following fields are required: + * ```java + * .fileIds() + * .tags() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [BulkAddTagsParams]. */ + class Builder internal constructor() { + + private var body: Body.Builder = Body.builder() + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + + @JvmSynthetic + internal fun from(bulkAddTagsParams: BulkAddTagsParams) = apply { + body = bulkAddTagsParams.body.toBuilder() + additionalHeaders = bulkAddTagsParams.additionalHeaders.toBuilder() + additionalQueryParams = bulkAddTagsParams.additionalQueryParams.toBuilder() + } + + /** + * Sets the entire request body. + * + * This is generally only useful if you are already constructing the body separately. + * Otherwise, it's more convenient to use the top-level setters instead: + * - [fileIds] + * - [tags] + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } + + /** An array of fileIds to which you want to add tags. */ + fun fileIds(fileIds: List) = apply { body.fileIds(fileIds) } + + /** + * Sets [Builder.fileIds] to an arbitrary JSON value. + * + * You should usually call [Builder.fileIds] with a well-typed `List` value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun fileIds(fileIds: JsonField>) = apply { body.fileIds(fileIds) } + + /** + * Adds a single [String] to [fileIds]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addFileId(fileId: String) = apply { body.addFileId(fileId) } + + /** An array of tags that you want to add to the files. */ + fun tags(tags: List) = apply { body.tags(tags) } + + /** + * Sets [Builder.tags] to an arbitrary JSON value. + * + * You should usually call [Builder.tags] with a well-typed `List` value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun tags(tags: JsonField>) = apply { body.tags(tags) } + + /** + * Adds a single [String] to [tags]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addTag(tag: String) = apply { body.addTag(tag) } + + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + body.additionalProperties(additionalBodyProperties) + } + + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + body.putAdditionalProperty(key, value) + } + + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + body.putAllAdditionalProperties(additionalBodyProperties) + } + + fun removeAdditionalBodyProperty(key: String) = apply { body.removeAdditionalProperty(key) } + + fun removeAllAdditionalBodyProperties(keys: Set) = apply { + body.removeAllAdditionalProperties(keys) + } + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + /** + * Returns an immutable instance of [BulkAddTagsParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .fileIds() + * .tags() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): BulkAddTagsParams = + BulkAddTagsParams( + body.build(), + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } + + fun _body(): Body = body + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + class Body + private constructor( + private val fileIds: JsonField>, + private val tags: JsonField>, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("fileIds") + @ExcludeMissing + fileIds: JsonField> = JsonMissing.of(), + @JsonProperty("tags") @ExcludeMissing tags: JsonField> = JsonMissing.of(), + ) : this(fileIds, tags, mutableMapOf()) + + /** + * An array of fileIds to which you want to add tags. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun fileIds(): List = fileIds.getRequired("fileIds") + + /** + * An array of tags that you want to add to the files. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun tags(): List = tags.getRequired("tags") + + /** + * Returns the raw JSON value of [fileIds]. + * + * Unlike [fileIds], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("fileIds") @ExcludeMissing fun _fileIds(): JsonField> = fileIds + + /** + * Returns the raw JSON value of [tags]. + * + * Unlike [tags], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("tags") @ExcludeMissing fun _tags(): JsonField> = tags + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Body]. + * + * The following fields are required: + * ```java + * .fileIds() + * .tags() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Body]. */ + class Builder internal constructor() { + + private var fileIds: JsonField>? = null + private var tags: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(body: Body) = apply { + fileIds = body.fileIds.map { it.toMutableList() } + tags = body.tags.map { it.toMutableList() } + additionalProperties = body.additionalProperties.toMutableMap() + } + + /** An array of fileIds to which you want to add tags. */ + fun fileIds(fileIds: List) = fileIds(JsonField.of(fileIds)) + + /** + * Sets [Builder.fileIds] to an arbitrary JSON value. + * + * You should usually call [Builder.fileIds] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun fileIds(fileIds: JsonField>) = apply { + this.fileIds = fileIds.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [fileIds]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addFileId(fileId: String) = apply { + fileIds = + (fileIds ?: JsonField.of(mutableListOf())).also { + checkKnown("fileIds", it).add(fileId) + } + } + + /** An array of tags that you want to add to the files. */ + fun tags(tags: List) = tags(JsonField.of(tags)) + + /** + * Sets [Builder.tags] to an arbitrary JSON value. + * + * You should usually call [Builder.tags] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun tags(tags: JsonField>) = apply { + this.tags = tags.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [tags]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addTag(tag: String) = apply { + tags = + (tags ?: JsonField.of(mutableListOf())).also { checkKnown("tags", it).add(tag) } + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Body]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .fileIds() + * .tags() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Body = + Body( + checkRequired("fileIds", fileIds).map { it.toImmutable() }, + checkRequired("tags", tags).map { it.toImmutable() }, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Body = apply { + if (validated) { + return@apply + } + + fileIds() + tags() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (fileIds.asKnown().getOrNull()?.size ?: 0) + (tags.asKnown().getOrNull()?.size ?: 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Body && + fileIds == other.fileIds && + tags == other.tags && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(fileIds, tags, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Body{fileIds=$fileIds, tags=$tags, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is BulkAddTagsParams && + body == other.body && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = Objects.hash(body, additionalHeaders, additionalQueryParams) + + override fun toString() = + "BulkAddTagsParams{body=$body, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/files/bulk/BulkAddTagsResponse.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/files/bulk/BulkAddTagsResponse.kt new file mode 100644 index 0000000..2cfbf74 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/files/bulk/BulkAddTagsResponse.kt @@ -0,0 +1,189 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.files.bulk + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.imagekit.api.core.ExcludeMissing +import com.imagekit.api.core.JsonField +import com.imagekit.api.core.JsonMissing +import com.imagekit.api.core.JsonValue +import com.imagekit.api.core.checkKnown +import com.imagekit.api.core.toImmutable +import com.imagekit.api.errors.ImageKitInvalidDataException +import java.util.Collections +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +class BulkAddTagsResponse +private constructor( + private val successfullyUpdatedFileIds: JsonField>, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("successfullyUpdatedFileIds") + @ExcludeMissing + successfullyUpdatedFileIds: JsonField> = JsonMissing.of() + ) : this(successfullyUpdatedFileIds, mutableMapOf()) + + /** + * An array of fileIds that in which tags were successfully added. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun successfullyUpdatedFileIds(): Optional> = + successfullyUpdatedFileIds.getOptional("successfullyUpdatedFileIds") + + /** + * Returns the raw JSON value of [successfullyUpdatedFileIds]. + * + * Unlike [successfullyUpdatedFileIds], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("successfullyUpdatedFileIds") + @ExcludeMissing + fun _successfullyUpdatedFileIds(): JsonField> = successfullyUpdatedFileIds + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [BulkAddTagsResponse]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [BulkAddTagsResponse]. */ + class Builder internal constructor() { + + private var successfullyUpdatedFileIds: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(bulkAddTagsResponse: BulkAddTagsResponse) = apply { + successfullyUpdatedFileIds = + bulkAddTagsResponse.successfullyUpdatedFileIds.map { it.toMutableList() } + additionalProperties = bulkAddTagsResponse.additionalProperties.toMutableMap() + } + + /** An array of fileIds that in which tags were successfully added. */ + fun successfullyUpdatedFileIds(successfullyUpdatedFileIds: List) = + successfullyUpdatedFileIds(JsonField.of(successfullyUpdatedFileIds)) + + /** + * Sets [Builder.successfullyUpdatedFileIds] to an arbitrary JSON value. + * + * You should usually call [Builder.successfullyUpdatedFileIds] with a well-typed + * `List` value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun successfullyUpdatedFileIds(successfullyUpdatedFileIds: JsonField>) = + apply { + this.successfullyUpdatedFileIds = + successfullyUpdatedFileIds.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [successfullyUpdatedFileIds]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addSuccessfullyUpdatedFileId(successfullyUpdatedFileId: String) = apply { + successfullyUpdatedFileIds = + (successfullyUpdatedFileIds ?: JsonField.of(mutableListOf())).also { + checkKnown("successfullyUpdatedFileIds", it).add(successfullyUpdatedFileId) + } + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [BulkAddTagsResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): BulkAddTagsResponse = + BulkAddTagsResponse( + (successfullyUpdatedFileIds ?: JsonMissing.of()).map { it.toImmutable() }, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): BulkAddTagsResponse = apply { + if (validated) { + return@apply + } + + successfullyUpdatedFileIds() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = (successfullyUpdatedFileIds.asKnown().getOrNull()?.size ?: 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is BulkAddTagsResponse && + successfullyUpdatedFileIds == other.successfullyUpdatedFileIds && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(successfullyUpdatedFileIds, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "BulkAddTagsResponse{successfullyUpdatedFileIds=$successfullyUpdatedFileIds, additionalProperties=$additionalProperties}" +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/files/bulk/BulkDeleteParams.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/files/bulk/BulkDeleteParams.kt new file mode 100644 index 0000000..e27e8f4 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/files/bulk/BulkDeleteParams.kt @@ -0,0 +1,447 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.files.bulk + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.imagekit.api.core.ExcludeMissing +import com.imagekit.api.core.JsonField +import com.imagekit.api.core.JsonMissing +import com.imagekit.api.core.JsonValue +import com.imagekit.api.core.Params +import com.imagekit.api.core.checkKnown +import com.imagekit.api.core.checkRequired +import com.imagekit.api.core.http.Headers +import com.imagekit.api.core.http.QueryParams +import com.imagekit.api.core.toImmutable +import com.imagekit.api.errors.ImageKitInvalidDataException +import java.util.Collections +import java.util.Objects +import kotlin.jvm.optionals.getOrNull + +/** + * This API deletes multiple files and all their file versions permanently. + * + * Note: If a file or specific transformation has been requested in the past, then the response is + * cached. Deleting a file does not purge the cache. You can purge the cache using purge cache API. + * + * A maximum of 100 files can be deleted at a time. + */ +class BulkDeleteParams +private constructor( + private val body: Body, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** + * An array of fileIds which you want to delete. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun fileIds(): List = body.fileIds() + + /** + * Returns the raw JSON value of [fileIds]. + * + * Unlike [fileIds], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _fileIds(): JsonField> = body._fileIds() + + fun _additionalBodyProperties(): Map = body._additionalProperties() + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [BulkDeleteParams]. + * + * The following fields are required: + * ```java + * .fileIds() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [BulkDeleteParams]. */ + class Builder internal constructor() { + + private var body: Body.Builder = Body.builder() + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + + @JvmSynthetic + internal fun from(bulkDeleteParams: BulkDeleteParams) = apply { + body = bulkDeleteParams.body.toBuilder() + additionalHeaders = bulkDeleteParams.additionalHeaders.toBuilder() + additionalQueryParams = bulkDeleteParams.additionalQueryParams.toBuilder() + } + + /** + * Sets the entire request body. + * + * This is generally only useful if you are already constructing the body separately. + * Otherwise, it's more convenient to use the top-level setters instead: + * - [fileIds] + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } + + /** An array of fileIds which you want to delete. */ + fun fileIds(fileIds: List) = apply { body.fileIds(fileIds) } + + /** + * Sets [Builder.fileIds] to an arbitrary JSON value. + * + * You should usually call [Builder.fileIds] with a well-typed `List` value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun fileIds(fileIds: JsonField>) = apply { body.fileIds(fileIds) } + + /** + * Adds a single [String] to [fileIds]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addFileId(fileId: String) = apply { body.addFileId(fileId) } + + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + body.additionalProperties(additionalBodyProperties) + } + + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + body.putAdditionalProperty(key, value) + } + + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + body.putAllAdditionalProperties(additionalBodyProperties) + } + + fun removeAdditionalBodyProperty(key: String) = apply { body.removeAdditionalProperty(key) } + + fun removeAllAdditionalBodyProperties(keys: Set) = apply { + body.removeAllAdditionalProperties(keys) + } + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + /** + * Returns an immutable instance of [BulkDeleteParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .fileIds() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): BulkDeleteParams = + BulkDeleteParams(body.build(), additionalHeaders.build(), additionalQueryParams.build()) + } + + fun _body(): Body = body + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + class Body + private constructor( + private val fileIds: JsonField>, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("fileIds") + @ExcludeMissing + fileIds: JsonField> = JsonMissing.of() + ) : this(fileIds, mutableMapOf()) + + /** + * An array of fileIds which you want to delete. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun fileIds(): List = fileIds.getRequired("fileIds") + + /** + * Returns the raw JSON value of [fileIds]. + * + * Unlike [fileIds], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("fileIds") @ExcludeMissing fun _fileIds(): JsonField> = fileIds + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Body]. + * + * The following fields are required: + * ```java + * .fileIds() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Body]. */ + class Builder internal constructor() { + + private var fileIds: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(body: Body) = apply { + fileIds = body.fileIds.map { it.toMutableList() } + additionalProperties = body.additionalProperties.toMutableMap() + } + + /** An array of fileIds which you want to delete. */ + fun fileIds(fileIds: List) = fileIds(JsonField.of(fileIds)) + + /** + * Sets [Builder.fileIds] to an arbitrary JSON value. + * + * You should usually call [Builder.fileIds] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun fileIds(fileIds: JsonField>) = apply { + this.fileIds = fileIds.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [fileIds]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addFileId(fileId: String) = apply { + fileIds = + (fileIds ?: JsonField.of(mutableListOf())).also { + checkKnown("fileIds", it).add(fileId) + } + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Body]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .fileIds() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Body = + Body( + checkRequired("fileIds", fileIds).map { it.toImmutable() }, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Body = apply { + if (validated) { + return@apply + } + + fileIds() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = (fileIds.asKnown().getOrNull()?.size ?: 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Body && + fileIds == other.fileIds && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(fileIds, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Body{fileIds=$fileIds, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is BulkDeleteParams && + body == other.body && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = Objects.hash(body, additionalHeaders, additionalQueryParams) + + override fun toString() = + "BulkDeleteParams{body=$body, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/files/bulk/BulkDeleteResponse.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/files/bulk/BulkDeleteResponse.kt new file mode 100644 index 0000000..10b9af2 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/files/bulk/BulkDeleteResponse.kt @@ -0,0 +1,189 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.files.bulk + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.imagekit.api.core.ExcludeMissing +import com.imagekit.api.core.JsonField +import com.imagekit.api.core.JsonMissing +import com.imagekit.api.core.JsonValue +import com.imagekit.api.core.checkKnown +import com.imagekit.api.core.toImmutable +import com.imagekit.api.errors.ImageKitInvalidDataException +import java.util.Collections +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +class BulkDeleteResponse +private constructor( + private val successfullyDeletedFileIds: JsonField>, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("successfullyDeletedFileIds") + @ExcludeMissing + successfullyDeletedFileIds: JsonField> = JsonMissing.of() + ) : this(successfullyDeletedFileIds, mutableMapOf()) + + /** + * An array of fileIds that were successfully deleted. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun successfullyDeletedFileIds(): Optional> = + successfullyDeletedFileIds.getOptional("successfullyDeletedFileIds") + + /** + * Returns the raw JSON value of [successfullyDeletedFileIds]. + * + * Unlike [successfullyDeletedFileIds], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("successfullyDeletedFileIds") + @ExcludeMissing + fun _successfullyDeletedFileIds(): JsonField> = successfullyDeletedFileIds + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [BulkDeleteResponse]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [BulkDeleteResponse]. */ + class Builder internal constructor() { + + private var successfullyDeletedFileIds: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(bulkDeleteResponse: BulkDeleteResponse) = apply { + successfullyDeletedFileIds = + bulkDeleteResponse.successfullyDeletedFileIds.map { it.toMutableList() } + additionalProperties = bulkDeleteResponse.additionalProperties.toMutableMap() + } + + /** An array of fileIds that were successfully deleted. */ + fun successfullyDeletedFileIds(successfullyDeletedFileIds: List) = + successfullyDeletedFileIds(JsonField.of(successfullyDeletedFileIds)) + + /** + * Sets [Builder.successfullyDeletedFileIds] to an arbitrary JSON value. + * + * You should usually call [Builder.successfullyDeletedFileIds] with a well-typed + * `List` value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun successfullyDeletedFileIds(successfullyDeletedFileIds: JsonField>) = + apply { + this.successfullyDeletedFileIds = + successfullyDeletedFileIds.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [successfullyDeletedFileIds]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addSuccessfullyDeletedFileId(successfullyDeletedFileId: String) = apply { + successfullyDeletedFileIds = + (successfullyDeletedFileIds ?: JsonField.of(mutableListOf())).also { + checkKnown("successfullyDeletedFileIds", it).add(successfullyDeletedFileId) + } + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [BulkDeleteResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): BulkDeleteResponse = + BulkDeleteResponse( + (successfullyDeletedFileIds ?: JsonMissing.of()).map { it.toImmutable() }, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): BulkDeleteResponse = apply { + if (validated) { + return@apply + } + + successfullyDeletedFileIds() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = (successfullyDeletedFileIds.asKnown().getOrNull()?.size ?: 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is BulkDeleteResponse && + successfullyDeletedFileIds == other.successfullyDeletedFileIds && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(successfullyDeletedFileIds, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "BulkDeleteResponse{successfullyDeletedFileIds=$successfullyDeletedFileIds, additionalProperties=$additionalProperties}" +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/files/bulk/BulkRemoveAiTagsParams.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/files/bulk/BulkRemoveAiTagsParams.kt new file mode 100644 index 0000000..f22a019 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/files/bulk/BulkRemoveAiTagsParams.kt @@ -0,0 +1,538 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.files.bulk + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.imagekit.api.core.ExcludeMissing +import com.imagekit.api.core.JsonField +import com.imagekit.api.core.JsonMissing +import com.imagekit.api.core.JsonValue +import com.imagekit.api.core.Params +import com.imagekit.api.core.checkKnown +import com.imagekit.api.core.checkRequired +import com.imagekit.api.core.http.Headers +import com.imagekit.api.core.http.QueryParams +import com.imagekit.api.core.toImmutable +import com.imagekit.api.errors.ImageKitInvalidDataException +import java.util.Collections +import java.util.Objects +import kotlin.jvm.optionals.getOrNull + +/** + * This API removes AITags from multiple files in bulk. A maximum of 50 files can be specified at a + * time. + */ +class BulkRemoveAiTagsParams +private constructor( + private val body: Body, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** + * An array of AITags that you want to remove from the files. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun aiTags(): List = body.aiTags() + + /** + * An array of fileIds from which you want to remove AITags. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun fileIds(): List = body.fileIds() + + /** + * Returns the raw JSON value of [aiTags]. + * + * Unlike [aiTags], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _aiTags(): JsonField> = body._aiTags() + + /** + * Returns the raw JSON value of [fileIds]. + * + * Unlike [fileIds], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _fileIds(): JsonField> = body._fileIds() + + fun _additionalBodyProperties(): Map = body._additionalProperties() + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [BulkRemoveAiTagsParams]. + * + * The following fields are required: + * ```java + * .aiTags() + * .fileIds() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [BulkRemoveAiTagsParams]. */ + class Builder internal constructor() { + + private var body: Body.Builder = Body.builder() + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + + @JvmSynthetic + internal fun from(bulkRemoveAiTagsParams: BulkRemoveAiTagsParams) = apply { + body = bulkRemoveAiTagsParams.body.toBuilder() + additionalHeaders = bulkRemoveAiTagsParams.additionalHeaders.toBuilder() + additionalQueryParams = bulkRemoveAiTagsParams.additionalQueryParams.toBuilder() + } + + /** + * Sets the entire request body. + * + * This is generally only useful if you are already constructing the body separately. + * Otherwise, it's more convenient to use the top-level setters instead: + * - [aiTags] + * - [fileIds] + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } + + /** An array of AITags that you want to remove from the files. */ + fun aiTags(aiTags: List) = apply { body.aiTags(aiTags) } + + /** + * Sets [Builder.aiTags] to an arbitrary JSON value. + * + * You should usually call [Builder.aiTags] with a well-typed `List` value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun aiTags(aiTags: JsonField>) = apply { body.aiTags(aiTags) } + + /** + * Adds a single [String] to [aiTags]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addAiTag(aiTag: String) = apply { body.addAiTag(aiTag) } + + /** An array of fileIds from which you want to remove AITags. */ + fun fileIds(fileIds: List) = apply { body.fileIds(fileIds) } + + /** + * Sets [Builder.fileIds] to an arbitrary JSON value. + * + * You should usually call [Builder.fileIds] with a well-typed `List` value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun fileIds(fileIds: JsonField>) = apply { body.fileIds(fileIds) } + + /** + * Adds a single [String] to [fileIds]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addFileId(fileId: String) = apply { body.addFileId(fileId) } + + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + body.additionalProperties(additionalBodyProperties) + } + + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + body.putAdditionalProperty(key, value) + } + + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + body.putAllAdditionalProperties(additionalBodyProperties) + } + + fun removeAdditionalBodyProperty(key: String) = apply { body.removeAdditionalProperty(key) } + + fun removeAllAdditionalBodyProperties(keys: Set) = apply { + body.removeAllAdditionalProperties(keys) + } + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + /** + * Returns an immutable instance of [BulkRemoveAiTagsParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .aiTags() + * .fileIds() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): BulkRemoveAiTagsParams = + BulkRemoveAiTagsParams( + body.build(), + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } + + fun _body(): Body = body + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + class Body + private constructor( + private val aiTags: JsonField>, + private val fileIds: JsonField>, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("AITags") + @ExcludeMissing + aiTags: JsonField> = JsonMissing.of(), + @JsonProperty("fileIds") + @ExcludeMissing + fileIds: JsonField> = JsonMissing.of(), + ) : this(aiTags, fileIds, mutableMapOf()) + + /** + * An array of AITags that you want to remove from the files. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun aiTags(): List = aiTags.getRequired("AITags") + + /** + * An array of fileIds from which you want to remove AITags. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun fileIds(): List = fileIds.getRequired("fileIds") + + /** + * Returns the raw JSON value of [aiTags]. + * + * Unlike [aiTags], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("AITags") @ExcludeMissing fun _aiTags(): JsonField> = aiTags + + /** + * Returns the raw JSON value of [fileIds]. + * + * Unlike [fileIds], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("fileIds") @ExcludeMissing fun _fileIds(): JsonField> = fileIds + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Body]. + * + * The following fields are required: + * ```java + * .aiTags() + * .fileIds() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Body]. */ + class Builder internal constructor() { + + private var aiTags: JsonField>? = null + private var fileIds: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(body: Body) = apply { + aiTags = body.aiTags.map { it.toMutableList() } + fileIds = body.fileIds.map { it.toMutableList() } + additionalProperties = body.additionalProperties.toMutableMap() + } + + /** An array of AITags that you want to remove from the files. */ + fun aiTags(aiTags: List) = aiTags(JsonField.of(aiTags)) + + /** + * Sets [Builder.aiTags] to an arbitrary JSON value. + * + * You should usually call [Builder.aiTags] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun aiTags(aiTags: JsonField>) = apply { + this.aiTags = aiTags.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [aiTags]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addAiTag(aiTag: String) = apply { + aiTags = + (aiTags ?: JsonField.of(mutableListOf())).also { + checkKnown("aiTags", it).add(aiTag) + } + } + + /** An array of fileIds from which you want to remove AITags. */ + fun fileIds(fileIds: List) = fileIds(JsonField.of(fileIds)) + + /** + * Sets [Builder.fileIds] to an arbitrary JSON value. + * + * You should usually call [Builder.fileIds] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun fileIds(fileIds: JsonField>) = apply { + this.fileIds = fileIds.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [fileIds]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addFileId(fileId: String) = apply { + fileIds = + (fileIds ?: JsonField.of(mutableListOf())).also { + checkKnown("fileIds", it).add(fileId) + } + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Body]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .aiTags() + * .fileIds() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Body = + Body( + checkRequired("aiTags", aiTags).map { it.toImmutable() }, + checkRequired("fileIds", fileIds).map { it.toImmutable() }, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Body = apply { + if (validated) { + return@apply + } + + aiTags() + fileIds() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (aiTags.asKnown().getOrNull()?.size ?: 0) + (fileIds.asKnown().getOrNull()?.size ?: 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Body && + aiTags == other.aiTags && + fileIds == other.fileIds && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(aiTags, fileIds, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Body{aiTags=$aiTags, fileIds=$fileIds, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is BulkRemoveAiTagsParams && + body == other.body && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = Objects.hash(body, additionalHeaders, additionalQueryParams) + + override fun toString() = + "BulkRemoveAiTagsParams{body=$body, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/files/bulk/BulkRemoveAiTagsResponse.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/files/bulk/BulkRemoveAiTagsResponse.kt new file mode 100644 index 0000000..9d46735 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/files/bulk/BulkRemoveAiTagsResponse.kt @@ -0,0 +1,189 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.files.bulk + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.imagekit.api.core.ExcludeMissing +import com.imagekit.api.core.JsonField +import com.imagekit.api.core.JsonMissing +import com.imagekit.api.core.JsonValue +import com.imagekit.api.core.checkKnown +import com.imagekit.api.core.toImmutable +import com.imagekit.api.errors.ImageKitInvalidDataException +import java.util.Collections +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +class BulkRemoveAiTagsResponse +private constructor( + private val successfullyUpdatedFileIds: JsonField>, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("successfullyUpdatedFileIds") + @ExcludeMissing + successfullyUpdatedFileIds: JsonField> = JsonMissing.of() + ) : this(successfullyUpdatedFileIds, mutableMapOf()) + + /** + * An array of fileIds that in which AITags were successfully removed. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun successfullyUpdatedFileIds(): Optional> = + successfullyUpdatedFileIds.getOptional("successfullyUpdatedFileIds") + + /** + * Returns the raw JSON value of [successfullyUpdatedFileIds]. + * + * Unlike [successfullyUpdatedFileIds], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("successfullyUpdatedFileIds") + @ExcludeMissing + fun _successfullyUpdatedFileIds(): JsonField> = successfullyUpdatedFileIds + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [BulkRemoveAiTagsResponse]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [BulkRemoveAiTagsResponse]. */ + class Builder internal constructor() { + + private var successfullyUpdatedFileIds: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(bulkRemoveAiTagsResponse: BulkRemoveAiTagsResponse) = apply { + successfullyUpdatedFileIds = + bulkRemoveAiTagsResponse.successfullyUpdatedFileIds.map { it.toMutableList() } + additionalProperties = bulkRemoveAiTagsResponse.additionalProperties.toMutableMap() + } + + /** An array of fileIds that in which AITags were successfully removed. */ + fun successfullyUpdatedFileIds(successfullyUpdatedFileIds: List) = + successfullyUpdatedFileIds(JsonField.of(successfullyUpdatedFileIds)) + + /** + * Sets [Builder.successfullyUpdatedFileIds] to an arbitrary JSON value. + * + * You should usually call [Builder.successfullyUpdatedFileIds] with a well-typed + * `List` value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun successfullyUpdatedFileIds(successfullyUpdatedFileIds: JsonField>) = + apply { + this.successfullyUpdatedFileIds = + successfullyUpdatedFileIds.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [successfullyUpdatedFileIds]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addSuccessfullyUpdatedFileId(successfullyUpdatedFileId: String) = apply { + successfullyUpdatedFileIds = + (successfullyUpdatedFileIds ?: JsonField.of(mutableListOf())).also { + checkKnown("successfullyUpdatedFileIds", it).add(successfullyUpdatedFileId) + } + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [BulkRemoveAiTagsResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): BulkRemoveAiTagsResponse = + BulkRemoveAiTagsResponse( + (successfullyUpdatedFileIds ?: JsonMissing.of()).map { it.toImmutable() }, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): BulkRemoveAiTagsResponse = apply { + if (validated) { + return@apply + } + + successfullyUpdatedFileIds() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = (successfullyUpdatedFileIds.asKnown().getOrNull()?.size ?: 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is BulkRemoveAiTagsResponse && + successfullyUpdatedFileIds == other.successfullyUpdatedFileIds && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(successfullyUpdatedFileIds, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "BulkRemoveAiTagsResponse{successfullyUpdatedFileIds=$successfullyUpdatedFileIds, additionalProperties=$additionalProperties}" +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/files/bulk/BulkRemoveTagsParams.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/files/bulk/BulkRemoveTagsParams.kt new file mode 100644 index 0000000..f72a452 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/files/bulk/BulkRemoveTagsParams.kt @@ -0,0 +1,534 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.files.bulk + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.imagekit.api.core.ExcludeMissing +import com.imagekit.api.core.JsonField +import com.imagekit.api.core.JsonMissing +import com.imagekit.api.core.JsonValue +import com.imagekit.api.core.Params +import com.imagekit.api.core.checkKnown +import com.imagekit.api.core.checkRequired +import com.imagekit.api.core.http.Headers +import com.imagekit.api.core.http.QueryParams +import com.imagekit.api.core.toImmutable +import com.imagekit.api.errors.ImageKitInvalidDataException +import java.util.Collections +import java.util.Objects +import kotlin.jvm.optionals.getOrNull + +/** + * This API removes tags from multiple files in bulk. A maximum of 50 files can be specified at a + * time. + */ +class BulkRemoveTagsParams +private constructor( + private val body: Body, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** + * An array of fileIds from which you want to remove tags. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun fileIds(): List = body.fileIds() + + /** + * An array of tags that you want to remove from the files. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun tags(): List = body.tags() + + /** + * Returns the raw JSON value of [fileIds]. + * + * Unlike [fileIds], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _fileIds(): JsonField> = body._fileIds() + + /** + * Returns the raw JSON value of [tags]. + * + * Unlike [tags], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _tags(): JsonField> = body._tags() + + fun _additionalBodyProperties(): Map = body._additionalProperties() + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [BulkRemoveTagsParams]. + * + * The following fields are required: + * ```java + * .fileIds() + * .tags() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [BulkRemoveTagsParams]. */ + class Builder internal constructor() { + + private var body: Body.Builder = Body.builder() + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + + @JvmSynthetic + internal fun from(bulkRemoveTagsParams: BulkRemoveTagsParams) = apply { + body = bulkRemoveTagsParams.body.toBuilder() + additionalHeaders = bulkRemoveTagsParams.additionalHeaders.toBuilder() + additionalQueryParams = bulkRemoveTagsParams.additionalQueryParams.toBuilder() + } + + /** + * Sets the entire request body. + * + * This is generally only useful if you are already constructing the body separately. + * Otherwise, it's more convenient to use the top-level setters instead: + * - [fileIds] + * - [tags] + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } + + /** An array of fileIds from which you want to remove tags. */ + fun fileIds(fileIds: List) = apply { body.fileIds(fileIds) } + + /** + * Sets [Builder.fileIds] to an arbitrary JSON value. + * + * You should usually call [Builder.fileIds] with a well-typed `List` value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun fileIds(fileIds: JsonField>) = apply { body.fileIds(fileIds) } + + /** + * Adds a single [String] to [fileIds]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addFileId(fileId: String) = apply { body.addFileId(fileId) } + + /** An array of tags that you want to remove from the files. */ + fun tags(tags: List) = apply { body.tags(tags) } + + /** + * Sets [Builder.tags] to an arbitrary JSON value. + * + * You should usually call [Builder.tags] with a well-typed `List` value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun tags(tags: JsonField>) = apply { body.tags(tags) } + + /** + * Adds a single [String] to [tags]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addTag(tag: String) = apply { body.addTag(tag) } + + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + body.additionalProperties(additionalBodyProperties) + } + + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + body.putAdditionalProperty(key, value) + } + + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + body.putAllAdditionalProperties(additionalBodyProperties) + } + + fun removeAdditionalBodyProperty(key: String) = apply { body.removeAdditionalProperty(key) } + + fun removeAllAdditionalBodyProperties(keys: Set) = apply { + body.removeAllAdditionalProperties(keys) + } + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + /** + * Returns an immutable instance of [BulkRemoveTagsParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .fileIds() + * .tags() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): BulkRemoveTagsParams = + BulkRemoveTagsParams( + body.build(), + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } + + fun _body(): Body = body + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + class Body + private constructor( + private val fileIds: JsonField>, + private val tags: JsonField>, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("fileIds") + @ExcludeMissing + fileIds: JsonField> = JsonMissing.of(), + @JsonProperty("tags") @ExcludeMissing tags: JsonField> = JsonMissing.of(), + ) : this(fileIds, tags, mutableMapOf()) + + /** + * An array of fileIds from which you want to remove tags. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun fileIds(): List = fileIds.getRequired("fileIds") + + /** + * An array of tags that you want to remove from the files. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun tags(): List = tags.getRequired("tags") + + /** + * Returns the raw JSON value of [fileIds]. + * + * Unlike [fileIds], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("fileIds") @ExcludeMissing fun _fileIds(): JsonField> = fileIds + + /** + * Returns the raw JSON value of [tags]. + * + * Unlike [tags], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("tags") @ExcludeMissing fun _tags(): JsonField> = tags + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Body]. + * + * The following fields are required: + * ```java + * .fileIds() + * .tags() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Body]. */ + class Builder internal constructor() { + + private var fileIds: JsonField>? = null + private var tags: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(body: Body) = apply { + fileIds = body.fileIds.map { it.toMutableList() } + tags = body.tags.map { it.toMutableList() } + additionalProperties = body.additionalProperties.toMutableMap() + } + + /** An array of fileIds from which you want to remove tags. */ + fun fileIds(fileIds: List) = fileIds(JsonField.of(fileIds)) + + /** + * Sets [Builder.fileIds] to an arbitrary JSON value. + * + * You should usually call [Builder.fileIds] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun fileIds(fileIds: JsonField>) = apply { + this.fileIds = fileIds.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [fileIds]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addFileId(fileId: String) = apply { + fileIds = + (fileIds ?: JsonField.of(mutableListOf())).also { + checkKnown("fileIds", it).add(fileId) + } + } + + /** An array of tags that you want to remove from the files. */ + fun tags(tags: List) = tags(JsonField.of(tags)) + + /** + * Sets [Builder.tags] to an arbitrary JSON value. + * + * You should usually call [Builder.tags] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun tags(tags: JsonField>) = apply { + this.tags = tags.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [tags]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addTag(tag: String) = apply { + tags = + (tags ?: JsonField.of(mutableListOf())).also { checkKnown("tags", it).add(tag) } + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Body]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .fileIds() + * .tags() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Body = + Body( + checkRequired("fileIds", fileIds).map { it.toImmutable() }, + checkRequired("tags", tags).map { it.toImmutable() }, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Body = apply { + if (validated) { + return@apply + } + + fileIds() + tags() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (fileIds.asKnown().getOrNull()?.size ?: 0) + (tags.asKnown().getOrNull()?.size ?: 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Body && + fileIds == other.fileIds && + tags == other.tags && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(fileIds, tags, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Body{fileIds=$fileIds, tags=$tags, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is BulkRemoveTagsParams && + body == other.body && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = Objects.hash(body, additionalHeaders, additionalQueryParams) + + override fun toString() = + "BulkRemoveTagsParams{body=$body, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/files/bulk/BulkRemoveTagsResponse.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/files/bulk/BulkRemoveTagsResponse.kt new file mode 100644 index 0000000..0a23ecd --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/files/bulk/BulkRemoveTagsResponse.kt @@ -0,0 +1,189 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.files.bulk + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.imagekit.api.core.ExcludeMissing +import com.imagekit.api.core.JsonField +import com.imagekit.api.core.JsonMissing +import com.imagekit.api.core.JsonValue +import com.imagekit.api.core.checkKnown +import com.imagekit.api.core.toImmutable +import com.imagekit.api.errors.ImageKitInvalidDataException +import java.util.Collections +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +class BulkRemoveTagsResponse +private constructor( + private val successfullyUpdatedFileIds: JsonField>, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("successfullyUpdatedFileIds") + @ExcludeMissing + successfullyUpdatedFileIds: JsonField> = JsonMissing.of() + ) : this(successfullyUpdatedFileIds, mutableMapOf()) + + /** + * An array of fileIds that in which tags were successfully removed. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun successfullyUpdatedFileIds(): Optional> = + successfullyUpdatedFileIds.getOptional("successfullyUpdatedFileIds") + + /** + * Returns the raw JSON value of [successfullyUpdatedFileIds]. + * + * Unlike [successfullyUpdatedFileIds], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("successfullyUpdatedFileIds") + @ExcludeMissing + fun _successfullyUpdatedFileIds(): JsonField> = successfullyUpdatedFileIds + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [BulkRemoveTagsResponse]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [BulkRemoveTagsResponse]. */ + class Builder internal constructor() { + + private var successfullyUpdatedFileIds: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(bulkRemoveTagsResponse: BulkRemoveTagsResponse) = apply { + successfullyUpdatedFileIds = + bulkRemoveTagsResponse.successfullyUpdatedFileIds.map { it.toMutableList() } + additionalProperties = bulkRemoveTagsResponse.additionalProperties.toMutableMap() + } + + /** An array of fileIds that in which tags were successfully removed. */ + fun successfullyUpdatedFileIds(successfullyUpdatedFileIds: List) = + successfullyUpdatedFileIds(JsonField.of(successfullyUpdatedFileIds)) + + /** + * Sets [Builder.successfullyUpdatedFileIds] to an arbitrary JSON value. + * + * You should usually call [Builder.successfullyUpdatedFileIds] with a well-typed + * `List` value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun successfullyUpdatedFileIds(successfullyUpdatedFileIds: JsonField>) = + apply { + this.successfullyUpdatedFileIds = + successfullyUpdatedFileIds.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [successfullyUpdatedFileIds]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addSuccessfullyUpdatedFileId(successfullyUpdatedFileId: String) = apply { + successfullyUpdatedFileIds = + (successfullyUpdatedFileIds ?: JsonField.of(mutableListOf())).also { + checkKnown("successfullyUpdatedFileIds", it).add(successfullyUpdatedFileId) + } + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [BulkRemoveTagsResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): BulkRemoveTagsResponse = + BulkRemoveTagsResponse( + (successfullyUpdatedFileIds ?: JsonMissing.of()).map { it.toImmutable() }, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): BulkRemoveTagsResponse = apply { + if (validated) { + return@apply + } + + successfullyUpdatedFileIds() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = (successfullyUpdatedFileIds.asKnown().getOrNull()?.size ?: 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is BulkRemoveTagsResponse && + successfullyUpdatedFileIds == other.successfullyUpdatedFileIds && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(successfullyUpdatedFileIds, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "BulkRemoveTagsResponse{successfullyUpdatedFileIds=$successfullyUpdatedFileIds, additionalProperties=$additionalProperties}" +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/files/metadata/MetadataGetFromUrlParams.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/files/metadata/MetadataGetFromUrlParams.kt new file mode 100644 index 0000000..a5131a3 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/files/metadata/MetadataGetFromUrlParams.kt @@ -0,0 +1,203 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.files.metadata + +import com.imagekit.api.core.Params +import com.imagekit.api.core.checkRequired +import com.imagekit.api.core.http.Headers +import com.imagekit.api.core.http.QueryParams +import java.util.Objects + +/** Get image EXIF, pHash, and other metadata from ImageKit.io powered remote URL using this API. */ +class MetadataGetFromUrlParams +private constructor( + private val url: String, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** Should be a valid file URL. It should be accessible using your ImageKit.io account. */ + fun url(): String = url + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [MetadataGetFromUrlParams]. + * + * The following fields are required: + * ```java + * .url() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [MetadataGetFromUrlParams]. */ + class Builder internal constructor() { + + private var url: String? = null + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + + @JvmSynthetic + internal fun from(metadataGetFromUrlParams: MetadataGetFromUrlParams) = apply { + url = metadataGetFromUrlParams.url + additionalHeaders = metadataGetFromUrlParams.additionalHeaders.toBuilder() + additionalQueryParams = metadataGetFromUrlParams.additionalQueryParams.toBuilder() + } + + /** Should be a valid file URL. It should be accessible using your ImageKit.io account. */ + fun url(url: String) = apply { this.url = url } + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + /** + * Returns an immutable instance of [MetadataGetFromUrlParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .url() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): MetadataGetFromUrlParams = + MetadataGetFromUrlParams( + checkRequired("url", url), + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = + QueryParams.builder() + .apply { + put("url", url) + putAll(additionalQueryParams) + } + .build() + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is MetadataGetFromUrlParams && + url == other.url && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = Objects.hash(url, additionalHeaders, additionalQueryParams) + + override fun toString() = + "MetadataGetFromUrlParams{url=$url, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/files/metadata/MetadataGetParams.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/files/metadata/MetadataGetParams.kt new file mode 100644 index 0000000..cab27ba --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/files/metadata/MetadataGetParams.kt @@ -0,0 +1,195 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.files.metadata + +import com.imagekit.api.core.Params +import com.imagekit.api.core.http.Headers +import com.imagekit.api.core.http.QueryParams +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** + * You can programmatically get image EXIF, pHash, and other metadata for uploaded files in the + * ImageKit.io media library using this API. + * + * You can also get the metadata in upload API response by passing `metadata` in `responseFields` + * parameter. + */ +class MetadataGetParams +private constructor( + private val fileId: String?, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + fun fileId(): Optional = Optional.ofNullable(fileId) + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun none(): MetadataGetParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [MetadataGetParams]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [MetadataGetParams]. */ + class Builder internal constructor() { + + private var fileId: String? = null + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + + @JvmSynthetic + internal fun from(metadataGetParams: MetadataGetParams) = apply { + fileId = metadataGetParams.fileId + additionalHeaders = metadataGetParams.additionalHeaders.toBuilder() + additionalQueryParams = metadataGetParams.additionalQueryParams.toBuilder() + } + + fun fileId(fileId: String?) = apply { this.fileId = fileId } + + /** Alias for calling [Builder.fileId] with `fileId.orElse(null)`. */ + fun fileId(fileId: Optional) = fileId(fileId.getOrNull()) + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + /** + * Returns an immutable instance of [MetadataGetParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): MetadataGetParams = + MetadataGetParams(fileId, additionalHeaders.build(), additionalQueryParams.build()) + } + + fun _pathParam(index: Int): String = + when (index) { + 0 -> fileId ?: "" + else -> "" + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is MetadataGetParams && + fileId == other.fileId && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = Objects.hash(fileId, additionalHeaders, additionalQueryParams) + + override fun toString() = + "MetadataGetParams{fileId=$fileId, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/files/versions/VersionDeleteParams.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/files/versions/VersionDeleteParams.kt new file mode 100644 index 0000000..f43c522 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/files/versions/VersionDeleteParams.kt @@ -0,0 +1,262 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.files.versions + +import com.imagekit.api.core.JsonValue +import com.imagekit.api.core.Params +import com.imagekit.api.core.checkRequired +import com.imagekit.api.core.http.Headers +import com.imagekit.api.core.http.QueryParams +import com.imagekit.api.core.toImmutable +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** + * This API deletes a non-current file version permanently. The API returns an empty response. + * + * Note: If you want to delete all versions of a file, use the delete file API. + */ +class VersionDeleteParams +private constructor( + private val fileId: String, + private val versionId: String?, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, + private val additionalBodyProperties: Map, +) : Params { + + fun fileId(): String = fileId + + fun versionId(): Optional = Optional.ofNullable(versionId) + + /** Additional body properties to send with the request. */ + fun _additionalBodyProperties(): Map = additionalBodyProperties + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [VersionDeleteParams]. + * + * The following fields are required: + * ```java + * .fileId() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [VersionDeleteParams]. */ + class Builder internal constructor() { + + private var fileId: String? = null + private var versionId: String? = null + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + private var additionalBodyProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(versionDeleteParams: VersionDeleteParams) = apply { + fileId = versionDeleteParams.fileId + versionId = versionDeleteParams.versionId + additionalHeaders = versionDeleteParams.additionalHeaders.toBuilder() + additionalQueryParams = versionDeleteParams.additionalQueryParams.toBuilder() + additionalBodyProperties = versionDeleteParams.additionalBodyProperties.toMutableMap() + } + + fun fileId(fileId: String) = apply { this.fileId = fileId } + + fun versionId(versionId: String?) = apply { this.versionId = versionId } + + /** Alias for calling [Builder.versionId] with `versionId.orElse(null)`. */ + fun versionId(versionId: Optional) = versionId(versionId.getOrNull()) + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + this.additionalBodyProperties.clear() + putAllAdditionalBodyProperties(additionalBodyProperties) + } + + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + additionalBodyProperties.put(key, value) + } + + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + this.additionalBodyProperties.putAll(additionalBodyProperties) + } + + fun removeAdditionalBodyProperty(key: String) = apply { + additionalBodyProperties.remove(key) + } + + fun removeAllAdditionalBodyProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalBodyProperty) + } + + /** + * Returns an immutable instance of [VersionDeleteParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .fileId() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): VersionDeleteParams = + VersionDeleteParams( + checkRequired("fileId", fileId), + versionId, + additionalHeaders.build(), + additionalQueryParams.build(), + additionalBodyProperties.toImmutable(), + ) + } + + fun _body(): Optional> = + Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) + + fun _pathParam(index: Int): String = + when (index) { + 0 -> fileId + 1 -> versionId ?: "" + else -> "" + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is VersionDeleteParams && + fileId == other.fileId && + versionId == other.versionId && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams && + additionalBodyProperties == other.additionalBodyProperties + } + + override fun hashCode(): Int = + Objects.hash( + fileId, + versionId, + additionalHeaders, + additionalQueryParams, + additionalBodyProperties, + ) + + override fun toString() = + "VersionDeleteParams{fileId=$fileId, versionId=$versionId, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams, additionalBodyProperties=$additionalBodyProperties}" +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/files/versions/VersionDeleteResponse.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/files/versions/VersionDeleteResponse.kt new file mode 100644 index 0000000..1b41f61 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/files/versions/VersionDeleteResponse.kt @@ -0,0 +1,113 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.files.versions + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.imagekit.api.core.ExcludeMissing +import com.imagekit.api.core.JsonValue +import com.imagekit.api.errors.ImageKitInvalidDataException +import java.util.Collections +import java.util.Objects + +class VersionDeleteResponse +private constructor(private val additionalProperties: MutableMap) { + + @JsonCreator private constructor() : this(mutableMapOf()) + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [VersionDeleteResponse]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [VersionDeleteResponse]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(versionDeleteResponse: VersionDeleteResponse) = apply { + additionalProperties = versionDeleteResponse.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [VersionDeleteResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): VersionDeleteResponse = + VersionDeleteResponse(additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): VersionDeleteResponse = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = 0 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is VersionDeleteResponse && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "VersionDeleteResponse{additionalProperties=$additionalProperties}" +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/files/versions/VersionGetParams.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/files/versions/VersionGetParams.kt new file mode 100644 index 0000000..fd71f44 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/files/versions/VersionGetParams.kt @@ -0,0 +1,217 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.files.versions + +import com.imagekit.api.core.Params +import com.imagekit.api.core.checkRequired +import com.imagekit.api.core.http.Headers +import com.imagekit.api.core.http.QueryParams +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** This API returns an object with details or attributes of a file version. */ +class VersionGetParams +private constructor( + private val fileId: String, + private val versionId: String?, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + fun fileId(): String = fileId + + fun versionId(): Optional = Optional.ofNullable(versionId) + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [VersionGetParams]. + * + * The following fields are required: + * ```java + * .fileId() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [VersionGetParams]. */ + class Builder internal constructor() { + + private var fileId: String? = null + private var versionId: String? = null + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + + @JvmSynthetic + internal fun from(versionGetParams: VersionGetParams) = apply { + fileId = versionGetParams.fileId + versionId = versionGetParams.versionId + additionalHeaders = versionGetParams.additionalHeaders.toBuilder() + additionalQueryParams = versionGetParams.additionalQueryParams.toBuilder() + } + + fun fileId(fileId: String) = apply { this.fileId = fileId } + + fun versionId(versionId: String?) = apply { this.versionId = versionId } + + /** Alias for calling [Builder.versionId] with `versionId.orElse(null)`. */ + fun versionId(versionId: Optional) = versionId(versionId.getOrNull()) + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + /** + * Returns an immutable instance of [VersionGetParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .fileId() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): VersionGetParams = + VersionGetParams( + checkRequired("fileId", fileId), + versionId, + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } + + fun _pathParam(index: Int): String = + when (index) { + 0 -> fileId + 1 -> versionId ?: "" + else -> "" + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is VersionGetParams && + fileId == other.fileId && + versionId == other.versionId && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = + Objects.hash(fileId, versionId, additionalHeaders, additionalQueryParams) + + override fun toString() = + "VersionGetParams{fileId=$fileId, versionId=$versionId, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/files/versions/VersionListParams.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/files/versions/VersionListParams.kt new file mode 100644 index 0000000..92b5d69 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/files/versions/VersionListParams.kt @@ -0,0 +1,189 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.files.versions + +import com.imagekit.api.core.Params +import com.imagekit.api.core.http.Headers +import com.imagekit.api.core.http.QueryParams +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** This API returns details of all versions of a file. */ +class VersionListParams +private constructor( + private val fileId: String?, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + fun fileId(): Optional = Optional.ofNullable(fileId) + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun none(): VersionListParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [VersionListParams]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [VersionListParams]. */ + class Builder internal constructor() { + + private var fileId: String? = null + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + + @JvmSynthetic + internal fun from(versionListParams: VersionListParams) = apply { + fileId = versionListParams.fileId + additionalHeaders = versionListParams.additionalHeaders.toBuilder() + additionalQueryParams = versionListParams.additionalQueryParams.toBuilder() + } + + fun fileId(fileId: String?) = apply { this.fileId = fileId } + + /** Alias for calling [Builder.fileId] with `fileId.orElse(null)`. */ + fun fileId(fileId: Optional) = fileId(fileId.getOrNull()) + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + /** + * Returns an immutable instance of [VersionListParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): VersionListParams = + VersionListParams(fileId, additionalHeaders.build(), additionalQueryParams.build()) + } + + fun _pathParam(index: Int): String = + when (index) { + 0 -> fileId ?: "" + else -> "" + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is VersionListParams && + fileId == other.fileId && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = Objects.hash(fileId, additionalHeaders, additionalQueryParams) + + override fun toString() = + "VersionListParams{fileId=$fileId, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/files/versions/VersionRestoreParams.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/files/versions/VersionRestoreParams.kt new file mode 100644 index 0000000..6edc115 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/files/versions/VersionRestoreParams.kt @@ -0,0 +1,258 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.files.versions + +import com.imagekit.api.core.JsonValue +import com.imagekit.api.core.Params +import com.imagekit.api.core.checkRequired +import com.imagekit.api.core.http.Headers +import com.imagekit.api.core.http.QueryParams +import com.imagekit.api.core.toImmutable +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** This API restores a file version as the current file version. */ +class VersionRestoreParams +private constructor( + private val fileId: String, + private val versionId: String?, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, + private val additionalBodyProperties: Map, +) : Params { + + fun fileId(): String = fileId + + fun versionId(): Optional = Optional.ofNullable(versionId) + + /** Additional body properties to send with the request. */ + fun _additionalBodyProperties(): Map = additionalBodyProperties + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [VersionRestoreParams]. + * + * The following fields are required: + * ```java + * .fileId() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [VersionRestoreParams]. */ + class Builder internal constructor() { + + private var fileId: String? = null + private var versionId: String? = null + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + private var additionalBodyProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(versionRestoreParams: VersionRestoreParams) = apply { + fileId = versionRestoreParams.fileId + versionId = versionRestoreParams.versionId + additionalHeaders = versionRestoreParams.additionalHeaders.toBuilder() + additionalQueryParams = versionRestoreParams.additionalQueryParams.toBuilder() + additionalBodyProperties = versionRestoreParams.additionalBodyProperties.toMutableMap() + } + + fun fileId(fileId: String) = apply { this.fileId = fileId } + + fun versionId(versionId: String?) = apply { this.versionId = versionId } + + /** Alias for calling [Builder.versionId] with `versionId.orElse(null)`. */ + fun versionId(versionId: Optional) = versionId(versionId.getOrNull()) + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + this.additionalBodyProperties.clear() + putAllAdditionalBodyProperties(additionalBodyProperties) + } + + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + additionalBodyProperties.put(key, value) + } + + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + this.additionalBodyProperties.putAll(additionalBodyProperties) + } + + fun removeAdditionalBodyProperty(key: String) = apply { + additionalBodyProperties.remove(key) + } + + fun removeAllAdditionalBodyProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalBodyProperty) + } + + /** + * Returns an immutable instance of [VersionRestoreParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .fileId() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): VersionRestoreParams = + VersionRestoreParams( + checkRequired("fileId", fileId), + versionId, + additionalHeaders.build(), + additionalQueryParams.build(), + additionalBodyProperties.toImmutable(), + ) + } + + fun _body(): Optional> = + Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) + + fun _pathParam(index: Int): String = + when (index) { + 0 -> fileId + 1 -> versionId ?: "" + else -> "" + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is VersionRestoreParams && + fileId == other.fileId && + versionId == other.versionId && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams && + additionalBodyProperties == other.additionalBodyProperties + } + + override fun hashCode(): Int = + Objects.hash( + fileId, + versionId, + additionalHeaders, + additionalQueryParams, + additionalBodyProperties, + ) + + override fun toString() = + "VersionRestoreParams{fileId=$fileId, versionId=$versionId, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams, additionalBodyProperties=$additionalBodyProperties}" +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/folders/FolderCopyParams.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/folders/FolderCopyParams.kt new file mode 100644 index 0000000..92cb793 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/folders/FolderCopyParams.kt @@ -0,0 +1,605 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.folders + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.imagekit.api.core.ExcludeMissing +import com.imagekit.api.core.JsonField +import com.imagekit.api.core.JsonMissing +import com.imagekit.api.core.JsonValue +import com.imagekit.api.core.Params +import com.imagekit.api.core.checkRequired +import com.imagekit.api.core.http.Headers +import com.imagekit.api.core.http.QueryParams +import com.imagekit.api.errors.ImageKitInvalidDataException +import java.util.Collections +import java.util.Objects +import java.util.Optional + +/** + * This will copy one folder into another. The selected folder, its nested folders, files, and their + * versions (in `includeVersions` is set to true) are copied in this operation. Note: If any file at + * the destination has the same name as the source file, then the source file and its versions will + * be appended to the destination file version history. + */ +class FolderCopyParams +private constructor( + private val body: Body, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** + * Full path to the destination folder where you want to copy the source folder into. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun destinationPath(): String = body.destinationPath() + + /** + * The full path to the source folder you want to copy. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun sourceFolderPath(): String = body.sourceFolderPath() + + /** + * Option to copy all versions of files that are nested inside the selected folder. By default, + * only the current version of each file will be copied. When set to true, all versions of each + * file will be copied. Default value - `false`. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun includeVersions(): Optional = body.includeVersions() + + /** + * Returns the raw JSON value of [destinationPath]. + * + * Unlike [destinationPath], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _destinationPath(): JsonField = body._destinationPath() + + /** + * Returns the raw JSON value of [sourceFolderPath]. + * + * Unlike [sourceFolderPath], this method doesn't throw if the JSON field has an unexpected + * type. + */ + fun _sourceFolderPath(): JsonField = body._sourceFolderPath() + + /** + * Returns the raw JSON value of [includeVersions]. + * + * Unlike [includeVersions], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _includeVersions(): JsonField = body._includeVersions() + + fun _additionalBodyProperties(): Map = body._additionalProperties() + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [FolderCopyParams]. + * + * The following fields are required: + * ```java + * .destinationPath() + * .sourceFolderPath() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [FolderCopyParams]. */ + class Builder internal constructor() { + + private var body: Body.Builder = Body.builder() + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + + @JvmSynthetic + internal fun from(folderCopyParams: FolderCopyParams) = apply { + body = folderCopyParams.body.toBuilder() + additionalHeaders = folderCopyParams.additionalHeaders.toBuilder() + additionalQueryParams = folderCopyParams.additionalQueryParams.toBuilder() + } + + /** + * Sets the entire request body. + * + * This is generally only useful if you are already constructing the body separately. + * Otherwise, it's more convenient to use the top-level setters instead: + * - [destinationPath] + * - [sourceFolderPath] + * - [includeVersions] + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } + + /** Full path to the destination folder where you want to copy the source folder into. */ + fun destinationPath(destinationPath: String) = apply { + body.destinationPath(destinationPath) + } + + /** + * Sets [Builder.destinationPath] to an arbitrary JSON value. + * + * You should usually call [Builder.destinationPath] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun destinationPath(destinationPath: JsonField) = apply { + body.destinationPath(destinationPath) + } + + /** The full path to the source folder you want to copy. */ + fun sourceFolderPath(sourceFolderPath: String) = apply { + body.sourceFolderPath(sourceFolderPath) + } + + /** + * Sets [Builder.sourceFolderPath] to an arbitrary JSON value. + * + * You should usually call [Builder.sourceFolderPath] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun sourceFolderPath(sourceFolderPath: JsonField) = apply { + body.sourceFolderPath(sourceFolderPath) + } + + /** + * Option to copy all versions of files that are nested inside the selected folder. By + * default, only the current version of each file will be copied. When set to true, all + * versions of each file will be copied. Default value - `false`. + */ + fun includeVersions(includeVersions: Boolean) = apply { + body.includeVersions(includeVersions) + } + + /** + * Sets [Builder.includeVersions] to an arbitrary JSON value. + * + * You should usually call [Builder.includeVersions] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun includeVersions(includeVersions: JsonField) = apply { + body.includeVersions(includeVersions) + } + + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + body.additionalProperties(additionalBodyProperties) + } + + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + body.putAdditionalProperty(key, value) + } + + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + body.putAllAdditionalProperties(additionalBodyProperties) + } + + fun removeAdditionalBodyProperty(key: String) = apply { body.removeAdditionalProperty(key) } + + fun removeAllAdditionalBodyProperties(keys: Set) = apply { + body.removeAllAdditionalProperties(keys) + } + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + /** + * Returns an immutable instance of [FolderCopyParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .destinationPath() + * .sourceFolderPath() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): FolderCopyParams = + FolderCopyParams(body.build(), additionalHeaders.build(), additionalQueryParams.build()) + } + + fun _body(): Body = body + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + class Body + private constructor( + private val destinationPath: JsonField, + private val sourceFolderPath: JsonField, + private val includeVersions: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("destinationPath") + @ExcludeMissing + destinationPath: JsonField = JsonMissing.of(), + @JsonProperty("sourceFolderPath") + @ExcludeMissing + sourceFolderPath: JsonField = JsonMissing.of(), + @JsonProperty("includeVersions") + @ExcludeMissing + includeVersions: JsonField = JsonMissing.of(), + ) : this(destinationPath, sourceFolderPath, includeVersions, mutableMapOf()) + + /** + * Full path to the destination folder where you want to copy the source folder into. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun destinationPath(): String = destinationPath.getRequired("destinationPath") + + /** + * The full path to the source folder you want to copy. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun sourceFolderPath(): String = sourceFolderPath.getRequired("sourceFolderPath") + + /** + * Option to copy all versions of files that are nested inside the selected folder. By + * default, only the current version of each file will be copied. When set to true, all + * versions of each file will be copied. Default value - `false`. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun includeVersions(): Optional = includeVersions.getOptional("includeVersions") + + /** + * Returns the raw JSON value of [destinationPath]. + * + * Unlike [destinationPath], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("destinationPath") + @ExcludeMissing + fun _destinationPath(): JsonField = destinationPath + + /** + * Returns the raw JSON value of [sourceFolderPath]. + * + * Unlike [sourceFolderPath], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("sourceFolderPath") + @ExcludeMissing + fun _sourceFolderPath(): JsonField = sourceFolderPath + + /** + * Returns the raw JSON value of [includeVersions]. + * + * Unlike [includeVersions], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("includeVersions") + @ExcludeMissing + fun _includeVersions(): JsonField = includeVersions + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Body]. + * + * The following fields are required: + * ```java + * .destinationPath() + * .sourceFolderPath() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Body]. */ + class Builder internal constructor() { + + private var destinationPath: JsonField? = null + private var sourceFolderPath: JsonField? = null + private var includeVersions: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(body: Body) = apply { + destinationPath = body.destinationPath + sourceFolderPath = body.sourceFolderPath + includeVersions = body.includeVersions + additionalProperties = body.additionalProperties.toMutableMap() + } + + /** + * Full path to the destination folder where you want to copy the source folder into. + */ + fun destinationPath(destinationPath: String) = + destinationPath(JsonField.of(destinationPath)) + + /** + * Sets [Builder.destinationPath] to an arbitrary JSON value. + * + * You should usually call [Builder.destinationPath] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun destinationPath(destinationPath: JsonField) = apply { + this.destinationPath = destinationPath + } + + /** The full path to the source folder you want to copy. */ + fun sourceFolderPath(sourceFolderPath: String) = + sourceFolderPath(JsonField.of(sourceFolderPath)) + + /** + * Sets [Builder.sourceFolderPath] to an arbitrary JSON value. + * + * You should usually call [Builder.sourceFolderPath] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun sourceFolderPath(sourceFolderPath: JsonField) = apply { + this.sourceFolderPath = sourceFolderPath + } + + /** + * Option to copy all versions of files that are nested inside the selected folder. By + * default, only the current version of each file will be copied. When set to true, all + * versions of each file will be copied. Default value - `false`. + */ + fun includeVersions(includeVersions: Boolean) = + includeVersions(JsonField.of(includeVersions)) + + /** + * Sets [Builder.includeVersions] to an arbitrary JSON value. + * + * You should usually call [Builder.includeVersions] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun includeVersions(includeVersions: JsonField) = apply { + this.includeVersions = includeVersions + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Body]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .destinationPath() + * .sourceFolderPath() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Body = + Body( + checkRequired("destinationPath", destinationPath), + checkRequired("sourceFolderPath", sourceFolderPath), + includeVersions, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Body = apply { + if (validated) { + return@apply + } + + destinationPath() + sourceFolderPath() + includeVersions() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (destinationPath.asKnown().isPresent) 1 else 0) + + (if (sourceFolderPath.asKnown().isPresent) 1 else 0) + + (if (includeVersions.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Body && + destinationPath == other.destinationPath && + sourceFolderPath == other.sourceFolderPath && + includeVersions == other.includeVersions && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(destinationPath, sourceFolderPath, includeVersions, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Body{destinationPath=$destinationPath, sourceFolderPath=$sourceFolderPath, includeVersions=$includeVersions, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is FolderCopyParams && + body == other.body && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = Objects.hash(body, additionalHeaders, additionalQueryParams) + + override fun toString() = + "FolderCopyParams{body=$body, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/folders/FolderCopyResponse.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/folders/FolderCopyResponse.kt new file mode 100644 index 0000000..3373e26 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/folders/FolderCopyResponse.kt @@ -0,0 +1,172 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.folders + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.imagekit.api.core.ExcludeMissing +import com.imagekit.api.core.JsonField +import com.imagekit.api.core.JsonMissing +import com.imagekit.api.core.JsonValue +import com.imagekit.api.core.checkRequired +import com.imagekit.api.errors.ImageKitInvalidDataException +import java.util.Collections +import java.util.Objects + +/** Job submitted successfully. A `jobId` will be returned. */ +class FolderCopyResponse +private constructor( + private val jobId: JsonField, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("jobId") @ExcludeMissing jobId: JsonField = JsonMissing.of() + ) : this(jobId, mutableMapOf()) + + /** + * Unique identifier of the bulk job. This can be used to check the status of the bulk job. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun jobId(): String = jobId.getRequired("jobId") + + /** + * Returns the raw JSON value of [jobId]. + * + * Unlike [jobId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("jobId") @ExcludeMissing fun _jobId(): JsonField = jobId + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [FolderCopyResponse]. + * + * The following fields are required: + * ```java + * .jobId() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [FolderCopyResponse]. */ + class Builder internal constructor() { + + private var jobId: JsonField? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(folderCopyResponse: FolderCopyResponse) = apply { + jobId = folderCopyResponse.jobId + additionalProperties = folderCopyResponse.additionalProperties.toMutableMap() + } + + /** + * Unique identifier of the bulk job. This can be used to check the status of the bulk job. + */ + fun jobId(jobId: String) = jobId(JsonField.of(jobId)) + + /** + * Sets [Builder.jobId] to an arbitrary JSON value. + * + * You should usually call [Builder.jobId] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun jobId(jobId: JsonField) = apply { this.jobId = jobId } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [FolderCopyResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .jobId() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): FolderCopyResponse = + FolderCopyResponse(checkRequired("jobId", jobId), additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): FolderCopyResponse = apply { + if (validated) { + return@apply + } + + jobId() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = (if (jobId.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is FolderCopyResponse && + jobId == other.jobId && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(jobId, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "FolderCopyResponse{jobId=$jobId, additionalProperties=$additionalProperties}" +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/folders/FolderCreateParams.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/folders/FolderCreateParams.kt new file mode 100644 index 0000000..3976d1e --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/folders/FolderCreateParams.kt @@ -0,0 +1,550 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.folders + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.imagekit.api.core.ExcludeMissing +import com.imagekit.api.core.JsonField +import com.imagekit.api.core.JsonMissing +import com.imagekit.api.core.JsonValue +import com.imagekit.api.core.Params +import com.imagekit.api.core.checkRequired +import com.imagekit.api.core.http.Headers +import com.imagekit.api.core.http.QueryParams +import com.imagekit.api.errors.ImageKitInvalidDataException +import java.util.Collections +import java.util.Objects + +/** + * This will create a new folder. You can specify the folder name and location of the parent folder + * where this new folder should be created. + */ +class FolderCreateParams +private constructor( + private val body: Body, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** + * The folder will be created with this name. + * + * All characters except alphabets and numbers (inclusive of unicode letters, marks, and + * numerals in other languages) will be replaced by an underscore i.e. `_`. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun folderName(): String = body.folderName() + + /** + * The folder where the new folder should be created, for root use `/` else the path e.g. + * `containing/folder/`. + * + * Note: If any folder(s) is not present in the parentFolderPath parameter, it will be + * automatically created. For example, if you pass `/product/images/summer`, then `product`, + * `images`, and `summer` folders will be created if they don't already exist. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun parentFolderPath(): String = body.parentFolderPath() + + /** + * Returns the raw JSON value of [folderName]. + * + * Unlike [folderName], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _folderName(): JsonField = body._folderName() + + /** + * Returns the raw JSON value of [parentFolderPath]. + * + * Unlike [parentFolderPath], this method doesn't throw if the JSON field has an unexpected + * type. + */ + fun _parentFolderPath(): JsonField = body._parentFolderPath() + + fun _additionalBodyProperties(): Map = body._additionalProperties() + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [FolderCreateParams]. + * + * The following fields are required: + * ```java + * .folderName() + * .parentFolderPath() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [FolderCreateParams]. */ + class Builder internal constructor() { + + private var body: Body.Builder = Body.builder() + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + + @JvmSynthetic + internal fun from(folderCreateParams: FolderCreateParams) = apply { + body = folderCreateParams.body.toBuilder() + additionalHeaders = folderCreateParams.additionalHeaders.toBuilder() + additionalQueryParams = folderCreateParams.additionalQueryParams.toBuilder() + } + + /** + * Sets the entire request body. + * + * This is generally only useful if you are already constructing the body separately. + * Otherwise, it's more convenient to use the top-level setters instead: + * - [folderName] + * - [parentFolderPath] + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } + + /** + * The folder will be created with this name. + * + * All characters except alphabets and numbers (inclusive of unicode letters, marks, and + * numerals in other languages) will be replaced by an underscore i.e. `_`. + */ + fun folderName(folderName: String) = apply { body.folderName(folderName) } + + /** + * Sets [Builder.folderName] to an arbitrary JSON value. + * + * You should usually call [Builder.folderName] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun folderName(folderName: JsonField) = apply { body.folderName(folderName) } + + /** + * The folder where the new folder should be created, for root use `/` else the path e.g. + * `containing/folder/`. + * + * Note: If any folder(s) is not present in the parentFolderPath parameter, it will be + * automatically created. For example, if you pass `/product/images/summer`, then `product`, + * `images`, and `summer` folders will be created if they don't already exist. + */ + fun parentFolderPath(parentFolderPath: String) = apply { + body.parentFolderPath(parentFolderPath) + } + + /** + * Sets [Builder.parentFolderPath] to an arbitrary JSON value. + * + * You should usually call [Builder.parentFolderPath] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun parentFolderPath(parentFolderPath: JsonField) = apply { + body.parentFolderPath(parentFolderPath) + } + + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + body.additionalProperties(additionalBodyProperties) + } + + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + body.putAdditionalProperty(key, value) + } + + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + body.putAllAdditionalProperties(additionalBodyProperties) + } + + fun removeAdditionalBodyProperty(key: String) = apply { body.removeAdditionalProperty(key) } + + fun removeAllAdditionalBodyProperties(keys: Set) = apply { + body.removeAllAdditionalProperties(keys) + } + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + /** + * Returns an immutable instance of [FolderCreateParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .folderName() + * .parentFolderPath() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): FolderCreateParams = + FolderCreateParams( + body.build(), + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } + + fun _body(): Body = body + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + class Body + private constructor( + private val folderName: JsonField, + private val parentFolderPath: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("folderName") + @ExcludeMissing + folderName: JsonField = JsonMissing.of(), + @JsonProperty("parentFolderPath") + @ExcludeMissing + parentFolderPath: JsonField = JsonMissing.of(), + ) : this(folderName, parentFolderPath, mutableMapOf()) + + /** + * The folder will be created with this name. + * + * All characters except alphabets and numbers (inclusive of unicode letters, marks, and + * numerals in other languages) will be replaced by an underscore i.e. `_`. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun folderName(): String = folderName.getRequired("folderName") + + /** + * The folder where the new folder should be created, for root use `/` else the path e.g. + * `containing/folder/`. + * + * Note: If any folder(s) is not present in the parentFolderPath parameter, it will be + * automatically created. For example, if you pass `/product/images/summer`, then `product`, + * `images`, and `summer` folders will be created if they don't already exist. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun parentFolderPath(): String = parentFolderPath.getRequired("parentFolderPath") + + /** + * Returns the raw JSON value of [folderName]. + * + * Unlike [folderName], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("folderName") + @ExcludeMissing + fun _folderName(): JsonField = folderName + + /** + * Returns the raw JSON value of [parentFolderPath]. + * + * Unlike [parentFolderPath], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("parentFolderPath") + @ExcludeMissing + fun _parentFolderPath(): JsonField = parentFolderPath + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Body]. + * + * The following fields are required: + * ```java + * .folderName() + * .parentFolderPath() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Body]. */ + class Builder internal constructor() { + + private var folderName: JsonField? = null + private var parentFolderPath: JsonField? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(body: Body) = apply { + folderName = body.folderName + parentFolderPath = body.parentFolderPath + additionalProperties = body.additionalProperties.toMutableMap() + } + + /** + * The folder will be created with this name. + * + * All characters except alphabets and numbers (inclusive of unicode letters, marks, and + * numerals in other languages) will be replaced by an underscore i.e. `_`. + */ + fun folderName(folderName: String) = folderName(JsonField.of(folderName)) + + /** + * Sets [Builder.folderName] to an arbitrary JSON value. + * + * You should usually call [Builder.folderName] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun folderName(folderName: JsonField) = apply { this.folderName = folderName } + + /** + * The folder where the new folder should be created, for root use `/` else the path + * e.g. `containing/folder/`. + * + * Note: If any folder(s) is not present in the parentFolderPath parameter, it will be + * automatically created. For example, if you pass `/product/images/summer`, then + * `product`, `images`, and `summer` folders will be created if they don't already + * exist. + */ + fun parentFolderPath(parentFolderPath: String) = + parentFolderPath(JsonField.of(parentFolderPath)) + + /** + * Sets [Builder.parentFolderPath] to an arbitrary JSON value. + * + * You should usually call [Builder.parentFolderPath] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun parentFolderPath(parentFolderPath: JsonField) = apply { + this.parentFolderPath = parentFolderPath + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Body]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .folderName() + * .parentFolderPath() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Body = + Body( + checkRequired("folderName", folderName), + checkRequired("parentFolderPath", parentFolderPath), + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Body = apply { + if (validated) { + return@apply + } + + folderName() + parentFolderPath() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (folderName.asKnown().isPresent) 1 else 0) + + (if (parentFolderPath.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Body && + folderName == other.folderName && + parentFolderPath == other.parentFolderPath && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(folderName, parentFolderPath, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Body{folderName=$folderName, parentFolderPath=$parentFolderPath, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is FolderCreateParams && + body == other.body && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = Objects.hash(body, additionalHeaders, additionalQueryParams) + + override fun toString() = + "FolderCreateParams{body=$body, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/folders/FolderCreateResponse.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/folders/FolderCreateResponse.kt new file mode 100644 index 0000000..ca1aebd --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/folders/FolderCreateResponse.kt @@ -0,0 +1,113 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.folders + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.imagekit.api.core.ExcludeMissing +import com.imagekit.api.core.JsonValue +import com.imagekit.api.errors.ImageKitInvalidDataException +import java.util.Collections +import java.util.Objects + +class FolderCreateResponse +private constructor(private val additionalProperties: MutableMap) { + + @JsonCreator private constructor() : this(mutableMapOf()) + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [FolderCreateResponse]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [FolderCreateResponse]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(folderCreateResponse: FolderCreateResponse) = apply { + additionalProperties = folderCreateResponse.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [FolderCreateResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): FolderCreateResponse = + FolderCreateResponse(additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): FolderCreateResponse = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = 0 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is FolderCreateResponse && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "FolderCreateResponse{additionalProperties=$additionalProperties}" +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/folders/FolderDeleteParams.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/folders/FolderDeleteParams.kt new file mode 100644 index 0000000..0cdc851 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/folders/FolderDeleteParams.kt @@ -0,0 +1,421 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.folders + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.imagekit.api.core.ExcludeMissing +import com.imagekit.api.core.JsonField +import com.imagekit.api.core.JsonMissing +import com.imagekit.api.core.JsonValue +import com.imagekit.api.core.Params +import com.imagekit.api.core.checkRequired +import com.imagekit.api.core.http.Headers +import com.imagekit.api.core.http.QueryParams +import com.imagekit.api.errors.ImageKitInvalidDataException +import java.util.Collections +import java.util.Objects + +/** + * This will delete a folder and all its contents permanently. The API returns an empty response. + */ +class FolderDeleteParams +private constructor( + private val body: Body, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** + * Full path to the folder you want to delete. For example `/folder/to/delete/`. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun folderPath(): String = body.folderPath() + + /** + * Returns the raw JSON value of [folderPath]. + * + * Unlike [folderPath], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _folderPath(): JsonField = body._folderPath() + + fun _additionalBodyProperties(): Map = body._additionalProperties() + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [FolderDeleteParams]. + * + * The following fields are required: + * ```java + * .folderPath() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [FolderDeleteParams]. */ + class Builder internal constructor() { + + private var body: Body.Builder = Body.builder() + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + + @JvmSynthetic + internal fun from(folderDeleteParams: FolderDeleteParams) = apply { + body = folderDeleteParams.body.toBuilder() + additionalHeaders = folderDeleteParams.additionalHeaders.toBuilder() + additionalQueryParams = folderDeleteParams.additionalQueryParams.toBuilder() + } + + /** + * Sets the entire request body. + * + * This is generally only useful if you are already constructing the body separately. + * Otherwise, it's more convenient to use the top-level setters instead: + * - [folderPath] + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } + + /** Full path to the folder you want to delete. For example `/folder/to/delete/`. */ + fun folderPath(folderPath: String) = apply { body.folderPath(folderPath) } + + /** + * Sets [Builder.folderPath] to an arbitrary JSON value. + * + * You should usually call [Builder.folderPath] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun folderPath(folderPath: JsonField) = apply { body.folderPath(folderPath) } + + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + body.additionalProperties(additionalBodyProperties) + } + + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + body.putAdditionalProperty(key, value) + } + + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + body.putAllAdditionalProperties(additionalBodyProperties) + } + + fun removeAdditionalBodyProperty(key: String) = apply { body.removeAdditionalProperty(key) } + + fun removeAllAdditionalBodyProperties(keys: Set) = apply { + body.removeAllAdditionalProperties(keys) + } + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + /** + * Returns an immutable instance of [FolderDeleteParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .folderPath() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): FolderDeleteParams = + FolderDeleteParams( + body.build(), + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } + + fun _body(): Body = body + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + class Body + private constructor( + private val folderPath: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("folderPath") + @ExcludeMissing + folderPath: JsonField = JsonMissing.of() + ) : this(folderPath, mutableMapOf()) + + /** + * Full path to the folder you want to delete. For example `/folder/to/delete/`. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun folderPath(): String = folderPath.getRequired("folderPath") + + /** + * Returns the raw JSON value of [folderPath]. + * + * Unlike [folderPath], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("folderPath") + @ExcludeMissing + fun _folderPath(): JsonField = folderPath + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Body]. + * + * The following fields are required: + * ```java + * .folderPath() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Body]. */ + class Builder internal constructor() { + + private var folderPath: JsonField? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(body: Body) = apply { + folderPath = body.folderPath + additionalProperties = body.additionalProperties.toMutableMap() + } + + /** Full path to the folder you want to delete. For example `/folder/to/delete/`. */ + fun folderPath(folderPath: String) = folderPath(JsonField.of(folderPath)) + + /** + * Sets [Builder.folderPath] to an arbitrary JSON value. + * + * You should usually call [Builder.folderPath] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun folderPath(folderPath: JsonField) = apply { this.folderPath = folderPath } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Body]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .folderPath() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Body = + Body(checkRequired("folderPath", folderPath), additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Body = apply { + if (validated) { + return@apply + } + + folderPath() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = (if (folderPath.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Body && + folderPath == other.folderPath && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(folderPath, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Body{folderPath=$folderPath, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is FolderDeleteParams && + body == other.body && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = Objects.hash(body, additionalHeaders, additionalQueryParams) + + override fun toString() = + "FolderDeleteParams{body=$body, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/folders/FolderDeleteResponse.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/folders/FolderDeleteResponse.kt new file mode 100644 index 0000000..b9d17cd --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/folders/FolderDeleteResponse.kt @@ -0,0 +1,113 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.folders + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.imagekit.api.core.ExcludeMissing +import com.imagekit.api.core.JsonValue +import com.imagekit.api.errors.ImageKitInvalidDataException +import java.util.Collections +import java.util.Objects + +class FolderDeleteResponse +private constructor(private val additionalProperties: MutableMap) { + + @JsonCreator private constructor() : this(mutableMapOf()) + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [FolderDeleteResponse]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [FolderDeleteResponse]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(folderDeleteResponse: FolderDeleteResponse) = apply { + additionalProperties = folderDeleteResponse.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [FolderDeleteResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): FolderDeleteResponse = + FolderDeleteResponse(additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): FolderDeleteResponse = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = 0 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is FolderDeleteResponse && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "FolderDeleteResponse{additionalProperties=$additionalProperties}" +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/folders/FolderMoveParams.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/folders/FolderMoveParams.kt new file mode 100644 index 0000000..2653973 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/folders/FolderMoveParams.kt @@ -0,0 +1,517 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.folders + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.imagekit.api.core.ExcludeMissing +import com.imagekit.api.core.JsonField +import com.imagekit.api.core.JsonMissing +import com.imagekit.api.core.JsonValue +import com.imagekit.api.core.Params +import com.imagekit.api.core.checkRequired +import com.imagekit.api.core.http.Headers +import com.imagekit.api.core.http.QueryParams +import com.imagekit.api.errors.ImageKitInvalidDataException +import java.util.Collections +import java.util.Objects + +/** + * This will move one folder into another. The selected folder, its nested folders, files, and their + * versions are moved in this operation. Note: If any file at the destination has the same name as + * the source file, then the source file and its versions will be appended to the destination file + * version history. + */ +class FolderMoveParams +private constructor( + private val body: Body, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** + * Full path to the destination folder where you want to move the source folder into. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun destinationPath(): String = body.destinationPath() + + /** + * The full path to the source folder you want to move. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun sourceFolderPath(): String = body.sourceFolderPath() + + /** + * Returns the raw JSON value of [destinationPath]. + * + * Unlike [destinationPath], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _destinationPath(): JsonField = body._destinationPath() + + /** + * Returns the raw JSON value of [sourceFolderPath]. + * + * Unlike [sourceFolderPath], this method doesn't throw if the JSON field has an unexpected + * type. + */ + fun _sourceFolderPath(): JsonField = body._sourceFolderPath() + + fun _additionalBodyProperties(): Map = body._additionalProperties() + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [FolderMoveParams]. + * + * The following fields are required: + * ```java + * .destinationPath() + * .sourceFolderPath() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [FolderMoveParams]. */ + class Builder internal constructor() { + + private var body: Body.Builder = Body.builder() + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + + @JvmSynthetic + internal fun from(folderMoveParams: FolderMoveParams) = apply { + body = folderMoveParams.body.toBuilder() + additionalHeaders = folderMoveParams.additionalHeaders.toBuilder() + additionalQueryParams = folderMoveParams.additionalQueryParams.toBuilder() + } + + /** + * Sets the entire request body. + * + * This is generally only useful if you are already constructing the body separately. + * Otherwise, it's more convenient to use the top-level setters instead: + * - [destinationPath] + * - [sourceFolderPath] + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } + + /** Full path to the destination folder where you want to move the source folder into. */ + fun destinationPath(destinationPath: String) = apply { + body.destinationPath(destinationPath) + } + + /** + * Sets [Builder.destinationPath] to an arbitrary JSON value. + * + * You should usually call [Builder.destinationPath] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun destinationPath(destinationPath: JsonField) = apply { + body.destinationPath(destinationPath) + } + + /** The full path to the source folder you want to move. */ + fun sourceFolderPath(sourceFolderPath: String) = apply { + body.sourceFolderPath(sourceFolderPath) + } + + /** + * Sets [Builder.sourceFolderPath] to an arbitrary JSON value. + * + * You should usually call [Builder.sourceFolderPath] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun sourceFolderPath(sourceFolderPath: JsonField) = apply { + body.sourceFolderPath(sourceFolderPath) + } + + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + body.additionalProperties(additionalBodyProperties) + } + + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + body.putAdditionalProperty(key, value) + } + + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + body.putAllAdditionalProperties(additionalBodyProperties) + } + + fun removeAdditionalBodyProperty(key: String) = apply { body.removeAdditionalProperty(key) } + + fun removeAllAdditionalBodyProperties(keys: Set) = apply { + body.removeAllAdditionalProperties(keys) + } + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + /** + * Returns an immutable instance of [FolderMoveParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .destinationPath() + * .sourceFolderPath() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): FolderMoveParams = + FolderMoveParams(body.build(), additionalHeaders.build(), additionalQueryParams.build()) + } + + fun _body(): Body = body + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + class Body + private constructor( + private val destinationPath: JsonField, + private val sourceFolderPath: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("destinationPath") + @ExcludeMissing + destinationPath: JsonField = JsonMissing.of(), + @JsonProperty("sourceFolderPath") + @ExcludeMissing + sourceFolderPath: JsonField = JsonMissing.of(), + ) : this(destinationPath, sourceFolderPath, mutableMapOf()) + + /** + * Full path to the destination folder where you want to move the source folder into. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun destinationPath(): String = destinationPath.getRequired("destinationPath") + + /** + * The full path to the source folder you want to move. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun sourceFolderPath(): String = sourceFolderPath.getRequired("sourceFolderPath") + + /** + * Returns the raw JSON value of [destinationPath]. + * + * Unlike [destinationPath], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("destinationPath") + @ExcludeMissing + fun _destinationPath(): JsonField = destinationPath + + /** + * Returns the raw JSON value of [sourceFolderPath]. + * + * Unlike [sourceFolderPath], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("sourceFolderPath") + @ExcludeMissing + fun _sourceFolderPath(): JsonField = sourceFolderPath + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Body]. + * + * The following fields are required: + * ```java + * .destinationPath() + * .sourceFolderPath() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Body]. */ + class Builder internal constructor() { + + private var destinationPath: JsonField? = null + private var sourceFolderPath: JsonField? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(body: Body) = apply { + destinationPath = body.destinationPath + sourceFolderPath = body.sourceFolderPath + additionalProperties = body.additionalProperties.toMutableMap() + } + + /** + * Full path to the destination folder where you want to move the source folder into. + */ + fun destinationPath(destinationPath: String) = + destinationPath(JsonField.of(destinationPath)) + + /** + * Sets [Builder.destinationPath] to an arbitrary JSON value. + * + * You should usually call [Builder.destinationPath] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun destinationPath(destinationPath: JsonField) = apply { + this.destinationPath = destinationPath + } + + /** The full path to the source folder you want to move. */ + fun sourceFolderPath(sourceFolderPath: String) = + sourceFolderPath(JsonField.of(sourceFolderPath)) + + /** + * Sets [Builder.sourceFolderPath] to an arbitrary JSON value. + * + * You should usually call [Builder.sourceFolderPath] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun sourceFolderPath(sourceFolderPath: JsonField) = apply { + this.sourceFolderPath = sourceFolderPath + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Body]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .destinationPath() + * .sourceFolderPath() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Body = + Body( + checkRequired("destinationPath", destinationPath), + checkRequired("sourceFolderPath", sourceFolderPath), + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Body = apply { + if (validated) { + return@apply + } + + destinationPath() + sourceFolderPath() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (destinationPath.asKnown().isPresent) 1 else 0) + + (if (sourceFolderPath.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Body && + destinationPath == other.destinationPath && + sourceFolderPath == other.sourceFolderPath && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(destinationPath, sourceFolderPath, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Body{destinationPath=$destinationPath, sourceFolderPath=$sourceFolderPath, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is FolderMoveParams && + body == other.body && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = Objects.hash(body, additionalHeaders, additionalQueryParams) + + override fun toString() = + "FolderMoveParams{body=$body, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/folders/FolderMoveResponse.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/folders/FolderMoveResponse.kt new file mode 100644 index 0000000..7df902c --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/folders/FolderMoveResponse.kt @@ -0,0 +1,172 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.folders + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.imagekit.api.core.ExcludeMissing +import com.imagekit.api.core.JsonField +import com.imagekit.api.core.JsonMissing +import com.imagekit.api.core.JsonValue +import com.imagekit.api.core.checkRequired +import com.imagekit.api.errors.ImageKitInvalidDataException +import java.util.Collections +import java.util.Objects + +/** Job submitted successfully. A `jobId` will be returned. */ +class FolderMoveResponse +private constructor( + private val jobId: JsonField, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("jobId") @ExcludeMissing jobId: JsonField = JsonMissing.of() + ) : this(jobId, mutableMapOf()) + + /** + * Unique identifier of the bulk job. This can be used to check the status of the bulk job. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun jobId(): String = jobId.getRequired("jobId") + + /** + * Returns the raw JSON value of [jobId]. + * + * Unlike [jobId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("jobId") @ExcludeMissing fun _jobId(): JsonField = jobId + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [FolderMoveResponse]. + * + * The following fields are required: + * ```java + * .jobId() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [FolderMoveResponse]. */ + class Builder internal constructor() { + + private var jobId: JsonField? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(folderMoveResponse: FolderMoveResponse) = apply { + jobId = folderMoveResponse.jobId + additionalProperties = folderMoveResponse.additionalProperties.toMutableMap() + } + + /** + * Unique identifier of the bulk job. This can be used to check the status of the bulk job. + */ + fun jobId(jobId: String) = jobId(JsonField.of(jobId)) + + /** + * Sets [Builder.jobId] to an arbitrary JSON value. + * + * You should usually call [Builder.jobId] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun jobId(jobId: JsonField) = apply { this.jobId = jobId } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [FolderMoveResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .jobId() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): FolderMoveResponse = + FolderMoveResponse(checkRequired("jobId", jobId), additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): FolderMoveResponse = apply { + if (validated) { + return@apply + } + + jobId() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = (if (jobId.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is FolderMoveResponse && + jobId == other.jobId && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(jobId, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "FolderMoveResponse{jobId=$jobId, additionalProperties=$additionalProperties}" +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/folders/FolderRenameParams.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/folders/FolderRenameParams.kt new file mode 100644 index 0000000..c6564c8 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/folders/FolderRenameParams.kt @@ -0,0 +1,646 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.folders + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.imagekit.api.core.ExcludeMissing +import com.imagekit.api.core.JsonField +import com.imagekit.api.core.JsonMissing +import com.imagekit.api.core.JsonValue +import com.imagekit.api.core.Params +import com.imagekit.api.core.checkRequired +import com.imagekit.api.core.http.Headers +import com.imagekit.api.core.http.QueryParams +import com.imagekit.api.errors.ImageKitInvalidDataException +import java.util.Collections +import java.util.Objects +import java.util.Optional + +/** + * This API allows you to rename an existing folder. The folder and all its nested assets and + * sub-folders will remain unchanged, but their paths will be updated to reflect the new folder + * name. + */ +class FolderRenameParams +private constructor( + private val body: Body, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** + * The full path to the folder you want to rename. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun folderPath(): String = body.folderPath() + + /** + * The new name for the folder. + * + * All characters except alphabets and numbers (inclusive of unicode letters, marks, and + * numerals in other languages) and `-` will be replaced by an underscore i.e. `_`. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun newFolderName(): String = body.newFolderName() + + /** + * Option to purge cache for the old nested files and their versions' URLs. + * + * When set to true, it will internally issue a purge cache request on CDN to remove the cached + * content of the old nested files and their versions. There will only be one purge request for + * all the nested files, which will be counted against your monthly purge quota. + * + * Note: A purge cache request will be issued against `https://ik.imagekit.io/old/folder/path*` + * (with a wildcard at the end). This will remove all nested files, their versions' URLs, and + * any transformations made using query parameters on these files or their versions. However, + * the cache for file transformations made using path parameters will persist. You can purge + * them using the purge API. For more details, refer to the purge API documentation. + * + * Default value - `false` + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun purgeCache(): Optional = body.purgeCache() + + /** + * Returns the raw JSON value of [folderPath]. + * + * Unlike [folderPath], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _folderPath(): JsonField = body._folderPath() + + /** + * Returns the raw JSON value of [newFolderName]. + * + * Unlike [newFolderName], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _newFolderName(): JsonField = body._newFolderName() + + /** + * Returns the raw JSON value of [purgeCache]. + * + * Unlike [purgeCache], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _purgeCache(): JsonField = body._purgeCache() + + fun _additionalBodyProperties(): Map = body._additionalProperties() + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [FolderRenameParams]. + * + * The following fields are required: + * ```java + * .folderPath() + * .newFolderName() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [FolderRenameParams]. */ + class Builder internal constructor() { + + private var body: Body.Builder = Body.builder() + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + + @JvmSynthetic + internal fun from(folderRenameParams: FolderRenameParams) = apply { + body = folderRenameParams.body.toBuilder() + additionalHeaders = folderRenameParams.additionalHeaders.toBuilder() + additionalQueryParams = folderRenameParams.additionalQueryParams.toBuilder() + } + + /** + * Sets the entire request body. + * + * This is generally only useful if you are already constructing the body separately. + * Otherwise, it's more convenient to use the top-level setters instead: + * - [folderPath] + * - [newFolderName] + * - [purgeCache] + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } + + /** The full path to the folder you want to rename. */ + fun folderPath(folderPath: String) = apply { body.folderPath(folderPath) } + + /** + * Sets [Builder.folderPath] to an arbitrary JSON value. + * + * You should usually call [Builder.folderPath] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun folderPath(folderPath: JsonField) = apply { body.folderPath(folderPath) } + + /** + * The new name for the folder. + * + * All characters except alphabets and numbers (inclusive of unicode letters, marks, and + * numerals in other languages) and `-` will be replaced by an underscore i.e. `_`. + */ + fun newFolderName(newFolderName: String) = apply { body.newFolderName(newFolderName) } + + /** + * Sets [Builder.newFolderName] to an arbitrary JSON value. + * + * You should usually call [Builder.newFolderName] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun newFolderName(newFolderName: JsonField) = apply { + body.newFolderName(newFolderName) + } + + /** + * Option to purge cache for the old nested files and their versions' URLs. + * + * When set to true, it will internally issue a purge cache request on CDN to remove the + * cached content of the old nested files and their versions. There will only be one purge + * request for all the nested files, which will be counted against your monthly purge quota. + * + * Note: A purge cache request will be issued against + * `https://ik.imagekit.io/old/folder/path*` (with a wildcard at the end). This will remove + * all nested files, their versions' URLs, and any transformations made using query + * parameters on these files or their versions. However, the cache for file transformations + * made using path parameters will persist. You can purge them using the purge API. For more + * details, refer to the purge API documentation. + * + * Default value - `false` + */ + fun purgeCache(purgeCache: Boolean) = apply { body.purgeCache(purgeCache) } + + /** + * Sets [Builder.purgeCache] to an arbitrary JSON value. + * + * You should usually call [Builder.purgeCache] with a well-typed [Boolean] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun purgeCache(purgeCache: JsonField) = apply { body.purgeCache(purgeCache) } + + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + body.additionalProperties(additionalBodyProperties) + } + + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + body.putAdditionalProperty(key, value) + } + + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + body.putAllAdditionalProperties(additionalBodyProperties) + } + + fun removeAdditionalBodyProperty(key: String) = apply { body.removeAdditionalProperty(key) } + + fun removeAllAdditionalBodyProperties(keys: Set) = apply { + body.removeAllAdditionalProperties(keys) + } + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + /** + * Returns an immutable instance of [FolderRenameParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .folderPath() + * .newFolderName() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): FolderRenameParams = + FolderRenameParams( + body.build(), + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } + + fun _body(): Body = body + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + class Body + private constructor( + private val folderPath: JsonField, + private val newFolderName: JsonField, + private val purgeCache: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("folderPath") + @ExcludeMissing + folderPath: JsonField = JsonMissing.of(), + @JsonProperty("newFolderName") + @ExcludeMissing + newFolderName: JsonField = JsonMissing.of(), + @JsonProperty("purgeCache") + @ExcludeMissing + purgeCache: JsonField = JsonMissing.of(), + ) : this(folderPath, newFolderName, purgeCache, mutableMapOf()) + + /** + * The full path to the folder you want to rename. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun folderPath(): String = folderPath.getRequired("folderPath") + + /** + * The new name for the folder. + * + * All characters except alphabets and numbers (inclusive of unicode letters, marks, and + * numerals in other languages) and `-` will be replaced by an underscore i.e. `_`. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun newFolderName(): String = newFolderName.getRequired("newFolderName") + + /** + * Option to purge cache for the old nested files and their versions' URLs. + * + * When set to true, it will internally issue a purge cache request on CDN to remove the + * cached content of the old nested files and their versions. There will only be one purge + * request for all the nested files, which will be counted against your monthly purge quota. + * + * Note: A purge cache request will be issued against + * `https://ik.imagekit.io/old/folder/path*` (with a wildcard at the end). This will remove + * all nested files, their versions' URLs, and any transformations made using query + * parameters on these files or their versions. However, the cache for file transformations + * made using path parameters will persist. You can purge them using the purge API. For more + * details, refer to the purge API documentation. + * + * Default value - `false` + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun purgeCache(): Optional = purgeCache.getOptional("purgeCache") + + /** + * Returns the raw JSON value of [folderPath]. + * + * Unlike [folderPath], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("folderPath") + @ExcludeMissing + fun _folderPath(): JsonField = folderPath + + /** + * Returns the raw JSON value of [newFolderName]. + * + * Unlike [newFolderName], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("newFolderName") + @ExcludeMissing + fun _newFolderName(): JsonField = newFolderName + + /** + * Returns the raw JSON value of [purgeCache]. + * + * Unlike [purgeCache], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("purgeCache") + @ExcludeMissing + fun _purgeCache(): JsonField = purgeCache + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Body]. + * + * The following fields are required: + * ```java + * .folderPath() + * .newFolderName() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Body]. */ + class Builder internal constructor() { + + private var folderPath: JsonField? = null + private var newFolderName: JsonField? = null + private var purgeCache: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(body: Body) = apply { + folderPath = body.folderPath + newFolderName = body.newFolderName + purgeCache = body.purgeCache + additionalProperties = body.additionalProperties.toMutableMap() + } + + /** The full path to the folder you want to rename. */ + fun folderPath(folderPath: String) = folderPath(JsonField.of(folderPath)) + + /** + * Sets [Builder.folderPath] to an arbitrary JSON value. + * + * You should usually call [Builder.folderPath] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun folderPath(folderPath: JsonField) = apply { this.folderPath = folderPath } + + /** + * The new name for the folder. + * + * All characters except alphabets and numbers (inclusive of unicode letters, marks, and + * numerals in other languages) and `-` will be replaced by an underscore i.e. `_`. + */ + fun newFolderName(newFolderName: String) = newFolderName(JsonField.of(newFolderName)) + + /** + * Sets [Builder.newFolderName] to an arbitrary JSON value. + * + * You should usually call [Builder.newFolderName] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun newFolderName(newFolderName: JsonField) = apply { + this.newFolderName = newFolderName + } + + /** + * Option to purge cache for the old nested files and their versions' URLs. + * + * When set to true, it will internally issue a purge cache request on CDN to remove the + * cached content of the old nested files and their versions. There will only be one + * purge request for all the nested files, which will be counted against your monthly + * purge quota. + * + * Note: A purge cache request will be issued against + * `https://ik.imagekit.io/old/folder/path*` (with a wildcard at the end). This will + * remove all nested files, their versions' URLs, and any transformations made using + * query parameters on these files or their versions. However, the cache for file + * transformations made using path parameters will persist. You can purge them using the + * purge API. For more details, refer to the purge API documentation. + * + * Default value - `false` + */ + fun purgeCache(purgeCache: Boolean) = purgeCache(JsonField.of(purgeCache)) + + /** + * Sets [Builder.purgeCache] to an arbitrary JSON value. + * + * You should usually call [Builder.purgeCache] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun purgeCache(purgeCache: JsonField) = apply { this.purgeCache = purgeCache } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Body]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .folderPath() + * .newFolderName() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Body = + Body( + checkRequired("folderPath", folderPath), + checkRequired("newFolderName", newFolderName), + purgeCache, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Body = apply { + if (validated) { + return@apply + } + + folderPath() + newFolderName() + purgeCache() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (folderPath.asKnown().isPresent) 1 else 0) + + (if (newFolderName.asKnown().isPresent) 1 else 0) + + (if (purgeCache.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Body && + folderPath == other.folderPath && + newFolderName == other.newFolderName && + purgeCache == other.purgeCache && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(folderPath, newFolderName, purgeCache, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Body{folderPath=$folderPath, newFolderName=$newFolderName, purgeCache=$purgeCache, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is FolderRenameParams && + body == other.body && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = Objects.hash(body, additionalHeaders, additionalQueryParams) + + override fun toString() = + "FolderRenameParams{body=$body, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/folders/FolderRenameResponse.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/folders/FolderRenameResponse.kt new file mode 100644 index 0000000..96bd156 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/folders/FolderRenameResponse.kt @@ -0,0 +1,172 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.folders + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.imagekit.api.core.ExcludeMissing +import com.imagekit.api.core.JsonField +import com.imagekit.api.core.JsonMissing +import com.imagekit.api.core.JsonValue +import com.imagekit.api.core.checkRequired +import com.imagekit.api.errors.ImageKitInvalidDataException +import java.util.Collections +import java.util.Objects + +/** Job submitted successfully. A `jobId` will be returned. */ +class FolderRenameResponse +private constructor( + private val jobId: JsonField, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("jobId") @ExcludeMissing jobId: JsonField = JsonMissing.of() + ) : this(jobId, mutableMapOf()) + + /** + * Unique identifier of the bulk job. This can be used to check the status of the bulk job. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun jobId(): String = jobId.getRequired("jobId") + + /** + * Returns the raw JSON value of [jobId]. + * + * Unlike [jobId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("jobId") @ExcludeMissing fun _jobId(): JsonField = jobId + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [FolderRenameResponse]. + * + * The following fields are required: + * ```java + * .jobId() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [FolderRenameResponse]. */ + class Builder internal constructor() { + + private var jobId: JsonField? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(folderRenameResponse: FolderRenameResponse) = apply { + jobId = folderRenameResponse.jobId + additionalProperties = folderRenameResponse.additionalProperties.toMutableMap() + } + + /** + * Unique identifier of the bulk job. This can be used to check the status of the bulk job. + */ + fun jobId(jobId: String) = jobId(JsonField.of(jobId)) + + /** + * Sets [Builder.jobId] to an arbitrary JSON value. + * + * You should usually call [Builder.jobId] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun jobId(jobId: JsonField) = apply { this.jobId = jobId } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [FolderRenameResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .jobId() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): FolderRenameResponse = + FolderRenameResponse(checkRequired("jobId", jobId), additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): FolderRenameResponse = apply { + if (validated) { + return@apply + } + + jobId() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = (if (jobId.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is FolderRenameResponse && + jobId == other.jobId && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(jobId, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "FolderRenameResponse{jobId=$jobId, additionalProperties=$additionalProperties}" +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/folders/job/JobGetParams.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/folders/job/JobGetParams.kt new file mode 100644 index 0000000..6e87f9b --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/folders/job/JobGetParams.kt @@ -0,0 +1,189 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.folders.job + +import com.imagekit.api.core.Params +import com.imagekit.api.core.http.Headers +import com.imagekit.api.core.http.QueryParams +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** This API returns the status of a bulk job like copy and move folder operations. */ +class JobGetParams +private constructor( + private val jobId: String?, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + fun jobId(): Optional = Optional.ofNullable(jobId) + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun none(): JobGetParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [JobGetParams]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [JobGetParams]. */ + class Builder internal constructor() { + + private var jobId: String? = null + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + + @JvmSynthetic + internal fun from(jobGetParams: JobGetParams) = apply { + jobId = jobGetParams.jobId + additionalHeaders = jobGetParams.additionalHeaders.toBuilder() + additionalQueryParams = jobGetParams.additionalQueryParams.toBuilder() + } + + fun jobId(jobId: String?) = apply { this.jobId = jobId } + + /** Alias for calling [Builder.jobId] with `jobId.orElse(null)`. */ + fun jobId(jobId: Optional) = jobId(jobId.getOrNull()) + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + /** + * Returns an immutable instance of [JobGetParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): JobGetParams = + JobGetParams(jobId, additionalHeaders.build(), additionalQueryParams.build()) + } + + fun _pathParam(index: Int): String = + when (index) { + 0 -> jobId ?: "" + else -> "" + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is JobGetParams && + jobId == other.jobId && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = Objects.hash(jobId, additionalHeaders, additionalQueryParams) + + override fun toString() = + "JobGetParams{jobId=$jobId, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/folders/job/JobGetResponse.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/folders/job/JobGetResponse.kt new file mode 100644 index 0000000..b6ed81c --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/folders/job/JobGetResponse.kt @@ -0,0 +1,533 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.folders.job + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.imagekit.api.core.Enum +import com.imagekit.api.core.ExcludeMissing +import com.imagekit.api.core.JsonField +import com.imagekit.api.core.JsonMissing +import com.imagekit.api.core.JsonValue +import com.imagekit.api.errors.ImageKitInvalidDataException +import java.util.Collections +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +class JobGetResponse +private constructor( + private val jobId: JsonField, + private val purgeRequestId: JsonField, + private val status: JsonField, + private val type: JsonField, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("jobId") @ExcludeMissing jobId: JsonField = JsonMissing.of(), + @JsonProperty("purgeRequestId") + @ExcludeMissing + purgeRequestId: JsonField = JsonMissing.of(), + @JsonProperty("status") @ExcludeMissing status: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonField = JsonMissing.of(), + ) : this(jobId, purgeRequestId, status, type, mutableMapOf()) + + /** + * Unique identifier of the bulk job. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun jobId(): Optional = jobId.getOptional("jobId") + + /** + * Unique identifier of the purge request. This will be present only if `purgeCache` is set to + * `true` in the rename folder API request. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun purgeRequestId(): Optional = purgeRequestId.getOptional("purgeRequestId") + + /** + * Status of the bulk job. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun status(): Optional = status.getOptional("status") + + /** + * Type of the bulk job. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun type(): Optional = type.getOptional("type") + + /** + * Returns the raw JSON value of [jobId]. + * + * Unlike [jobId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("jobId") @ExcludeMissing fun _jobId(): JsonField = jobId + + /** + * Returns the raw JSON value of [purgeRequestId]. + * + * Unlike [purgeRequestId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("purgeRequestId") + @ExcludeMissing + fun _purgeRequestId(): JsonField = purgeRequestId + + /** + * Returns the raw JSON value of [status]. + * + * Unlike [status], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("status") @ExcludeMissing fun _status(): JsonField = status + + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [JobGetResponse]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [JobGetResponse]. */ + class Builder internal constructor() { + + private var jobId: JsonField = JsonMissing.of() + private var purgeRequestId: JsonField = JsonMissing.of() + private var status: JsonField = JsonMissing.of() + private var type: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(jobGetResponse: JobGetResponse) = apply { + jobId = jobGetResponse.jobId + purgeRequestId = jobGetResponse.purgeRequestId + status = jobGetResponse.status + type = jobGetResponse.type + additionalProperties = jobGetResponse.additionalProperties.toMutableMap() + } + + /** Unique identifier of the bulk job. */ + fun jobId(jobId: String) = jobId(JsonField.of(jobId)) + + /** + * Sets [Builder.jobId] to an arbitrary JSON value. + * + * You should usually call [Builder.jobId] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun jobId(jobId: JsonField) = apply { this.jobId = jobId } + + /** + * Unique identifier of the purge request. This will be present only if `purgeCache` is set + * to `true` in the rename folder API request. + */ + fun purgeRequestId(purgeRequestId: String) = purgeRequestId(JsonField.of(purgeRequestId)) + + /** + * Sets [Builder.purgeRequestId] to an arbitrary JSON value. + * + * You should usually call [Builder.purgeRequestId] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun purgeRequestId(purgeRequestId: JsonField) = apply { + this.purgeRequestId = purgeRequestId + } + + /** Status of the bulk job. */ + fun status(status: Status) = status(JsonField.of(status)) + + /** + * Sets [Builder.status] to an arbitrary JSON value. + * + * You should usually call [Builder.status] with a well-typed [Status] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun status(status: JsonField) = apply { this.status = status } + + /** Type of the bulk job. */ + fun type(type: Type) = type(JsonField.of(type)) + + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [Type] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun type(type: JsonField) = apply { this.type = type } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [JobGetResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): JobGetResponse = + JobGetResponse(jobId, purgeRequestId, status, type, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): JobGetResponse = apply { + if (validated) { + return@apply + } + + jobId() + purgeRequestId() + status().ifPresent { it.validate() } + type().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (jobId.asKnown().isPresent) 1 else 0) + + (if (purgeRequestId.asKnown().isPresent) 1 else 0) + + (status.asKnown().getOrNull()?.validity() ?: 0) + + (type.asKnown().getOrNull()?.validity() ?: 0) + + /** Status of the bulk job. */ + class Status @JsonCreator private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is on an + * older version than the API, then the API may respond with new members that the SDK is + * unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val PENDING = of("Pending") + + @JvmField val COMPLETED = of("Completed") + + @JvmStatic fun of(value: String) = Status(JsonField.of(value)) + } + + /** An enum containing [Status]'s known values. */ + enum class Known { + PENDING, + COMPLETED, + } + + /** + * An enum containing [Status]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [Status] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if the + * SDK is on an older version than the API, then the API may respond with new members that + * the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + PENDING, + COMPLETED, + /** An enum member indicating that [Status] was instantiated with an unknown value. */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] + * if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you want + * to throw for the unknown case. + */ + fun value(): Value = + when (this) { + PENDING -> Value.PENDING + COMPLETED -> Value.COMPLETED + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and don't + * want to throw for the unknown case. + * + * @throws ImageKitInvalidDataException if this class instance's value is a not a known + * member. + */ + fun known(): Known = + when (this) { + PENDING -> Known.PENDING + COMPLETED -> Known.COMPLETED + else -> throw ImageKitInvalidDataException("Unknown Status: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for debugging + * and generally doesn't throw. + * + * @throws ImageKitInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + ImageKitInvalidDataException("Value is not a String") + } + + private var validated: Boolean = false + + fun validate(): Status = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Status && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + /** Type of the bulk job. */ + class Type @JsonCreator private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is on an + * older version than the API, then the API may respond with new members that the SDK is + * unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val COPY_FOLDER = of("COPY_FOLDER") + + @JvmField val MOVE_FOLDER = of("MOVE_FOLDER") + + @JvmField val RENAME_FOLDER = of("RENAME_FOLDER") + + @JvmStatic fun of(value: String) = Type(JsonField.of(value)) + } + + /** An enum containing [Type]'s known values. */ + enum class Known { + COPY_FOLDER, + MOVE_FOLDER, + RENAME_FOLDER, + } + + /** + * An enum containing [Type]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [Type] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if the + * SDK is on an older version than the API, then the API may respond with new members that + * the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + COPY_FOLDER, + MOVE_FOLDER, + RENAME_FOLDER, + /** An enum member indicating that [Type] was instantiated with an unknown value. */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] + * if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you want + * to throw for the unknown case. + */ + fun value(): Value = + when (this) { + COPY_FOLDER -> Value.COPY_FOLDER + MOVE_FOLDER -> Value.MOVE_FOLDER + RENAME_FOLDER -> Value.RENAME_FOLDER + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and don't + * want to throw for the unknown case. + * + * @throws ImageKitInvalidDataException if this class instance's value is a not a known + * member. + */ + fun known(): Known = + when (this) { + COPY_FOLDER -> Known.COPY_FOLDER + MOVE_FOLDER -> Known.MOVE_FOLDER + RENAME_FOLDER -> Known.RENAME_FOLDER + else -> throw ImageKitInvalidDataException("Unknown Type: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for debugging + * and generally doesn't throw. + * + * @throws ImageKitInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + ImageKitInvalidDataException("Value is not a String") + } + + private var validated: Boolean = false + + fun validate(): Type = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Type && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is JobGetResponse && + jobId == other.jobId && + purgeRequestId == other.purgeRequestId && + status == other.status && + type == other.type && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(jobId, purgeRequestId, status, type, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "JobGetResponse{jobId=$jobId, purgeRequestId=$purgeRequestId, status=$status, type=$type, additionalProperties=$additionalProperties}" +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/webhooks/BaseWebhookEvent.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/webhooks/BaseWebhookEvent.kt new file mode 100644 index 0000000..5b0e7ed --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/webhooks/BaseWebhookEvent.kt @@ -0,0 +1,209 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.webhooks + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.imagekit.api.core.ExcludeMissing +import com.imagekit.api.core.JsonField +import com.imagekit.api.core.JsonMissing +import com.imagekit.api.core.JsonValue +import com.imagekit.api.core.checkRequired +import com.imagekit.api.errors.ImageKitInvalidDataException +import java.util.Collections +import java.util.Objects + +class BaseWebhookEvent +private constructor( + private val id: JsonField, + private val type: JsonField, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonField = JsonMissing.of(), + ) : this(id, type, mutableMapOf()) + + /** + * Unique identifier for the event. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun id(): String = id.getRequired("id") + + /** + * The type of webhook event. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun type(): String = type.getRequired("type") + + /** + * Returns the raw JSON value of [id]. + * + * Unlike [id], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id + + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [BaseWebhookEvent]. + * + * The following fields are required: + * ```java + * .id() + * .type() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [BaseWebhookEvent]. */ + class Builder internal constructor() { + + private var id: JsonField? = null + private var type: JsonField? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(baseWebhookEvent: BaseWebhookEvent) = apply { + id = baseWebhookEvent.id + type = baseWebhookEvent.type + additionalProperties = baseWebhookEvent.additionalProperties.toMutableMap() + } + + /** Unique identifier for the event. */ + fun id(id: String) = id(JsonField.of(id)) + + /** + * Sets [Builder.id] to an arbitrary JSON value. + * + * You should usually call [Builder.id] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun id(id: JsonField) = apply { this.id = id } + + /** The type of webhook event. */ + fun type(type: String) = type(JsonField.of(type)) + + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun type(type: JsonField) = apply { this.type = type } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [BaseWebhookEvent]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .id() + * .type() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): BaseWebhookEvent = + BaseWebhookEvent( + checkRequired("id", id), + checkRequired("type", type), + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): BaseWebhookEvent = apply { + if (validated) { + return@apply + } + + id() + type() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (id.asKnown().isPresent) 1 else 0) + (if (type.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is BaseWebhookEvent && + id == other.id && + type == other.type && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(id, type, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "BaseWebhookEvent{id=$id, type=$type, additionalProperties=$additionalProperties}" +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/webhooks/UnsafeUnwrapWebhookEvent.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/webhooks/UnsafeUnwrapWebhookEvent.kt new file mode 100644 index 0000000..a989564 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/webhooks/UnsafeUnwrapWebhookEvent.kt @@ -0,0 +1,560 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.webhooks + +import com.fasterxml.jackson.core.JsonGenerator +import com.fasterxml.jackson.core.ObjectCodec +import com.fasterxml.jackson.databind.JsonNode +import com.fasterxml.jackson.databind.SerializerProvider +import com.fasterxml.jackson.databind.annotation.JsonDeserialize +import com.fasterxml.jackson.databind.annotation.JsonSerialize +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.imagekit.api.core.BaseDeserializer +import com.imagekit.api.core.BaseSerializer +import com.imagekit.api.core.JsonValue +import com.imagekit.api.core.allMaxBy +import com.imagekit.api.core.getOrThrow +import com.imagekit.api.errors.ImageKitInvalidDataException +import java.util.Objects +import java.util.Optional + +/** + * Triggered when a new video transformation request is accepted for processing. This event confirms + * that ImageKit has received and queued your transformation request. Use this for debugging and + * tracking transformation lifecycle. + */ +@JsonDeserialize(using = UnsafeUnwrapWebhookEvent.Deserializer::class) +@JsonSerialize(using = UnsafeUnwrapWebhookEvent.Serializer::class) +class UnsafeUnwrapWebhookEvent +private constructor( + private val videoTransformationAccepted: VideoTransformationAcceptedEvent? = null, + private val videoTransformationReady: VideoTransformationReadyEvent? = null, + private val videoTransformationError: VideoTransformationErrorEvent? = null, + private val uploadPreTransformSuccess: UploadPreTransformSuccessEvent? = null, + private val uploadPreTransformError: UploadPreTransformErrorEvent? = null, + private val uploadPostTransformSuccess: UploadPostTransformSuccessEvent? = null, + private val uploadPostTransformError: UploadPostTransformErrorEvent? = null, + private val _json: JsonValue? = null, +) { + + /** + * Triggered when a new video transformation request is accepted for processing. This event + * confirms that ImageKit has received and queued your transformation request. Use this for + * debugging and tracking transformation lifecycle. + */ + fun videoTransformationAccepted(): Optional = + Optional.ofNullable(videoTransformationAccepted) + + /** + * Triggered when video encoding is finished and the transformed resource is ready to be served. + * This is the key event to listen for - update your database or CMS flags when you receive this + * so your application can start showing the transformed video to users. + */ + fun videoTransformationReady(): Optional = + Optional.ofNullable(videoTransformationReady) + + /** + * Triggered when an error occurs during video encoding. Listen to this webhook to log error + * reasons and debug issues. Check your origin and URL endpoint settings if the reason is + * related to download failure. For other errors, contact ImageKit support. + */ + fun videoTransformationError(): Optional = + Optional.ofNullable(videoTransformationError) + + /** + * Triggered when a pre-transformation completes successfully. The file has been processed with + * the requested transformation and is now available in the Media Library. + */ + fun uploadPreTransformSuccess(): Optional = + Optional.ofNullable(uploadPreTransformSuccess) + + /** + * Triggered when a pre-transformation fails. The file upload may have been accepted, but the + * requested transformation could not be applied. + */ + fun uploadPreTransformError(): Optional = + Optional.ofNullable(uploadPreTransformError) + + /** + * Triggered when a post-transformation completes successfully. The transformed version of the + * file is now ready and can be accessed via the provided URL. Note that each + * post-transformation generates a separate webhook event. + */ + fun uploadPostTransformSuccess(): Optional = + Optional.ofNullable(uploadPostTransformSuccess) + + /** + * Triggered when a post-transformation fails. The original file remains available, but the + * requested transformation could not be generated. + */ + fun uploadPostTransformError(): Optional = + Optional.ofNullable(uploadPostTransformError) + + fun isVideoTransformationAccepted(): Boolean = videoTransformationAccepted != null + + fun isVideoTransformationReady(): Boolean = videoTransformationReady != null + + fun isVideoTransformationError(): Boolean = videoTransformationError != null + + fun isUploadPreTransformSuccess(): Boolean = uploadPreTransformSuccess != null + + fun isUploadPreTransformError(): Boolean = uploadPreTransformError != null + + fun isUploadPostTransformSuccess(): Boolean = uploadPostTransformSuccess != null + + fun isUploadPostTransformError(): Boolean = uploadPostTransformError != null + + /** + * Triggered when a new video transformation request is accepted for processing. This event + * confirms that ImageKit has received and queued your transformation request. Use this for + * debugging and tracking transformation lifecycle. + */ + fun asVideoTransformationAccepted(): VideoTransformationAcceptedEvent = + videoTransformationAccepted.getOrThrow("videoTransformationAccepted") + + /** + * Triggered when video encoding is finished and the transformed resource is ready to be served. + * This is the key event to listen for - update your database or CMS flags when you receive this + * so your application can start showing the transformed video to users. + */ + fun asVideoTransformationReady(): VideoTransformationReadyEvent = + videoTransformationReady.getOrThrow("videoTransformationReady") + + /** + * Triggered when an error occurs during video encoding. Listen to this webhook to log error + * reasons and debug issues. Check your origin and URL endpoint settings if the reason is + * related to download failure. For other errors, contact ImageKit support. + */ + fun asVideoTransformationError(): VideoTransformationErrorEvent = + videoTransformationError.getOrThrow("videoTransformationError") + + /** + * Triggered when a pre-transformation completes successfully. The file has been processed with + * the requested transformation and is now available in the Media Library. + */ + fun asUploadPreTransformSuccess(): UploadPreTransformSuccessEvent = + uploadPreTransformSuccess.getOrThrow("uploadPreTransformSuccess") + + /** + * Triggered when a pre-transformation fails. The file upload may have been accepted, but the + * requested transformation could not be applied. + */ + fun asUploadPreTransformError(): UploadPreTransformErrorEvent = + uploadPreTransformError.getOrThrow("uploadPreTransformError") + + /** + * Triggered when a post-transformation completes successfully. The transformed version of the + * file is now ready and can be accessed via the provided URL. Note that each + * post-transformation generates a separate webhook event. + */ + fun asUploadPostTransformSuccess(): UploadPostTransformSuccessEvent = + uploadPostTransformSuccess.getOrThrow("uploadPostTransformSuccess") + + /** + * Triggered when a post-transformation fails. The original file remains available, but the + * requested transformation could not be generated. + */ + fun asUploadPostTransformError(): UploadPostTransformErrorEvent = + uploadPostTransformError.getOrThrow("uploadPostTransformError") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + videoTransformationAccepted != null -> + visitor.visitVideoTransformationAccepted(videoTransformationAccepted) + videoTransformationReady != null -> + visitor.visitVideoTransformationReady(videoTransformationReady) + videoTransformationError != null -> + visitor.visitVideoTransformationError(videoTransformationError) + uploadPreTransformSuccess != null -> + visitor.visitUploadPreTransformSuccess(uploadPreTransformSuccess) + uploadPreTransformError != null -> + visitor.visitUploadPreTransformError(uploadPreTransformError) + uploadPostTransformSuccess != null -> + visitor.visitUploadPostTransformSuccess(uploadPostTransformSuccess) + uploadPostTransformError != null -> + visitor.visitUploadPostTransformError(uploadPostTransformError) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): UnsafeUnwrapWebhookEvent = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitVideoTransformationAccepted( + videoTransformationAccepted: VideoTransformationAcceptedEvent + ) { + videoTransformationAccepted.validate() + } + + override fun visitVideoTransformationReady( + videoTransformationReady: VideoTransformationReadyEvent + ) { + videoTransformationReady.validate() + } + + override fun visitVideoTransformationError( + videoTransformationError: VideoTransformationErrorEvent + ) { + videoTransformationError.validate() + } + + override fun visitUploadPreTransformSuccess( + uploadPreTransformSuccess: UploadPreTransformSuccessEvent + ) { + uploadPreTransformSuccess.validate() + } + + override fun visitUploadPreTransformError( + uploadPreTransformError: UploadPreTransformErrorEvent + ) { + uploadPreTransformError.validate() + } + + override fun visitUploadPostTransformSuccess( + uploadPostTransformSuccess: UploadPostTransformSuccessEvent + ) { + uploadPostTransformSuccess.validate() + } + + override fun visitUploadPostTransformError( + uploadPostTransformError: UploadPostTransformErrorEvent + ) { + uploadPostTransformError.validate() + } + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitVideoTransformationAccepted( + videoTransformationAccepted: VideoTransformationAcceptedEvent + ) = videoTransformationAccepted.validity() + + override fun visitVideoTransformationReady( + videoTransformationReady: VideoTransformationReadyEvent + ) = videoTransformationReady.validity() + + override fun visitVideoTransformationError( + videoTransformationError: VideoTransformationErrorEvent + ) = videoTransformationError.validity() + + override fun visitUploadPreTransformSuccess( + uploadPreTransformSuccess: UploadPreTransformSuccessEvent + ) = uploadPreTransformSuccess.validity() + + override fun visitUploadPreTransformError( + uploadPreTransformError: UploadPreTransformErrorEvent + ) = uploadPreTransformError.validity() + + override fun visitUploadPostTransformSuccess( + uploadPostTransformSuccess: UploadPostTransformSuccessEvent + ) = uploadPostTransformSuccess.validity() + + override fun visitUploadPostTransformError( + uploadPostTransformError: UploadPostTransformErrorEvent + ) = uploadPostTransformError.validity() + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is UnsafeUnwrapWebhookEvent && + videoTransformationAccepted == other.videoTransformationAccepted && + videoTransformationReady == other.videoTransformationReady && + videoTransformationError == other.videoTransformationError && + uploadPreTransformSuccess == other.uploadPreTransformSuccess && + uploadPreTransformError == other.uploadPreTransformError && + uploadPostTransformSuccess == other.uploadPostTransformSuccess && + uploadPostTransformError == other.uploadPostTransformError + } + + override fun hashCode(): Int = + Objects.hash( + videoTransformationAccepted, + videoTransformationReady, + videoTransformationError, + uploadPreTransformSuccess, + uploadPreTransformError, + uploadPostTransformSuccess, + uploadPostTransformError, + ) + + override fun toString(): String = + when { + videoTransformationAccepted != null -> + "UnsafeUnwrapWebhookEvent{videoTransformationAccepted=$videoTransformationAccepted}" + videoTransformationReady != null -> + "UnsafeUnwrapWebhookEvent{videoTransformationReady=$videoTransformationReady}" + videoTransformationError != null -> + "UnsafeUnwrapWebhookEvent{videoTransformationError=$videoTransformationError}" + uploadPreTransformSuccess != null -> + "UnsafeUnwrapWebhookEvent{uploadPreTransformSuccess=$uploadPreTransformSuccess}" + uploadPreTransformError != null -> + "UnsafeUnwrapWebhookEvent{uploadPreTransformError=$uploadPreTransformError}" + uploadPostTransformSuccess != null -> + "UnsafeUnwrapWebhookEvent{uploadPostTransformSuccess=$uploadPostTransformSuccess}" + uploadPostTransformError != null -> + "UnsafeUnwrapWebhookEvent{uploadPostTransformError=$uploadPostTransformError}" + _json != null -> "UnsafeUnwrapWebhookEvent{_unknown=$_json}" + else -> throw IllegalStateException("Invalid UnsafeUnwrapWebhookEvent") + } + + companion object { + + /** + * Triggered when a new video transformation request is accepted for processing. This event + * confirms that ImageKit has received and queued your transformation request. Use this for + * debugging and tracking transformation lifecycle. + */ + @JvmStatic + fun ofVideoTransformationAccepted( + videoTransformationAccepted: VideoTransformationAcceptedEvent + ) = UnsafeUnwrapWebhookEvent(videoTransformationAccepted = videoTransformationAccepted) + + /** + * Triggered when video encoding is finished and the transformed resource is ready to be + * served. This is the key event to listen for - update your database or CMS flags when you + * receive this so your application can start showing the transformed video to users. + */ + @JvmStatic + fun ofVideoTransformationReady(videoTransformationReady: VideoTransformationReadyEvent) = + UnsafeUnwrapWebhookEvent(videoTransformationReady = videoTransformationReady) + + /** + * Triggered when an error occurs during video encoding. Listen to this webhook to log error + * reasons and debug issues. Check your origin and URL endpoint settings if the reason is + * related to download failure. For other errors, contact ImageKit support. + */ + @JvmStatic + fun ofVideoTransformationError(videoTransformationError: VideoTransformationErrorEvent) = + UnsafeUnwrapWebhookEvent(videoTransformationError = videoTransformationError) + + /** + * Triggered when a pre-transformation completes successfully. The file has been processed + * with the requested transformation and is now available in the Media Library. + */ + @JvmStatic + fun ofUploadPreTransformSuccess(uploadPreTransformSuccess: UploadPreTransformSuccessEvent) = + UnsafeUnwrapWebhookEvent(uploadPreTransformSuccess = uploadPreTransformSuccess) + + /** + * Triggered when a pre-transformation fails. The file upload may have been accepted, but + * the requested transformation could not be applied. + */ + @JvmStatic + fun ofUploadPreTransformError(uploadPreTransformError: UploadPreTransformErrorEvent) = + UnsafeUnwrapWebhookEvent(uploadPreTransformError = uploadPreTransformError) + + /** + * Triggered when a post-transformation completes successfully. The transformed version of + * the file is now ready and can be accessed via the provided URL. Note that each + * post-transformation generates a separate webhook event. + */ + @JvmStatic + fun ofUploadPostTransformSuccess( + uploadPostTransformSuccess: UploadPostTransformSuccessEvent + ) = UnsafeUnwrapWebhookEvent(uploadPostTransformSuccess = uploadPostTransformSuccess) + + /** + * Triggered when a post-transformation fails. The original file remains available, but the + * requested transformation could not be generated. + */ + @JvmStatic + fun ofUploadPostTransformError(uploadPostTransformError: UploadPostTransformErrorEvent) = + UnsafeUnwrapWebhookEvent(uploadPostTransformError = uploadPostTransformError) + } + + /** + * An interface that defines how to map each variant of [UnsafeUnwrapWebhookEvent] to a value of + * type [T]. + */ + interface Visitor { + + /** + * Triggered when a new video transformation request is accepted for processing. This event + * confirms that ImageKit has received and queued your transformation request. Use this for + * debugging and tracking transformation lifecycle. + */ + fun visitVideoTransformationAccepted( + videoTransformationAccepted: VideoTransformationAcceptedEvent + ): T + + /** + * Triggered when video encoding is finished and the transformed resource is ready to be + * served. This is the key event to listen for - update your database or CMS flags when you + * receive this so your application can start showing the transformed video to users. + */ + fun visitVideoTransformationReady( + videoTransformationReady: VideoTransformationReadyEvent + ): T + + /** + * Triggered when an error occurs during video encoding. Listen to this webhook to log error + * reasons and debug issues. Check your origin and URL endpoint settings if the reason is + * related to download failure. For other errors, contact ImageKit support. + */ + fun visitVideoTransformationError( + videoTransformationError: VideoTransformationErrorEvent + ): T + + /** + * Triggered when a pre-transformation completes successfully. The file has been processed + * with the requested transformation and is now available in the Media Library. + */ + fun visitUploadPreTransformSuccess( + uploadPreTransformSuccess: UploadPreTransformSuccessEvent + ): T + + /** + * Triggered when a pre-transformation fails. The file upload may have been accepted, but + * the requested transformation could not be applied. + */ + fun visitUploadPreTransformError(uploadPreTransformError: UploadPreTransformErrorEvent): T + + /** + * Triggered when a post-transformation completes successfully. The transformed version of + * the file is now ready and can be accessed via the provided URL. Note that each + * post-transformation generates a separate webhook event. + */ + fun visitUploadPostTransformSuccess( + uploadPostTransformSuccess: UploadPostTransformSuccessEvent + ): T + + /** + * Triggered when a post-transformation fails. The original file remains available, but the + * requested transformation could not be generated. + */ + fun visitUploadPostTransformError( + uploadPostTransformError: UploadPostTransformErrorEvent + ): T + + /** + * Maps an unknown variant of [UnsafeUnwrapWebhookEvent] to a value of type [T]. + * + * An instance of [UnsafeUnwrapWebhookEvent] can contain an unknown variant if it was + * deserialized from data that doesn't match any known variant. For example, if the SDK is + * on an older version than the API, then the API may respond with new variants that the SDK + * is unaware of. + * + * @throws ImageKitInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw ImageKitInvalidDataException("Unknown UnsafeUnwrapWebhookEvent: $json") + } + } + + internal class Deserializer : + BaseDeserializer(UnsafeUnwrapWebhookEvent::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): UnsafeUnwrapWebhookEvent { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef()) + ?.let { + UnsafeUnwrapWebhookEvent( + videoTransformationAccepted = it, + _json = json, + ) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + UnsafeUnwrapWebhookEvent(videoTransformationReady = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + UnsafeUnwrapWebhookEvent(videoTransformationError = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef()) + ?.let { + UnsafeUnwrapWebhookEvent( + uploadPreTransformSuccess = it, + _json = json, + ) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + UnsafeUnwrapWebhookEvent(uploadPreTransformError = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef()) + ?.let { + UnsafeUnwrapWebhookEvent( + uploadPostTransformSuccess = it, + _json = json, + ) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + UnsafeUnwrapWebhookEvent(uploadPostTransformError = it, _json = json) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely incompatible with all + // the possible variants (e.g. deserializing from boolean). + 0 -> UnsafeUnwrapWebhookEvent(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then use the first + // completely valid match, or simply the first match if none are completely valid. + else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() + } + } + } + + internal class Serializer : + BaseSerializer(UnsafeUnwrapWebhookEvent::class) { + + override fun serialize( + value: UnsafeUnwrapWebhookEvent, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.videoTransformationAccepted != null -> + generator.writeObject(value.videoTransformationAccepted) + value.videoTransformationReady != null -> + generator.writeObject(value.videoTransformationReady) + value.videoTransformationError != null -> + generator.writeObject(value.videoTransformationError) + value.uploadPreTransformSuccess != null -> + generator.writeObject(value.uploadPreTransformSuccess) + value.uploadPreTransformError != null -> + generator.writeObject(value.uploadPreTransformError) + value.uploadPostTransformSuccess != null -> + generator.writeObject(value.uploadPostTransformSuccess) + value.uploadPostTransformError != null -> + generator.writeObject(value.uploadPostTransformError) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid UnsafeUnwrapWebhookEvent") + } + } + } +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/webhooks/UnwrapWebhookEvent.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/webhooks/UnwrapWebhookEvent.kt new file mode 100644 index 0000000..8e1eab9 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/webhooks/UnwrapWebhookEvent.kt @@ -0,0 +1,549 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.webhooks + +import com.fasterxml.jackson.core.JsonGenerator +import com.fasterxml.jackson.core.ObjectCodec +import com.fasterxml.jackson.databind.JsonNode +import com.fasterxml.jackson.databind.SerializerProvider +import com.fasterxml.jackson.databind.annotation.JsonDeserialize +import com.fasterxml.jackson.databind.annotation.JsonSerialize +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.imagekit.api.core.BaseDeserializer +import com.imagekit.api.core.BaseSerializer +import com.imagekit.api.core.JsonValue +import com.imagekit.api.core.allMaxBy +import com.imagekit.api.core.getOrThrow +import com.imagekit.api.errors.ImageKitInvalidDataException +import java.util.Objects +import java.util.Optional + +/** + * Triggered when a new video transformation request is accepted for processing. This event confirms + * that ImageKit has received and queued your transformation request. Use this for debugging and + * tracking transformation lifecycle. + */ +@JsonDeserialize(using = UnwrapWebhookEvent.Deserializer::class) +@JsonSerialize(using = UnwrapWebhookEvent.Serializer::class) +class UnwrapWebhookEvent +private constructor( + private val videoTransformationAccepted: VideoTransformationAcceptedEvent? = null, + private val videoTransformationReady: VideoTransformationReadyEvent? = null, + private val videoTransformationError: VideoTransformationErrorEvent? = null, + private val uploadPreTransformSuccess: UploadPreTransformSuccessEvent? = null, + private val uploadPreTransformError: UploadPreTransformErrorEvent? = null, + private val uploadPostTransformSuccess: UploadPostTransformSuccessEvent? = null, + private val uploadPostTransformError: UploadPostTransformErrorEvent? = null, + private val _json: JsonValue? = null, +) { + + /** + * Triggered when a new video transformation request is accepted for processing. This event + * confirms that ImageKit has received and queued your transformation request. Use this for + * debugging and tracking transformation lifecycle. + */ + fun videoTransformationAccepted(): Optional = + Optional.ofNullable(videoTransformationAccepted) + + /** + * Triggered when video encoding is finished and the transformed resource is ready to be served. + * This is the key event to listen for - update your database or CMS flags when you receive this + * so your application can start showing the transformed video to users. + */ + fun videoTransformationReady(): Optional = + Optional.ofNullable(videoTransformationReady) + + /** + * Triggered when an error occurs during video encoding. Listen to this webhook to log error + * reasons and debug issues. Check your origin and URL endpoint settings if the reason is + * related to download failure. For other errors, contact ImageKit support. + */ + fun videoTransformationError(): Optional = + Optional.ofNullable(videoTransformationError) + + /** + * Triggered when a pre-transformation completes successfully. The file has been processed with + * the requested transformation and is now available in the Media Library. + */ + fun uploadPreTransformSuccess(): Optional = + Optional.ofNullable(uploadPreTransformSuccess) + + /** + * Triggered when a pre-transformation fails. The file upload may have been accepted, but the + * requested transformation could not be applied. + */ + fun uploadPreTransformError(): Optional = + Optional.ofNullable(uploadPreTransformError) + + /** + * Triggered when a post-transformation completes successfully. The transformed version of the + * file is now ready and can be accessed via the provided URL. Note that each + * post-transformation generates a separate webhook event. + */ + fun uploadPostTransformSuccess(): Optional = + Optional.ofNullable(uploadPostTransformSuccess) + + /** + * Triggered when a post-transformation fails. The original file remains available, but the + * requested transformation could not be generated. + */ + fun uploadPostTransformError(): Optional = + Optional.ofNullable(uploadPostTransformError) + + fun isVideoTransformationAccepted(): Boolean = videoTransformationAccepted != null + + fun isVideoTransformationReady(): Boolean = videoTransformationReady != null + + fun isVideoTransformationError(): Boolean = videoTransformationError != null + + fun isUploadPreTransformSuccess(): Boolean = uploadPreTransformSuccess != null + + fun isUploadPreTransformError(): Boolean = uploadPreTransformError != null + + fun isUploadPostTransformSuccess(): Boolean = uploadPostTransformSuccess != null + + fun isUploadPostTransformError(): Boolean = uploadPostTransformError != null + + /** + * Triggered when a new video transformation request is accepted for processing. This event + * confirms that ImageKit has received and queued your transformation request. Use this for + * debugging and tracking transformation lifecycle. + */ + fun asVideoTransformationAccepted(): VideoTransformationAcceptedEvent = + videoTransformationAccepted.getOrThrow("videoTransformationAccepted") + + /** + * Triggered when video encoding is finished and the transformed resource is ready to be served. + * This is the key event to listen for - update your database or CMS flags when you receive this + * so your application can start showing the transformed video to users. + */ + fun asVideoTransformationReady(): VideoTransformationReadyEvent = + videoTransformationReady.getOrThrow("videoTransformationReady") + + /** + * Triggered when an error occurs during video encoding. Listen to this webhook to log error + * reasons and debug issues. Check your origin and URL endpoint settings if the reason is + * related to download failure. For other errors, contact ImageKit support. + */ + fun asVideoTransformationError(): VideoTransformationErrorEvent = + videoTransformationError.getOrThrow("videoTransformationError") + + /** + * Triggered when a pre-transformation completes successfully. The file has been processed with + * the requested transformation and is now available in the Media Library. + */ + fun asUploadPreTransformSuccess(): UploadPreTransformSuccessEvent = + uploadPreTransformSuccess.getOrThrow("uploadPreTransformSuccess") + + /** + * Triggered when a pre-transformation fails. The file upload may have been accepted, but the + * requested transformation could not be applied. + */ + fun asUploadPreTransformError(): UploadPreTransformErrorEvent = + uploadPreTransformError.getOrThrow("uploadPreTransformError") + + /** + * Triggered when a post-transformation completes successfully. The transformed version of the + * file is now ready and can be accessed via the provided URL. Note that each + * post-transformation generates a separate webhook event. + */ + fun asUploadPostTransformSuccess(): UploadPostTransformSuccessEvent = + uploadPostTransformSuccess.getOrThrow("uploadPostTransformSuccess") + + /** + * Triggered when a post-transformation fails. The original file remains available, but the + * requested transformation could not be generated. + */ + fun asUploadPostTransformError(): UploadPostTransformErrorEvent = + uploadPostTransformError.getOrThrow("uploadPostTransformError") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + videoTransformationAccepted != null -> + visitor.visitVideoTransformationAccepted(videoTransformationAccepted) + videoTransformationReady != null -> + visitor.visitVideoTransformationReady(videoTransformationReady) + videoTransformationError != null -> + visitor.visitVideoTransformationError(videoTransformationError) + uploadPreTransformSuccess != null -> + visitor.visitUploadPreTransformSuccess(uploadPreTransformSuccess) + uploadPreTransformError != null -> + visitor.visitUploadPreTransformError(uploadPreTransformError) + uploadPostTransformSuccess != null -> + visitor.visitUploadPostTransformSuccess(uploadPostTransformSuccess) + uploadPostTransformError != null -> + visitor.visitUploadPostTransformError(uploadPostTransformError) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): UnwrapWebhookEvent = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitVideoTransformationAccepted( + videoTransformationAccepted: VideoTransformationAcceptedEvent + ) { + videoTransformationAccepted.validate() + } + + override fun visitVideoTransformationReady( + videoTransformationReady: VideoTransformationReadyEvent + ) { + videoTransformationReady.validate() + } + + override fun visitVideoTransformationError( + videoTransformationError: VideoTransformationErrorEvent + ) { + videoTransformationError.validate() + } + + override fun visitUploadPreTransformSuccess( + uploadPreTransformSuccess: UploadPreTransformSuccessEvent + ) { + uploadPreTransformSuccess.validate() + } + + override fun visitUploadPreTransformError( + uploadPreTransformError: UploadPreTransformErrorEvent + ) { + uploadPreTransformError.validate() + } + + override fun visitUploadPostTransformSuccess( + uploadPostTransformSuccess: UploadPostTransformSuccessEvent + ) { + uploadPostTransformSuccess.validate() + } + + override fun visitUploadPostTransformError( + uploadPostTransformError: UploadPostTransformErrorEvent + ) { + uploadPostTransformError.validate() + } + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitVideoTransformationAccepted( + videoTransformationAccepted: VideoTransformationAcceptedEvent + ) = videoTransformationAccepted.validity() + + override fun visitVideoTransformationReady( + videoTransformationReady: VideoTransformationReadyEvent + ) = videoTransformationReady.validity() + + override fun visitVideoTransformationError( + videoTransformationError: VideoTransformationErrorEvent + ) = videoTransformationError.validity() + + override fun visitUploadPreTransformSuccess( + uploadPreTransformSuccess: UploadPreTransformSuccessEvent + ) = uploadPreTransformSuccess.validity() + + override fun visitUploadPreTransformError( + uploadPreTransformError: UploadPreTransformErrorEvent + ) = uploadPreTransformError.validity() + + override fun visitUploadPostTransformSuccess( + uploadPostTransformSuccess: UploadPostTransformSuccessEvent + ) = uploadPostTransformSuccess.validity() + + override fun visitUploadPostTransformError( + uploadPostTransformError: UploadPostTransformErrorEvent + ) = uploadPostTransformError.validity() + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is UnwrapWebhookEvent && + videoTransformationAccepted == other.videoTransformationAccepted && + videoTransformationReady == other.videoTransformationReady && + videoTransformationError == other.videoTransformationError && + uploadPreTransformSuccess == other.uploadPreTransformSuccess && + uploadPreTransformError == other.uploadPreTransformError && + uploadPostTransformSuccess == other.uploadPostTransformSuccess && + uploadPostTransformError == other.uploadPostTransformError + } + + override fun hashCode(): Int = + Objects.hash( + videoTransformationAccepted, + videoTransformationReady, + videoTransformationError, + uploadPreTransformSuccess, + uploadPreTransformError, + uploadPostTransformSuccess, + uploadPostTransformError, + ) + + override fun toString(): String = + when { + videoTransformationAccepted != null -> + "UnwrapWebhookEvent{videoTransformationAccepted=$videoTransformationAccepted}" + videoTransformationReady != null -> + "UnwrapWebhookEvent{videoTransformationReady=$videoTransformationReady}" + videoTransformationError != null -> + "UnwrapWebhookEvent{videoTransformationError=$videoTransformationError}" + uploadPreTransformSuccess != null -> + "UnwrapWebhookEvent{uploadPreTransformSuccess=$uploadPreTransformSuccess}" + uploadPreTransformError != null -> + "UnwrapWebhookEvent{uploadPreTransformError=$uploadPreTransformError}" + uploadPostTransformSuccess != null -> + "UnwrapWebhookEvent{uploadPostTransformSuccess=$uploadPostTransformSuccess}" + uploadPostTransformError != null -> + "UnwrapWebhookEvent{uploadPostTransformError=$uploadPostTransformError}" + _json != null -> "UnwrapWebhookEvent{_unknown=$_json}" + else -> throw IllegalStateException("Invalid UnwrapWebhookEvent") + } + + companion object { + + /** + * Triggered when a new video transformation request is accepted for processing. This event + * confirms that ImageKit has received and queued your transformation request. Use this for + * debugging and tracking transformation lifecycle. + */ + @JvmStatic + fun ofVideoTransformationAccepted( + videoTransformationAccepted: VideoTransformationAcceptedEvent + ) = UnwrapWebhookEvent(videoTransformationAccepted = videoTransformationAccepted) + + /** + * Triggered when video encoding is finished and the transformed resource is ready to be + * served. This is the key event to listen for - update your database or CMS flags when you + * receive this so your application can start showing the transformed video to users. + */ + @JvmStatic + fun ofVideoTransformationReady(videoTransformationReady: VideoTransformationReadyEvent) = + UnwrapWebhookEvent(videoTransformationReady = videoTransformationReady) + + /** + * Triggered when an error occurs during video encoding. Listen to this webhook to log error + * reasons and debug issues. Check your origin and URL endpoint settings if the reason is + * related to download failure. For other errors, contact ImageKit support. + */ + @JvmStatic + fun ofVideoTransformationError(videoTransformationError: VideoTransformationErrorEvent) = + UnwrapWebhookEvent(videoTransformationError = videoTransformationError) + + /** + * Triggered when a pre-transformation completes successfully. The file has been processed + * with the requested transformation and is now available in the Media Library. + */ + @JvmStatic + fun ofUploadPreTransformSuccess(uploadPreTransformSuccess: UploadPreTransformSuccessEvent) = + UnwrapWebhookEvent(uploadPreTransformSuccess = uploadPreTransformSuccess) + + /** + * Triggered when a pre-transformation fails. The file upload may have been accepted, but + * the requested transformation could not be applied. + */ + @JvmStatic + fun ofUploadPreTransformError(uploadPreTransformError: UploadPreTransformErrorEvent) = + UnwrapWebhookEvent(uploadPreTransformError = uploadPreTransformError) + + /** + * Triggered when a post-transformation completes successfully. The transformed version of + * the file is now ready and can be accessed via the provided URL. Note that each + * post-transformation generates a separate webhook event. + */ + @JvmStatic + fun ofUploadPostTransformSuccess( + uploadPostTransformSuccess: UploadPostTransformSuccessEvent + ) = UnwrapWebhookEvent(uploadPostTransformSuccess = uploadPostTransformSuccess) + + /** + * Triggered when a post-transformation fails. The original file remains available, but the + * requested transformation could not be generated. + */ + @JvmStatic + fun ofUploadPostTransformError(uploadPostTransformError: UploadPostTransformErrorEvent) = + UnwrapWebhookEvent(uploadPostTransformError = uploadPostTransformError) + } + + /** + * An interface that defines how to map each variant of [UnwrapWebhookEvent] to a value of type + * [T]. + */ + interface Visitor { + + /** + * Triggered when a new video transformation request is accepted for processing. This event + * confirms that ImageKit has received and queued your transformation request. Use this for + * debugging and tracking transformation lifecycle. + */ + fun visitVideoTransformationAccepted( + videoTransformationAccepted: VideoTransformationAcceptedEvent + ): T + + /** + * Triggered when video encoding is finished and the transformed resource is ready to be + * served. This is the key event to listen for - update your database or CMS flags when you + * receive this so your application can start showing the transformed video to users. + */ + fun visitVideoTransformationReady( + videoTransformationReady: VideoTransformationReadyEvent + ): T + + /** + * Triggered when an error occurs during video encoding. Listen to this webhook to log error + * reasons and debug issues. Check your origin and URL endpoint settings if the reason is + * related to download failure. For other errors, contact ImageKit support. + */ + fun visitVideoTransformationError( + videoTransformationError: VideoTransformationErrorEvent + ): T + + /** + * Triggered when a pre-transformation completes successfully. The file has been processed + * with the requested transformation and is now available in the Media Library. + */ + fun visitUploadPreTransformSuccess( + uploadPreTransformSuccess: UploadPreTransformSuccessEvent + ): T + + /** + * Triggered when a pre-transformation fails. The file upload may have been accepted, but + * the requested transformation could not be applied. + */ + fun visitUploadPreTransformError(uploadPreTransformError: UploadPreTransformErrorEvent): T + + /** + * Triggered when a post-transformation completes successfully. The transformed version of + * the file is now ready and can be accessed via the provided URL. Note that each + * post-transformation generates a separate webhook event. + */ + fun visitUploadPostTransformSuccess( + uploadPostTransformSuccess: UploadPostTransformSuccessEvent + ): T + + /** + * Triggered when a post-transformation fails. The original file remains available, but the + * requested transformation could not be generated. + */ + fun visitUploadPostTransformError( + uploadPostTransformError: UploadPostTransformErrorEvent + ): T + + /** + * Maps an unknown variant of [UnwrapWebhookEvent] to a value of type [T]. + * + * An instance of [UnwrapWebhookEvent] can contain an unknown variant if it was deserialized + * from data that doesn't match any known variant. For example, if the SDK is on an older + * version than the API, then the API may respond with new variants that the SDK is unaware + * of. + * + * @throws ImageKitInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw ImageKitInvalidDataException("Unknown UnwrapWebhookEvent: $json") + } + } + + internal class Deserializer : BaseDeserializer(UnwrapWebhookEvent::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): UnwrapWebhookEvent { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef()) + ?.let { + UnwrapWebhookEvent(videoTransformationAccepted = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + UnwrapWebhookEvent(videoTransformationReady = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + UnwrapWebhookEvent(videoTransformationError = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef()) + ?.let { + UnwrapWebhookEvent(uploadPreTransformSuccess = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + UnwrapWebhookEvent(uploadPreTransformError = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef()) + ?.let { + UnwrapWebhookEvent(uploadPostTransformSuccess = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + UnwrapWebhookEvent(uploadPostTransformError = it, _json = json) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely incompatible with all + // the possible variants (e.g. deserializing from boolean). + 0 -> UnwrapWebhookEvent(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then use the first + // completely valid match, or simply the first match if none are completely valid. + else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() + } + } + } + + internal class Serializer : BaseSerializer(UnwrapWebhookEvent::class) { + + override fun serialize( + value: UnwrapWebhookEvent, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.videoTransformationAccepted != null -> + generator.writeObject(value.videoTransformationAccepted) + value.videoTransformationReady != null -> + generator.writeObject(value.videoTransformationReady) + value.videoTransformationError != null -> + generator.writeObject(value.videoTransformationError) + value.uploadPreTransformSuccess != null -> + generator.writeObject(value.uploadPreTransformSuccess) + value.uploadPreTransformError != null -> + generator.writeObject(value.uploadPreTransformError) + value.uploadPostTransformSuccess != null -> + generator.writeObject(value.uploadPostTransformSuccess) + value.uploadPostTransformError != null -> + generator.writeObject(value.uploadPostTransformError) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid UnwrapWebhookEvent") + } + } + } +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/webhooks/UploadPostTransformErrorEvent.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/webhooks/UploadPostTransformErrorEvent.kt new file mode 100644 index 0000000..d5ec74e --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/webhooks/UploadPostTransformErrorEvent.kt @@ -0,0 +1,1693 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.webhooks + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.imagekit.api.core.Enum +import com.imagekit.api.core.ExcludeMissing +import com.imagekit.api.core.JsonField +import com.imagekit.api.core.JsonMissing +import com.imagekit.api.core.JsonValue +import com.imagekit.api.core.checkRequired +import com.imagekit.api.errors.ImageKitInvalidDataException +import java.time.OffsetDateTime +import java.util.Collections +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** + * Triggered when a post-transformation fails. The original file remains available, but the + * requested transformation could not be generated. + */ +class UploadPostTransformErrorEvent +private constructor( + private val id: JsonField, + private val type: JsonField, + private val createdAt: JsonField, + private val data: JsonField, + private val request: JsonField, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonField = JsonMissing.of(), + @JsonProperty("created_at") + @ExcludeMissing + createdAt: JsonField = JsonMissing.of(), + @JsonProperty("data") @ExcludeMissing data: JsonField = JsonMissing.of(), + @JsonProperty("request") @ExcludeMissing request: JsonField = JsonMissing.of(), + ) : this(id, type, createdAt, data, request, mutableMapOf()) + + fun toBaseWebhookEvent(): BaseWebhookEvent = + BaseWebhookEvent.builder().id(id).type(type).build() + + /** + * Unique identifier for the event. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun id(): String = id.getRequired("id") + + /** + * The type of webhook event. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun type(): String = type.getRequired("type") + + /** + * Timestamp of when the event occurred in ISO8601 format. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun createdAt(): OffsetDateTime = createdAt.getRequired("created_at") + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun data(): Data = data.getRequired("data") + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun request(): Request = request.getRequired("request") + + /** + * Returns the raw JSON value of [id]. + * + * Unlike [id], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id + + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + + /** + * Returns the raw JSON value of [createdAt]. + * + * Unlike [createdAt], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("created_at") + @ExcludeMissing + fun _createdAt(): JsonField = createdAt + + /** + * Returns the raw JSON value of [data]. + * + * Unlike [data], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("data") @ExcludeMissing fun _data(): JsonField = data + + /** + * Returns the raw JSON value of [request]. + * + * Unlike [request], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("request") @ExcludeMissing fun _request(): JsonField = request + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [UploadPostTransformErrorEvent]. + * + * The following fields are required: + * ```java + * .id() + * .type() + * .createdAt() + * .data() + * .request() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [UploadPostTransformErrorEvent]. */ + class Builder internal constructor() { + + private var id: JsonField? = null + private var type: JsonField? = null + private var createdAt: JsonField? = null + private var data: JsonField? = null + private var request: JsonField? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(uploadPostTransformErrorEvent: UploadPostTransformErrorEvent) = apply { + id = uploadPostTransformErrorEvent.id + type = uploadPostTransformErrorEvent.type + createdAt = uploadPostTransformErrorEvent.createdAt + data = uploadPostTransformErrorEvent.data + request = uploadPostTransformErrorEvent.request + additionalProperties = uploadPostTransformErrorEvent.additionalProperties.toMutableMap() + } + + /** Unique identifier for the event. */ + fun id(id: String) = id(JsonField.of(id)) + + /** + * Sets [Builder.id] to an arbitrary JSON value. + * + * You should usually call [Builder.id] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun id(id: JsonField) = apply { this.id = id } + + /** The type of webhook event. */ + fun type(type: String) = type(JsonField.of(type)) + + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun type(type: JsonField) = apply { this.type = type } + + /** Timestamp of when the event occurred in ISO8601 format. */ + fun createdAt(createdAt: OffsetDateTime) = createdAt(JsonField.of(createdAt)) + + /** + * Sets [Builder.createdAt] to an arbitrary JSON value. + * + * You should usually call [Builder.createdAt] with a well-typed [OffsetDateTime] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun createdAt(createdAt: JsonField) = apply { this.createdAt = createdAt } + + fun data(data: Data) = data(JsonField.of(data)) + + /** + * Sets [Builder.data] to an arbitrary JSON value. + * + * You should usually call [Builder.data] with a well-typed [Data] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun data(data: JsonField) = apply { this.data = data } + + fun request(request: Request) = request(JsonField.of(request)) + + /** + * Sets [Builder.request] to an arbitrary JSON value. + * + * You should usually call [Builder.request] with a well-typed [Request] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun request(request: JsonField) = apply { this.request = request } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [UploadPostTransformErrorEvent]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .id() + * .type() + * .createdAt() + * .data() + * .request() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): UploadPostTransformErrorEvent = + UploadPostTransformErrorEvent( + checkRequired("id", id), + checkRequired("type", type), + checkRequired("createdAt", createdAt), + checkRequired("data", data), + checkRequired("request", request), + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): UploadPostTransformErrorEvent = apply { + if (validated) { + return@apply + } + + id() + type() + createdAt() + data().validate() + request().validate() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (id.asKnown().isPresent) 1 else 0) + + (if (type.asKnown().isPresent) 1 else 0) + + (if (createdAt.asKnown().isPresent) 1 else 0) + + (data.asKnown().getOrNull()?.validity() ?: 0) + + (request.asKnown().getOrNull()?.validity() ?: 0) + + class Data + private constructor( + private val fileId: JsonField, + private val name: JsonField, + private val path: JsonField, + private val transformation: JsonField, + private val url: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("fileId") @ExcludeMissing fileId: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("path") @ExcludeMissing path: JsonField = JsonMissing.of(), + @JsonProperty("transformation") + @ExcludeMissing + transformation: JsonField = JsonMissing.of(), + @JsonProperty("url") @ExcludeMissing url: JsonField = JsonMissing.of(), + ) : this(fileId, name, path, transformation, url, mutableMapOf()) + + /** + * Unique identifier of the originally uploaded file. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun fileId(): String = fileId.getRequired("fileId") + + /** + * Name of the file. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun name(): String = name.getRequired("name") + + /** + * Path of the file. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun path(): String = path.getRequired("path") + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun transformation(): Transformation = transformation.getRequired("transformation") + + /** + * URL of the attempted post-transformation. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun url(): String = url.getRequired("url") + + /** + * Returns the raw JSON value of [fileId]. + * + * Unlike [fileId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("fileId") @ExcludeMissing fun _fileId(): JsonField = fileId + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + + /** + * Returns the raw JSON value of [path]. + * + * Unlike [path], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("path") @ExcludeMissing fun _path(): JsonField = path + + /** + * Returns the raw JSON value of [transformation]. + * + * Unlike [transformation], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("transformation") + @ExcludeMissing + fun _transformation(): JsonField = transformation + + /** + * Returns the raw JSON value of [url]. + * + * Unlike [url], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("url") @ExcludeMissing fun _url(): JsonField = url + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Data]. + * + * The following fields are required: + * ```java + * .fileId() + * .name() + * .path() + * .transformation() + * .url() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Data]. */ + class Builder internal constructor() { + + private var fileId: JsonField? = null + private var name: JsonField? = null + private var path: JsonField? = null + private var transformation: JsonField? = null + private var url: JsonField? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(data: Data) = apply { + fileId = data.fileId + name = data.name + path = data.path + transformation = data.transformation + url = data.url + additionalProperties = data.additionalProperties.toMutableMap() + } + + /** Unique identifier of the originally uploaded file. */ + fun fileId(fileId: String) = fileId(JsonField.of(fileId)) + + /** + * Sets [Builder.fileId] to an arbitrary JSON value. + * + * You should usually call [Builder.fileId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun fileId(fileId: JsonField) = apply { this.fileId = fileId } + + /** Name of the file. */ + fun name(name: String) = name(JsonField.of(name)) + + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun name(name: JsonField) = apply { this.name = name } + + /** Path of the file. */ + fun path(path: String) = path(JsonField.of(path)) + + /** + * Sets [Builder.path] to an arbitrary JSON value. + * + * You should usually call [Builder.path] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun path(path: JsonField) = apply { this.path = path } + + fun transformation(transformation: Transformation) = + transformation(JsonField.of(transformation)) + + /** + * Sets [Builder.transformation] to an arbitrary JSON value. + * + * You should usually call [Builder.transformation] with a well-typed [Transformation] + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun transformation(transformation: JsonField) = apply { + this.transformation = transformation + } + + /** URL of the attempted post-transformation. */ + fun url(url: String) = url(JsonField.of(url)) + + /** + * Sets [Builder.url] to an arbitrary JSON value. + * + * You should usually call [Builder.url] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun url(url: JsonField) = apply { this.url = url } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Data]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .fileId() + * .name() + * .path() + * .transformation() + * .url() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Data = + Data( + checkRequired("fileId", fileId), + checkRequired("name", name), + checkRequired("path", path), + checkRequired("transformation", transformation), + checkRequired("url", url), + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Data = apply { + if (validated) { + return@apply + } + + fileId() + name() + path() + transformation().validate() + url() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (fileId.asKnown().isPresent) 1 else 0) + + (if (name.asKnown().isPresent) 1 else 0) + + (if (path.asKnown().isPresent) 1 else 0) + + (transformation.asKnown().getOrNull()?.validity() ?: 0) + + (if (url.asKnown().isPresent) 1 else 0) + + class Transformation + private constructor( + private val error: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("error") @ExcludeMissing error: JsonField = JsonMissing.of() + ) : this(error, mutableMapOf()) + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected + * value). + */ + fun error(): Error = error.getRequired("error") + + /** + * Returns the raw JSON value of [error]. + * + * Unlike [error], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("error") @ExcludeMissing fun _error(): JsonField = error + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Transformation]. + * + * The following fields are required: + * ```java + * .error() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Transformation]. */ + class Builder internal constructor() { + + private var error: JsonField? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(transformation: Transformation) = apply { + error = transformation.error + additionalProperties = transformation.additionalProperties.toMutableMap() + } + + fun error(error: Error) = error(JsonField.of(error)) + + /** + * Sets [Builder.error] to an arbitrary JSON value. + * + * You should usually call [Builder.error] with a well-typed [Error] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun error(error: JsonField) = apply { this.error = error } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Transformation]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .error() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Transformation = + Transformation( + checkRequired("error", error), + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Transformation = apply { + if (validated) { + return@apply + } + + error().validate() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = (error.asKnown().getOrNull()?.validity() ?: 0) + + class Error + private constructor( + private val reason: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("reason") + @ExcludeMissing + reason: JsonField = JsonMissing.of() + ) : this(reason, mutableMapOf()) + + /** + * Reason for the post-transformation failure. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or + * is unexpectedly missing or null (e.g. if the server responded with an + * unexpected value). + */ + fun reason(): String = reason.getRequired("reason") + + /** + * Returns the raw JSON value of [reason]. + * + * Unlike [reason], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("reason") @ExcludeMissing fun _reason(): JsonField = reason + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Error]. + * + * The following fields are required: + * ```java + * .reason() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Error]. */ + class Builder internal constructor() { + + private var reason: JsonField? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(error: Error) = apply { + reason = error.reason + additionalProperties = error.additionalProperties.toMutableMap() + } + + /** Reason for the post-transformation failure. */ + fun reason(reason: String) = reason(JsonField.of(reason)) + + /** + * Sets [Builder.reason] to an arbitrary JSON value. + * + * You should usually call [Builder.reason] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun reason(reason: JsonField) = apply { this.reason = reason } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Error]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .reason() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Error = + Error(checkRequired("reason", reason), additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Error = apply { + if (validated) { + return@apply + } + + reason() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = (if (reason.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Error && + reason == other.reason && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(reason, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Error{reason=$reason, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Transformation && + error == other.error && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(error, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Transformation{error=$error, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Data && + fileId == other.fileId && + name == other.name && + path == other.path && + transformation == other.transformation && + url == other.url && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(fileId, name, path, transformation, url, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Data{fileId=$fileId, name=$name, path=$path, transformation=$transformation, url=$url, additionalProperties=$additionalProperties}" + } + + class Request + private constructor( + private val transformation: JsonField, + private val xRequestId: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("transformation") + @ExcludeMissing + transformation: JsonField = JsonMissing.of(), + @JsonProperty("x_request_id") + @ExcludeMissing + xRequestId: JsonField = JsonMissing.of(), + ) : this(transformation, xRequestId, mutableMapOf()) + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun transformation(): Transformation = transformation.getRequired("transformation") + + /** + * Unique identifier for the originating request. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun xRequestId(): String = xRequestId.getRequired("x_request_id") + + /** + * Returns the raw JSON value of [transformation]. + * + * Unlike [transformation], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("transformation") + @ExcludeMissing + fun _transformation(): JsonField = transformation + + /** + * Returns the raw JSON value of [xRequestId]. + * + * Unlike [xRequestId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("x_request_id") + @ExcludeMissing + fun _xRequestId(): JsonField = xRequestId + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Request]. + * + * The following fields are required: + * ```java + * .transformation() + * .xRequestId() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Request]. */ + class Builder internal constructor() { + + private var transformation: JsonField? = null + private var xRequestId: JsonField? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(request: Request) = apply { + transformation = request.transformation + xRequestId = request.xRequestId + additionalProperties = request.additionalProperties.toMutableMap() + } + + fun transformation(transformation: Transformation) = + transformation(JsonField.of(transformation)) + + /** + * Sets [Builder.transformation] to an arbitrary JSON value. + * + * You should usually call [Builder.transformation] with a well-typed [Transformation] + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun transformation(transformation: JsonField) = apply { + this.transformation = transformation + } + + /** Unique identifier for the originating request. */ + fun xRequestId(xRequestId: String) = xRequestId(JsonField.of(xRequestId)) + + /** + * Sets [Builder.xRequestId] to an arbitrary JSON value. + * + * You should usually call [Builder.xRequestId] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun xRequestId(xRequestId: JsonField) = apply { this.xRequestId = xRequestId } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Request]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .transformation() + * .xRequestId() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Request = + Request( + checkRequired("transformation", transformation), + checkRequired("xRequestId", xRequestId), + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Request = apply { + if (validated) { + return@apply + } + + transformation().validate() + xRequestId() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (transformation.asKnown().getOrNull()?.validity() ?: 0) + + (if (xRequestId.asKnown().isPresent) 1 else 0) + + class Transformation + private constructor( + private val type: JsonField, + private val protocol: JsonField, + private val value: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("type") @ExcludeMissing type: JsonField = JsonMissing.of(), + @JsonProperty("protocol") + @ExcludeMissing + protocol: JsonField = JsonMissing.of(), + @JsonProperty("value") @ExcludeMissing value: JsonField = JsonMissing.of(), + ) : this(type, protocol, value, mutableMapOf()) + + /** + * Type of the requested post-transformation. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected + * value). + */ + fun type(): Type = type.getRequired("type") + + /** + * Only applicable if transformation type is 'abs'. Streaming protocol used. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun protocol(): Optional = protocol.getOptional("protocol") + + /** + * Value for the requested transformation type. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun value(): Optional = value.getOptional("value") + + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + + /** + * Returns the raw JSON value of [protocol]. + * + * Unlike [protocol], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("protocol") + @ExcludeMissing + fun _protocol(): JsonField = protocol + + /** + * Returns the raw JSON value of [value]. + * + * Unlike [value], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("value") @ExcludeMissing fun _value(): JsonField = value + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Transformation]. + * + * The following fields are required: + * ```java + * .type() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Transformation]. */ + class Builder internal constructor() { + + private var type: JsonField? = null + private var protocol: JsonField = JsonMissing.of() + private var value: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(transformation: Transformation) = apply { + type = transformation.type + protocol = transformation.protocol + value = transformation.value + additionalProperties = transformation.additionalProperties.toMutableMap() + } + + /** Type of the requested post-transformation. */ + fun type(type: Type) = type(JsonField.of(type)) + + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [Type] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun type(type: JsonField) = apply { this.type = type } + + /** Only applicable if transformation type is 'abs'. Streaming protocol used. */ + fun protocol(protocol: Protocol) = protocol(JsonField.of(protocol)) + + /** + * Sets [Builder.protocol] to an arbitrary JSON value. + * + * You should usually call [Builder.protocol] with a well-typed [Protocol] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun protocol(protocol: JsonField) = apply { this.protocol = protocol } + + /** Value for the requested transformation type. */ + fun value(value: String) = value(JsonField.of(value)) + + /** + * Sets [Builder.value] to an arbitrary JSON value. + * + * You should usually call [Builder.value] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun value(value: JsonField) = apply { this.value = value } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Transformation]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .type() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Transformation = + Transformation( + checkRequired("type", type), + protocol, + value, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Transformation = apply { + if (validated) { + return@apply + } + + type().validate() + protocol().ifPresent { it.validate() } + value() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (type.asKnown().getOrNull()?.validity() ?: 0) + + (protocol.asKnown().getOrNull()?.validity() ?: 0) + + (if (value.asKnown().isPresent) 1 else 0) + + /** Type of the requested post-transformation. */ + class Type @JsonCreator private constructor(private val value: JsonField) : + Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that + * doesn't match any known member, and you want to know that value. For example, if + * the SDK is on an older version than the API, then the API may respond with new + * members that the SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val TRANSFORMATION = of("transformation") + + @JvmField val ABS = of("abs") + + @JvmField val GIF_TO_VIDEO = of("gif-to-video") + + @JvmField val THUMBNAIL = of("thumbnail") + + @JvmStatic fun of(value: String) = Type(JsonField.of(value)) + } + + /** An enum containing [Type]'s known values. */ + enum class Known { + TRANSFORMATION, + ABS, + GIF_TO_VIDEO, + THUMBNAIL, + } + + /** + * An enum containing [Type]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [Type] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, + * if the SDK is on an older version than the API, then the API may respond with + * new members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + TRANSFORMATION, + ABS, + GIF_TO_VIDEO, + THUMBNAIL, + /** + * An enum member indicating that [Type] was instantiated with an unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if + * you want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + TRANSFORMATION -> Value.TRANSFORMATION + ABS -> Value.ABS + GIF_TO_VIDEO -> Value.GIF_TO_VIDEO + THUMBNAIL -> Value.THUMBNAIL + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and + * don't want to throw for the unknown case. + * + * @throws ImageKitInvalidDataException if this class instance's value is a not a + * known member. + */ + fun known(): Known = + when (this) { + TRANSFORMATION -> Known.TRANSFORMATION + ABS -> Known.ABS + GIF_TO_VIDEO -> Known.GIF_TO_VIDEO + THUMBNAIL -> Known.THUMBNAIL + else -> throw ImageKitInvalidDataException("Unknown Type: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for + * debugging and generally doesn't throw. + * + * @throws ImageKitInvalidDataException if this class instance's value does not have + * the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + ImageKitInvalidDataException("Value is not a String") + } + + private var validated: Boolean = false + + fun validate(): Type = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Type && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + /** Only applicable if transformation type is 'abs'. Streaming protocol used. */ + class Protocol @JsonCreator private constructor(private val value: JsonField) : + Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that + * doesn't match any known member, and you want to know that value. For example, if + * the SDK is on an older version than the API, then the API may respond with new + * members that the SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val HLS = of("hls") + + @JvmField val DASH = of("dash") + + @JvmStatic fun of(value: String) = Protocol(JsonField.of(value)) + } + + /** An enum containing [Protocol]'s known values. */ + enum class Known { + HLS, + DASH, + } + + /** + * An enum containing [Protocol]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [Protocol] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, + * if the SDK is on an older version than the API, then the API may respond with + * new members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + HLS, + DASH, + /** + * An enum member indicating that [Protocol] was instantiated with an unknown + * value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if + * you want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + HLS -> Value.HLS + DASH -> Value.DASH + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and + * don't want to throw for the unknown case. + * + * @throws ImageKitInvalidDataException if this class instance's value is a not a + * known member. + */ + fun known(): Known = + when (this) { + HLS -> Known.HLS + DASH -> Known.DASH + else -> throw ImageKitInvalidDataException("Unknown Protocol: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for + * debugging and generally doesn't throw. + * + * @throws ImageKitInvalidDataException if this class instance's value does not have + * the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + ImageKitInvalidDataException("Value is not a String") + } + + private var validated: Boolean = false + + fun validate(): Protocol = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Protocol && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Transformation && + type == other.type && + protocol == other.protocol && + value == other.value && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(type, protocol, value, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Transformation{type=$type, protocol=$protocol, value=$value, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Request && + transformation == other.transformation && + xRequestId == other.xRequestId && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(transformation, xRequestId, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Request{transformation=$transformation, xRequestId=$xRequestId, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is UploadPostTransformErrorEvent && + id == other.id && + type == other.type && + createdAt == other.createdAt && + data == other.data && + request == other.request && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(id, type, createdAt, data, request, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "UploadPostTransformErrorEvent{id=$id, type=$type, createdAt=$createdAt, data=$data, request=$request, additionalProperties=$additionalProperties}" +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/webhooks/UploadPostTransformSuccessEvent.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/webhooks/UploadPostTransformSuccessEvent.kt new file mode 100644 index 0000000..78cc1df --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/webhooks/UploadPostTransformSuccessEvent.kt @@ -0,0 +1,1292 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.webhooks + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.imagekit.api.core.Enum +import com.imagekit.api.core.ExcludeMissing +import com.imagekit.api.core.JsonField +import com.imagekit.api.core.JsonMissing +import com.imagekit.api.core.JsonValue +import com.imagekit.api.core.checkRequired +import com.imagekit.api.errors.ImageKitInvalidDataException +import java.time.OffsetDateTime +import java.util.Collections +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** + * Triggered when a post-transformation completes successfully. The transformed version of the file + * is now ready and can be accessed via the provided URL. Note that each post-transformation + * generates a separate webhook event. + */ +class UploadPostTransformSuccessEvent +private constructor( + private val id: JsonField, + private val type: JsonField, + private val createdAt: JsonField, + private val data: JsonField, + private val request: JsonField, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonField = JsonMissing.of(), + @JsonProperty("created_at") + @ExcludeMissing + createdAt: JsonField = JsonMissing.of(), + @JsonProperty("data") @ExcludeMissing data: JsonField = JsonMissing.of(), + @JsonProperty("request") @ExcludeMissing request: JsonField = JsonMissing.of(), + ) : this(id, type, createdAt, data, request, mutableMapOf()) + + fun toBaseWebhookEvent(): BaseWebhookEvent = + BaseWebhookEvent.builder().id(id).type(type).build() + + /** + * Unique identifier for the event. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun id(): String = id.getRequired("id") + + /** + * The type of webhook event. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun type(): String = type.getRequired("type") + + /** + * Timestamp of when the event occurred in ISO8601 format. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun createdAt(): OffsetDateTime = createdAt.getRequired("created_at") + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun data(): Data = data.getRequired("data") + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun request(): Request = request.getRequired("request") + + /** + * Returns the raw JSON value of [id]. + * + * Unlike [id], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id + + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + + /** + * Returns the raw JSON value of [createdAt]. + * + * Unlike [createdAt], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("created_at") + @ExcludeMissing + fun _createdAt(): JsonField = createdAt + + /** + * Returns the raw JSON value of [data]. + * + * Unlike [data], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("data") @ExcludeMissing fun _data(): JsonField = data + + /** + * Returns the raw JSON value of [request]. + * + * Unlike [request], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("request") @ExcludeMissing fun _request(): JsonField = request + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [UploadPostTransformSuccessEvent]. + * + * The following fields are required: + * ```java + * .id() + * .type() + * .createdAt() + * .data() + * .request() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [UploadPostTransformSuccessEvent]. */ + class Builder internal constructor() { + + private var id: JsonField? = null + private var type: JsonField? = null + private var createdAt: JsonField? = null + private var data: JsonField? = null + private var request: JsonField? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(uploadPostTransformSuccessEvent: UploadPostTransformSuccessEvent) = + apply { + id = uploadPostTransformSuccessEvent.id + type = uploadPostTransformSuccessEvent.type + createdAt = uploadPostTransformSuccessEvent.createdAt + data = uploadPostTransformSuccessEvent.data + request = uploadPostTransformSuccessEvent.request + additionalProperties = + uploadPostTransformSuccessEvent.additionalProperties.toMutableMap() + } + + /** Unique identifier for the event. */ + fun id(id: String) = id(JsonField.of(id)) + + /** + * Sets [Builder.id] to an arbitrary JSON value. + * + * You should usually call [Builder.id] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun id(id: JsonField) = apply { this.id = id } + + /** The type of webhook event. */ + fun type(type: String) = type(JsonField.of(type)) + + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun type(type: JsonField) = apply { this.type = type } + + /** Timestamp of when the event occurred in ISO8601 format. */ + fun createdAt(createdAt: OffsetDateTime) = createdAt(JsonField.of(createdAt)) + + /** + * Sets [Builder.createdAt] to an arbitrary JSON value. + * + * You should usually call [Builder.createdAt] with a well-typed [OffsetDateTime] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun createdAt(createdAt: JsonField) = apply { this.createdAt = createdAt } + + fun data(data: Data) = data(JsonField.of(data)) + + /** + * Sets [Builder.data] to an arbitrary JSON value. + * + * You should usually call [Builder.data] with a well-typed [Data] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun data(data: JsonField) = apply { this.data = data } + + fun request(request: Request) = request(JsonField.of(request)) + + /** + * Sets [Builder.request] to an arbitrary JSON value. + * + * You should usually call [Builder.request] with a well-typed [Request] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun request(request: JsonField) = apply { this.request = request } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [UploadPostTransformSuccessEvent]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .id() + * .type() + * .createdAt() + * .data() + * .request() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): UploadPostTransformSuccessEvent = + UploadPostTransformSuccessEvent( + checkRequired("id", id), + checkRequired("type", type), + checkRequired("createdAt", createdAt), + checkRequired("data", data), + checkRequired("request", request), + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): UploadPostTransformSuccessEvent = apply { + if (validated) { + return@apply + } + + id() + type() + createdAt() + data().validate() + request().validate() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (id.asKnown().isPresent) 1 else 0) + + (if (type.asKnown().isPresent) 1 else 0) + + (if (createdAt.asKnown().isPresent) 1 else 0) + + (data.asKnown().getOrNull()?.validity() ?: 0) + + (request.asKnown().getOrNull()?.validity() ?: 0) + + class Data + private constructor( + private val fileId: JsonField, + private val name: JsonField, + private val url: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("fileId") @ExcludeMissing fileId: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("url") @ExcludeMissing url: JsonField = JsonMissing.of(), + ) : this(fileId, name, url, mutableMapOf()) + + /** + * Unique identifier of the originally uploaded file. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun fileId(): String = fileId.getRequired("fileId") + + /** + * Name of the file. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun name(): String = name.getRequired("name") + + /** + * URL of the generated post-transformation. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun url(): String = url.getRequired("url") + + /** + * Returns the raw JSON value of [fileId]. + * + * Unlike [fileId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("fileId") @ExcludeMissing fun _fileId(): JsonField = fileId + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + + /** + * Returns the raw JSON value of [url]. + * + * Unlike [url], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("url") @ExcludeMissing fun _url(): JsonField = url + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Data]. + * + * The following fields are required: + * ```java + * .fileId() + * .name() + * .url() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Data]. */ + class Builder internal constructor() { + + private var fileId: JsonField? = null + private var name: JsonField? = null + private var url: JsonField? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(data: Data) = apply { + fileId = data.fileId + name = data.name + url = data.url + additionalProperties = data.additionalProperties.toMutableMap() + } + + /** Unique identifier of the originally uploaded file. */ + fun fileId(fileId: String) = fileId(JsonField.of(fileId)) + + /** + * Sets [Builder.fileId] to an arbitrary JSON value. + * + * You should usually call [Builder.fileId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun fileId(fileId: JsonField) = apply { this.fileId = fileId } + + /** Name of the file. */ + fun name(name: String) = name(JsonField.of(name)) + + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun name(name: JsonField) = apply { this.name = name } + + /** URL of the generated post-transformation. */ + fun url(url: String) = url(JsonField.of(url)) + + /** + * Sets [Builder.url] to an arbitrary JSON value. + * + * You should usually call [Builder.url] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun url(url: JsonField) = apply { this.url = url } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Data]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .fileId() + * .name() + * .url() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Data = + Data( + checkRequired("fileId", fileId), + checkRequired("name", name), + checkRequired("url", url), + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Data = apply { + if (validated) { + return@apply + } + + fileId() + name() + url() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (fileId.asKnown().isPresent) 1 else 0) + + (if (name.asKnown().isPresent) 1 else 0) + + (if (url.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Data && + fileId == other.fileId && + name == other.name && + url == other.url && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(fileId, name, url, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Data{fileId=$fileId, name=$name, url=$url, additionalProperties=$additionalProperties}" + } + + class Request + private constructor( + private val transformation: JsonField, + private val xRequestId: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("transformation") + @ExcludeMissing + transformation: JsonField = JsonMissing.of(), + @JsonProperty("x_request_id") + @ExcludeMissing + xRequestId: JsonField = JsonMissing.of(), + ) : this(transformation, xRequestId, mutableMapOf()) + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun transformation(): Transformation = transformation.getRequired("transformation") + + /** + * Unique identifier for the originating request. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun xRequestId(): String = xRequestId.getRequired("x_request_id") + + /** + * Returns the raw JSON value of [transformation]. + * + * Unlike [transformation], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("transformation") + @ExcludeMissing + fun _transformation(): JsonField = transformation + + /** + * Returns the raw JSON value of [xRequestId]. + * + * Unlike [xRequestId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("x_request_id") + @ExcludeMissing + fun _xRequestId(): JsonField = xRequestId + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Request]. + * + * The following fields are required: + * ```java + * .transformation() + * .xRequestId() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Request]. */ + class Builder internal constructor() { + + private var transformation: JsonField? = null + private var xRequestId: JsonField? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(request: Request) = apply { + transformation = request.transformation + xRequestId = request.xRequestId + additionalProperties = request.additionalProperties.toMutableMap() + } + + fun transformation(transformation: Transformation) = + transformation(JsonField.of(transformation)) + + /** + * Sets [Builder.transformation] to an arbitrary JSON value. + * + * You should usually call [Builder.transformation] with a well-typed [Transformation] + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun transformation(transformation: JsonField) = apply { + this.transformation = transformation + } + + /** Unique identifier for the originating request. */ + fun xRequestId(xRequestId: String) = xRequestId(JsonField.of(xRequestId)) + + /** + * Sets [Builder.xRequestId] to an arbitrary JSON value. + * + * You should usually call [Builder.xRequestId] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun xRequestId(xRequestId: JsonField) = apply { this.xRequestId = xRequestId } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Request]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .transformation() + * .xRequestId() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Request = + Request( + checkRequired("transformation", transformation), + checkRequired("xRequestId", xRequestId), + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Request = apply { + if (validated) { + return@apply + } + + transformation().validate() + xRequestId() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (transformation.asKnown().getOrNull()?.validity() ?: 0) + + (if (xRequestId.asKnown().isPresent) 1 else 0) + + class Transformation + private constructor( + private val type: JsonField, + private val protocol: JsonField, + private val value: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("type") @ExcludeMissing type: JsonField = JsonMissing.of(), + @JsonProperty("protocol") + @ExcludeMissing + protocol: JsonField = JsonMissing.of(), + @JsonProperty("value") @ExcludeMissing value: JsonField = JsonMissing.of(), + ) : this(type, protocol, value, mutableMapOf()) + + /** + * Type of the requested post-transformation. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected + * value). + */ + fun type(): Type = type.getRequired("type") + + /** + * Only applicable if transformation type is 'abs'. Streaming protocol used. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun protocol(): Optional = protocol.getOptional("protocol") + + /** + * Value for the requested transformation type. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun value(): Optional = value.getOptional("value") + + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + + /** + * Returns the raw JSON value of [protocol]. + * + * Unlike [protocol], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("protocol") + @ExcludeMissing + fun _protocol(): JsonField = protocol + + /** + * Returns the raw JSON value of [value]. + * + * Unlike [value], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("value") @ExcludeMissing fun _value(): JsonField = value + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Transformation]. + * + * The following fields are required: + * ```java + * .type() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Transformation]. */ + class Builder internal constructor() { + + private var type: JsonField? = null + private var protocol: JsonField = JsonMissing.of() + private var value: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(transformation: Transformation) = apply { + type = transformation.type + protocol = transformation.protocol + value = transformation.value + additionalProperties = transformation.additionalProperties.toMutableMap() + } + + /** Type of the requested post-transformation. */ + fun type(type: Type) = type(JsonField.of(type)) + + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [Type] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun type(type: JsonField) = apply { this.type = type } + + /** Only applicable if transformation type is 'abs'. Streaming protocol used. */ + fun protocol(protocol: Protocol) = protocol(JsonField.of(protocol)) + + /** + * Sets [Builder.protocol] to an arbitrary JSON value. + * + * You should usually call [Builder.protocol] with a well-typed [Protocol] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun protocol(protocol: JsonField) = apply { this.protocol = protocol } + + /** Value for the requested transformation type. */ + fun value(value: String) = value(JsonField.of(value)) + + /** + * Sets [Builder.value] to an arbitrary JSON value. + * + * You should usually call [Builder.value] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun value(value: JsonField) = apply { this.value = value } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Transformation]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .type() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Transformation = + Transformation( + checkRequired("type", type), + protocol, + value, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Transformation = apply { + if (validated) { + return@apply + } + + type().validate() + protocol().ifPresent { it.validate() } + value() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (type.asKnown().getOrNull()?.validity() ?: 0) + + (protocol.asKnown().getOrNull()?.validity() ?: 0) + + (if (value.asKnown().isPresent) 1 else 0) + + /** Type of the requested post-transformation. */ + class Type @JsonCreator private constructor(private val value: JsonField) : + Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that + * doesn't match any known member, and you want to know that value. For example, if + * the SDK is on an older version than the API, then the API may respond with new + * members that the SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val TRANSFORMATION = of("transformation") + + @JvmField val ABS = of("abs") + + @JvmField val GIF_TO_VIDEO = of("gif-to-video") + + @JvmField val THUMBNAIL = of("thumbnail") + + @JvmStatic fun of(value: String) = Type(JsonField.of(value)) + } + + /** An enum containing [Type]'s known values. */ + enum class Known { + TRANSFORMATION, + ABS, + GIF_TO_VIDEO, + THUMBNAIL, + } + + /** + * An enum containing [Type]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [Type] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, + * if the SDK is on an older version than the API, then the API may respond with + * new members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + TRANSFORMATION, + ABS, + GIF_TO_VIDEO, + THUMBNAIL, + /** + * An enum member indicating that [Type] was instantiated with an unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if + * you want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + TRANSFORMATION -> Value.TRANSFORMATION + ABS -> Value.ABS + GIF_TO_VIDEO -> Value.GIF_TO_VIDEO + THUMBNAIL -> Value.THUMBNAIL + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and + * don't want to throw for the unknown case. + * + * @throws ImageKitInvalidDataException if this class instance's value is a not a + * known member. + */ + fun known(): Known = + when (this) { + TRANSFORMATION -> Known.TRANSFORMATION + ABS -> Known.ABS + GIF_TO_VIDEO -> Known.GIF_TO_VIDEO + THUMBNAIL -> Known.THUMBNAIL + else -> throw ImageKitInvalidDataException("Unknown Type: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for + * debugging and generally doesn't throw. + * + * @throws ImageKitInvalidDataException if this class instance's value does not have + * the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + ImageKitInvalidDataException("Value is not a String") + } + + private var validated: Boolean = false + + fun validate(): Type = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Type && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + /** Only applicable if transformation type is 'abs'. Streaming protocol used. */ + class Protocol @JsonCreator private constructor(private val value: JsonField) : + Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that + * doesn't match any known member, and you want to know that value. For example, if + * the SDK is on an older version than the API, then the API may respond with new + * members that the SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val HLS = of("hls") + + @JvmField val DASH = of("dash") + + @JvmStatic fun of(value: String) = Protocol(JsonField.of(value)) + } + + /** An enum containing [Protocol]'s known values. */ + enum class Known { + HLS, + DASH, + } + + /** + * An enum containing [Protocol]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [Protocol] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, + * if the SDK is on an older version than the API, then the API may respond with + * new members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + HLS, + DASH, + /** + * An enum member indicating that [Protocol] was instantiated with an unknown + * value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if + * you want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + HLS -> Value.HLS + DASH -> Value.DASH + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and + * don't want to throw for the unknown case. + * + * @throws ImageKitInvalidDataException if this class instance's value is a not a + * known member. + */ + fun known(): Known = + when (this) { + HLS -> Known.HLS + DASH -> Known.DASH + else -> throw ImageKitInvalidDataException("Unknown Protocol: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for + * debugging and generally doesn't throw. + * + * @throws ImageKitInvalidDataException if this class instance's value does not have + * the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + ImageKitInvalidDataException("Value is not a String") + } + + private var validated: Boolean = false + + fun validate(): Protocol = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Protocol && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Transformation && + type == other.type && + protocol == other.protocol && + value == other.value && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(type, protocol, value, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Transformation{type=$type, protocol=$protocol, value=$value, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Request && + transformation == other.transformation && + xRequestId == other.xRequestId && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(transformation, xRequestId, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Request{transformation=$transformation, xRequestId=$xRequestId, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is UploadPostTransformSuccessEvent && + id == other.id && + type == other.type && + createdAt == other.createdAt && + data == other.data && + request == other.request && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(id, type, createdAt, data, request, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "UploadPostTransformSuccessEvent{id=$id, type=$type, createdAt=$createdAt, data=$data, request=$request, additionalProperties=$additionalProperties}" +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/webhooks/UploadPreTransformErrorEvent.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/webhooks/UploadPreTransformErrorEvent.kt new file mode 100644 index 0000000..50655f3 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/webhooks/UploadPreTransformErrorEvent.kt @@ -0,0 +1,1103 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.webhooks + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.imagekit.api.core.ExcludeMissing +import com.imagekit.api.core.JsonField +import com.imagekit.api.core.JsonMissing +import com.imagekit.api.core.JsonValue +import com.imagekit.api.core.checkRequired +import com.imagekit.api.errors.ImageKitInvalidDataException +import java.time.OffsetDateTime +import java.util.Collections +import java.util.Objects +import kotlin.jvm.optionals.getOrNull + +/** + * Triggered when a pre-transformation fails. The file upload may have been accepted, but the + * requested transformation could not be applied. + */ +class UploadPreTransformErrorEvent +private constructor( + private val id: JsonField, + private val type: JsonField, + private val createdAt: JsonField, + private val data: JsonField, + private val request: JsonField, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonField = JsonMissing.of(), + @JsonProperty("created_at") + @ExcludeMissing + createdAt: JsonField = JsonMissing.of(), + @JsonProperty("data") @ExcludeMissing data: JsonField = JsonMissing.of(), + @JsonProperty("request") @ExcludeMissing request: JsonField = JsonMissing.of(), + ) : this(id, type, createdAt, data, request, mutableMapOf()) + + fun toBaseWebhookEvent(): BaseWebhookEvent = + BaseWebhookEvent.builder().id(id).type(type).build() + + /** + * Unique identifier for the event. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun id(): String = id.getRequired("id") + + /** + * The type of webhook event. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun type(): String = type.getRequired("type") + + /** + * Timestamp of when the event occurred in ISO8601 format. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun createdAt(): OffsetDateTime = createdAt.getRequired("created_at") + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun data(): Data = data.getRequired("data") + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun request(): Request = request.getRequired("request") + + /** + * Returns the raw JSON value of [id]. + * + * Unlike [id], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id + + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + + /** + * Returns the raw JSON value of [createdAt]. + * + * Unlike [createdAt], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("created_at") + @ExcludeMissing + fun _createdAt(): JsonField = createdAt + + /** + * Returns the raw JSON value of [data]. + * + * Unlike [data], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("data") @ExcludeMissing fun _data(): JsonField = data + + /** + * Returns the raw JSON value of [request]. + * + * Unlike [request], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("request") @ExcludeMissing fun _request(): JsonField = request + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [UploadPreTransformErrorEvent]. + * + * The following fields are required: + * ```java + * .id() + * .type() + * .createdAt() + * .data() + * .request() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [UploadPreTransformErrorEvent]. */ + class Builder internal constructor() { + + private var id: JsonField? = null + private var type: JsonField? = null + private var createdAt: JsonField? = null + private var data: JsonField? = null + private var request: JsonField? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(uploadPreTransformErrorEvent: UploadPreTransformErrorEvent) = apply { + id = uploadPreTransformErrorEvent.id + type = uploadPreTransformErrorEvent.type + createdAt = uploadPreTransformErrorEvent.createdAt + data = uploadPreTransformErrorEvent.data + request = uploadPreTransformErrorEvent.request + additionalProperties = uploadPreTransformErrorEvent.additionalProperties.toMutableMap() + } + + /** Unique identifier for the event. */ + fun id(id: String) = id(JsonField.of(id)) + + /** + * Sets [Builder.id] to an arbitrary JSON value. + * + * You should usually call [Builder.id] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun id(id: JsonField) = apply { this.id = id } + + /** The type of webhook event. */ + fun type(type: String) = type(JsonField.of(type)) + + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun type(type: JsonField) = apply { this.type = type } + + /** Timestamp of when the event occurred in ISO8601 format. */ + fun createdAt(createdAt: OffsetDateTime) = createdAt(JsonField.of(createdAt)) + + /** + * Sets [Builder.createdAt] to an arbitrary JSON value. + * + * You should usually call [Builder.createdAt] with a well-typed [OffsetDateTime] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun createdAt(createdAt: JsonField) = apply { this.createdAt = createdAt } + + fun data(data: Data) = data(JsonField.of(data)) + + /** + * Sets [Builder.data] to an arbitrary JSON value. + * + * You should usually call [Builder.data] with a well-typed [Data] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun data(data: JsonField) = apply { this.data = data } + + fun request(request: Request) = request(JsonField.of(request)) + + /** + * Sets [Builder.request] to an arbitrary JSON value. + * + * You should usually call [Builder.request] with a well-typed [Request] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun request(request: JsonField) = apply { this.request = request } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [UploadPreTransformErrorEvent]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .id() + * .type() + * .createdAt() + * .data() + * .request() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): UploadPreTransformErrorEvent = + UploadPreTransformErrorEvent( + checkRequired("id", id), + checkRequired("type", type), + checkRequired("createdAt", createdAt), + checkRequired("data", data), + checkRequired("request", request), + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): UploadPreTransformErrorEvent = apply { + if (validated) { + return@apply + } + + id() + type() + createdAt() + data().validate() + request().validate() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (id.asKnown().isPresent) 1 else 0) + + (if (type.asKnown().isPresent) 1 else 0) + + (if (createdAt.asKnown().isPresent) 1 else 0) + + (data.asKnown().getOrNull()?.validity() ?: 0) + + (request.asKnown().getOrNull()?.validity() ?: 0) + + class Data + private constructor( + private val name: JsonField, + private val path: JsonField, + private val transformation: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("path") @ExcludeMissing path: JsonField = JsonMissing.of(), + @JsonProperty("transformation") + @ExcludeMissing + transformation: JsonField = JsonMissing.of(), + ) : this(name, path, transformation, mutableMapOf()) + + /** + * Name of the file. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun name(): String = name.getRequired("name") + + /** + * Path of the file. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun path(): String = path.getRequired("path") + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun transformation(): Transformation = transformation.getRequired("transformation") + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + + /** + * Returns the raw JSON value of [path]. + * + * Unlike [path], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("path") @ExcludeMissing fun _path(): JsonField = path + + /** + * Returns the raw JSON value of [transformation]. + * + * Unlike [transformation], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("transformation") + @ExcludeMissing + fun _transformation(): JsonField = transformation + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Data]. + * + * The following fields are required: + * ```java + * .name() + * .path() + * .transformation() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Data]. */ + class Builder internal constructor() { + + private var name: JsonField? = null + private var path: JsonField? = null + private var transformation: JsonField? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(data: Data) = apply { + name = data.name + path = data.path + transformation = data.transformation + additionalProperties = data.additionalProperties.toMutableMap() + } + + /** Name of the file. */ + fun name(name: String) = name(JsonField.of(name)) + + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun name(name: JsonField) = apply { this.name = name } + + /** Path of the file. */ + fun path(path: String) = path(JsonField.of(path)) + + /** + * Sets [Builder.path] to an arbitrary JSON value. + * + * You should usually call [Builder.path] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun path(path: JsonField) = apply { this.path = path } + + fun transformation(transformation: Transformation) = + transformation(JsonField.of(transformation)) + + /** + * Sets [Builder.transformation] to an arbitrary JSON value. + * + * You should usually call [Builder.transformation] with a well-typed [Transformation] + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun transformation(transformation: JsonField) = apply { + this.transformation = transformation + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Data]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .name() + * .path() + * .transformation() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Data = + Data( + checkRequired("name", name), + checkRequired("path", path), + checkRequired("transformation", transformation), + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Data = apply { + if (validated) { + return@apply + } + + name() + path() + transformation().validate() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (name.asKnown().isPresent) 1 else 0) + + (if (path.asKnown().isPresent) 1 else 0) + + (transformation.asKnown().getOrNull()?.validity() ?: 0) + + class Transformation + private constructor( + private val error: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("error") @ExcludeMissing error: JsonField = JsonMissing.of() + ) : this(error, mutableMapOf()) + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected + * value). + */ + fun error(): Error = error.getRequired("error") + + /** + * Returns the raw JSON value of [error]. + * + * Unlike [error], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("error") @ExcludeMissing fun _error(): JsonField = error + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Transformation]. + * + * The following fields are required: + * ```java + * .error() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Transformation]. */ + class Builder internal constructor() { + + private var error: JsonField? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(transformation: Transformation) = apply { + error = transformation.error + additionalProperties = transformation.additionalProperties.toMutableMap() + } + + fun error(error: Error) = error(JsonField.of(error)) + + /** + * Sets [Builder.error] to an arbitrary JSON value. + * + * You should usually call [Builder.error] with a well-typed [Error] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun error(error: JsonField) = apply { this.error = error } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Transformation]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .error() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Transformation = + Transformation( + checkRequired("error", error), + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Transformation = apply { + if (validated) { + return@apply + } + + error().validate() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = (error.asKnown().getOrNull()?.validity() ?: 0) + + class Error + private constructor( + private val reason: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("reason") + @ExcludeMissing + reason: JsonField = JsonMissing.of() + ) : this(reason, mutableMapOf()) + + /** + * Reason for the pre-transformation failure. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or + * is unexpectedly missing or null (e.g. if the server responded with an + * unexpected value). + */ + fun reason(): String = reason.getRequired("reason") + + /** + * Returns the raw JSON value of [reason]. + * + * Unlike [reason], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("reason") @ExcludeMissing fun _reason(): JsonField = reason + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Error]. + * + * The following fields are required: + * ```java + * .reason() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Error]. */ + class Builder internal constructor() { + + private var reason: JsonField? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(error: Error) = apply { + reason = error.reason + additionalProperties = error.additionalProperties.toMutableMap() + } + + /** Reason for the pre-transformation failure. */ + fun reason(reason: String) = reason(JsonField.of(reason)) + + /** + * Sets [Builder.reason] to an arbitrary JSON value. + * + * You should usually call [Builder.reason] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun reason(reason: JsonField) = apply { this.reason = reason } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Error]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .reason() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Error = + Error(checkRequired("reason", reason), additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Error = apply { + if (validated) { + return@apply + } + + reason() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = (if (reason.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Error && + reason == other.reason && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(reason, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Error{reason=$reason, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Transformation && + error == other.error && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(error, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Transformation{error=$error, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Data && + name == other.name && + path == other.path && + transformation == other.transformation && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(name, path, transformation, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Data{name=$name, path=$path, transformation=$transformation, additionalProperties=$additionalProperties}" + } + + class Request + private constructor( + private val transformation: JsonField, + private val xRequestId: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("transformation") + @ExcludeMissing + transformation: JsonField = JsonMissing.of(), + @JsonProperty("x_request_id") + @ExcludeMissing + xRequestId: JsonField = JsonMissing.of(), + ) : this(transformation, xRequestId, mutableMapOf()) + + /** + * The requested pre-transformation string. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun transformation(): String = transformation.getRequired("transformation") + + /** + * Unique identifier for the originating request. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun xRequestId(): String = xRequestId.getRequired("x_request_id") + + /** + * Returns the raw JSON value of [transformation]. + * + * Unlike [transformation], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("transformation") + @ExcludeMissing + fun _transformation(): JsonField = transformation + + /** + * Returns the raw JSON value of [xRequestId]. + * + * Unlike [xRequestId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("x_request_id") + @ExcludeMissing + fun _xRequestId(): JsonField = xRequestId + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Request]. + * + * The following fields are required: + * ```java + * .transformation() + * .xRequestId() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Request]. */ + class Builder internal constructor() { + + private var transformation: JsonField? = null + private var xRequestId: JsonField? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(request: Request) = apply { + transformation = request.transformation + xRequestId = request.xRequestId + additionalProperties = request.additionalProperties.toMutableMap() + } + + /** The requested pre-transformation string. */ + fun transformation(transformation: String) = + transformation(JsonField.of(transformation)) + + /** + * Sets [Builder.transformation] to an arbitrary JSON value. + * + * You should usually call [Builder.transformation] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun transformation(transformation: JsonField) = apply { + this.transformation = transformation + } + + /** Unique identifier for the originating request. */ + fun xRequestId(xRequestId: String) = xRequestId(JsonField.of(xRequestId)) + + /** + * Sets [Builder.xRequestId] to an arbitrary JSON value. + * + * You should usually call [Builder.xRequestId] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun xRequestId(xRequestId: JsonField) = apply { this.xRequestId = xRequestId } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Request]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .transformation() + * .xRequestId() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Request = + Request( + checkRequired("transformation", transformation), + checkRequired("xRequestId", xRequestId), + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Request = apply { + if (validated) { + return@apply + } + + transformation() + xRequestId() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (transformation.asKnown().isPresent) 1 else 0) + + (if (xRequestId.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Request && + transformation == other.transformation && + xRequestId == other.xRequestId && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(transformation, xRequestId, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Request{transformation=$transformation, xRequestId=$xRequestId, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is UploadPreTransformErrorEvent && + id == other.id && + type == other.type && + createdAt == other.createdAt && + data == other.data && + request == other.request && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(id, type, createdAt, data, request, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "UploadPreTransformErrorEvent{id=$id, type=$type, createdAt=$createdAt, data=$data, request=$request, additionalProperties=$additionalProperties}" +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/webhooks/UploadPreTransformSuccessEvent.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/webhooks/UploadPreTransformSuccessEvent.kt new file mode 100644 index 0000000..9c71f74 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/webhooks/UploadPreTransformSuccessEvent.kt @@ -0,0 +1,3221 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.webhooks + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.imagekit.api.core.Enum +import com.imagekit.api.core.ExcludeMissing +import com.imagekit.api.core.JsonField +import com.imagekit.api.core.JsonMissing +import com.imagekit.api.core.JsonValue +import com.imagekit.api.core.checkKnown +import com.imagekit.api.core.checkRequired +import com.imagekit.api.core.toImmutable +import com.imagekit.api.errors.ImageKitInvalidDataException +import com.imagekit.api.models.files.Metadata +import java.time.OffsetDateTime +import java.util.Collections +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** + * Triggered when a pre-transformation completes successfully. The file has been processed with the + * requested transformation and is now available in the Media Library. + */ +class UploadPreTransformSuccessEvent +private constructor( + private val id: JsonField, + private val type: JsonField, + private val createdAt: JsonField, + private val data: JsonField, + private val request: JsonField, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonField = JsonMissing.of(), + @JsonProperty("created_at") + @ExcludeMissing + createdAt: JsonField = JsonMissing.of(), + @JsonProperty("data") @ExcludeMissing data: JsonField = JsonMissing.of(), + @JsonProperty("request") @ExcludeMissing request: JsonField = JsonMissing.of(), + ) : this(id, type, createdAt, data, request, mutableMapOf()) + + fun toBaseWebhookEvent(): BaseWebhookEvent = + BaseWebhookEvent.builder().id(id).type(type).build() + + /** + * Unique identifier for the event. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun id(): String = id.getRequired("id") + + /** + * The type of webhook event. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun type(): String = type.getRequired("type") + + /** + * Timestamp of when the event occurred in ISO8601 format. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun createdAt(): OffsetDateTime = createdAt.getRequired("created_at") + + /** + * Object containing details of a successful upload. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun data(): Data = data.getRequired("data") + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun request(): Request = request.getRequired("request") + + /** + * Returns the raw JSON value of [id]. + * + * Unlike [id], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id + + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + + /** + * Returns the raw JSON value of [createdAt]. + * + * Unlike [createdAt], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("created_at") + @ExcludeMissing + fun _createdAt(): JsonField = createdAt + + /** + * Returns the raw JSON value of [data]. + * + * Unlike [data], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("data") @ExcludeMissing fun _data(): JsonField = data + + /** + * Returns the raw JSON value of [request]. + * + * Unlike [request], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("request") @ExcludeMissing fun _request(): JsonField = request + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [UploadPreTransformSuccessEvent]. + * + * The following fields are required: + * ```java + * .id() + * .type() + * .createdAt() + * .data() + * .request() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [UploadPreTransformSuccessEvent]. */ + class Builder internal constructor() { + + private var id: JsonField? = null + private var type: JsonField? = null + private var createdAt: JsonField? = null + private var data: JsonField? = null + private var request: JsonField? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(uploadPreTransformSuccessEvent: UploadPreTransformSuccessEvent) = apply { + id = uploadPreTransformSuccessEvent.id + type = uploadPreTransformSuccessEvent.type + createdAt = uploadPreTransformSuccessEvent.createdAt + data = uploadPreTransformSuccessEvent.data + request = uploadPreTransformSuccessEvent.request + additionalProperties = + uploadPreTransformSuccessEvent.additionalProperties.toMutableMap() + } + + /** Unique identifier for the event. */ + fun id(id: String) = id(JsonField.of(id)) + + /** + * Sets [Builder.id] to an arbitrary JSON value. + * + * You should usually call [Builder.id] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun id(id: JsonField) = apply { this.id = id } + + /** The type of webhook event. */ + fun type(type: String) = type(JsonField.of(type)) + + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun type(type: JsonField) = apply { this.type = type } + + /** Timestamp of when the event occurred in ISO8601 format. */ + fun createdAt(createdAt: OffsetDateTime) = createdAt(JsonField.of(createdAt)) + + /** + * Sets [Builder.createdAt] to an arbitrary JSON value. + * + * You should usually call [Builder.createdAt] with a well-typed [OffsetDateTime] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun createdAt(createdAt: JsonField) = apply { this.createdAt = createdAt } + + /** Object containing details of a successful upload. */ + fun data(data: Data) = data(JsonField.of(data)) + + /** + * Sets [Builder.data] to an arbitrary JSON value. + * + * You should usually call [Builder.data] with a well-typed [Data] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun data(data: JsonField) = apply { this.data = data } + + fun request(request: Request) = request(JsonField.of(request)) + + /** + * Sets [Builder.request] to an arbitrary JSON value. + * + * You should usually call [Builder.request] with a well-typed [Request] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun request(request: JsonField) = apply { this.request = request } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [UploadPreTransformSuccessEvent]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .id() + * .type() + * .createdAt() + * .data() + * .request() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): UploadPreTransformSuccessEvent = + UploadPreTransformSuccessEvent( + checkRequired("id", id), + checkRequired("type", type), + checkRequired("createdAt", createdAt), + checkRequired("data", data), + checkRequired("request", request), + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): UploadPreTransformSuccessEvent = apply { + if (validated) { + return@apply + } + + id() + type() + createdAt() + data().validate() + request().validate() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (id.asKnown().isPresent) 1 else 0) + + (if (type.asKnown().isPresent) 1 else 0) + + (if (createdAt.asKnown().isPresent) 1 else 0) + + (data.asKnown().getOrNull()?.validity() ?: 0) + + (request.asKnown().getOrNull()?.validity() ?: 0) + + /** Object containing details of a successful upload. */ + class Data + private constructor( + private val aiTags: JsonField>, + private val audioCodec: JsonField, + private val bitRate: JsonField, + private val customCoordinates: JsonField, + private val customMetadata: JsonField, + private val description: JsonField, + private val duration: JsonField, + private val embeddedMetadata: JsonField, + private val extensionStatus: JsonField, + private val fileId: JsonField, + private val filePath: JsonField, + private val fileType: JsonField, + private val height: JsonField, + private val isPrivateFile: JsonField, + private val isPublished: JsonField, + private val metadata: JsonField, + private val name: JsonField, + private val size: JsonField, + private val tags: JsonField>, + private val thumbnailUrl: JsonField, + private val url: JsonField, + private val versionInfo: JsonField, + private val videoCodec: JsonField, + private val width: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("AITags") + @ExcludeMissing + aiTags: JsonField> = JsonMissing.of(), + @JsonProperty("audioCodec") + @ExcludeMissing + audioCodec: JsonField = JsonMissing.of(), + @JsonProperty("bitRate") @ExcludeMissing bitRate: JsonField = JsonMissing.of(), + @JsonProperty("customCoordinates") + @ExcludeMissing + customCoordinates: JsonField = JsonMissing.of(), + @JsonProperty("customMetadata") + @ExcludeMissing + customMetadata: JsonField = JsonMissing.of(), + @JsonProperty("description") + @ExcludeMissing + description: JsonField = JsonMissing.of(), + @JsonProperty("duration") @ExcludeMissing duration: JsonField = JsonMissing.of(), + @JsonProperty("embeddedMetadata") + @ExcludeMissing + embeddedMetadata: JsonField = JsonMissing.of(), + @JsonProperty("extensionStatus") + @ExcludeMissing + extensionStatus: JsonField = JsonMissing.of(), + @JsonProperty("fileId") @ExcludeMissing fileId: JsonField = JsonMissing.of(), + @JsonProperty("filePath") + @ExcludeMissing + filePath: JsonField = JsonMissing.of(), + @JsonProperty("fileType") + @ExcludeMissing + fileType: JsonField = JsonMissing.of(), + @JsonProperty("height") @ExcludeMissing height: JsonField = JsonMissing.of(), + @JsonProperty("isPrivateFile") + @ExcludeMissing + isPrivateFile: JsonField = JsonMissing.of(), + @JsonProperty("isPublished") + @ExcludeMissing + isPublished: JsonField = JsonMissing.of(), + @JsonProperty("metadata") + @ExcludeMissing + metadata: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("size") @ExcludeMissing size: JsonField = JsonMissing.of(), + @JsonProperty("tags") @ExcludeMissing tags: JsonField> = JsonMissing.of(), + @JsonProperty("thumbnailUrl") + @ExcludeMissing + thumbnailUrl: JsonField = JsonMissing.of(), + @JsonProperty("url") @ExcludeMissing url: JsonField = JsonMissing.of(), + @JsonProperty("versionInfo") + @ExcludeMissing + versionInfo: JsonField = JsonMissing.of(), + @JsonProperty("videoCodec") + @ExcludeMissing + videoCodec: JsonField = JsonMissing.of(), + @JsonProperty("width") @ExcludeMissing width: JsonField = JsonMissing.of(), + ) : this( + aiTags, + audioCodec, + bitRate, + customCoordinates, + customMetadata, + description, + duration, + embeddedMetadata, + extensionStatus, + fileId, + filePath, + fileType, + height, + isPrivateFile, + isPublished, + metadata, + name, + size, + tags, + thumbnailUrl, + url, + versionInfo, + videoCodec, + width, + mutableMapOf(), + ) + + /** + * An array of tags assigned to the uploaded file by auto tagging. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun aiTags(): Optional> = aiTags.getOptional("AITags") + + /** + * The audio codec used in the video (only for video). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun audioCodec(): Optional = audioCodec.getOptional("audioCodec") + + /** + * The bit rate of the video in kbps (only for video). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun bitRate(): Optional = bitRate.getOptional("bitRate") + + /** + * Value of custom coordinates associated with the image in the format `x,y,width,height`. + * If `customCoordinates` are not defined, then it is `null`. Send `customCoordinates` in + * `responseFields` in API request to get the value of this field. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun customCoordinates(): Optional = + customCoordinates.getOptional("customCoordinates") + + /** + * A key-value data associated with the asset. Use `responseField` in API request to get + * `customMetadata` in the upload API response. Before setting any custom metadata on an + * asset, you have to create the field using custom metadata fields API. Send + * `customMetadata` in `responseFields` in API request to get the value of this field. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun customMetadata(): Optional = + customMetadata.getOptional("customMetadata") + + /** + * Optional text to describe the contents of the file. Can be set by the user or the + * ai-auto-description extension. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun description(): Optional = description.getOptional("description") + + /** + * The duration of the video in seconds (only for video). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun duration(): Optional = duration.getOptional("duration") + + /** + * Consolidated embedded metadata associated with the file. It includes exif, iptc, and xmp + * data. Send `embeddedMetadata` in `responseFields` in API request to get embeddedMetadata + * in the upload API response. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun embeddedMetadata(): Optional = + embeddedMetadata.getOptional("embeddedMetadata") + + /** + * Extension names with their processing status at the time of completion of the request. It + * could have one of the following status values: + * + * `success`: The extension has been successfully applied. `failed`: The extension has + * failed and will not be retried. `pending`: The extension will finish processing in some + * time. On completion, the final status (success / failed) will be sent to the `webhookUrl` + * provided. + * + * If no extension was requested, then this parameter is not returned. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun extensionStatus(): Optional = + extensionStatus.getOptional("extensionStatus") + + /** + * Unique fileId. Store this fileld in your database, as this will be used to perform update + * action on this file. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun fileId(): Optional = fileId.getOptional("fileId") + + /** + * The relative path of the file in the media library e.g. + * `/marketing-assets/new-banner.jpg`. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun filePath(): Optional = filePath.getOptional("filePath") + + /** + * Type of the uploaded file. Possible values are `image`, `non-image`. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun fileType(): Optional = fileType.getOptional("fileType") + + /** + * Height of the image in pixels (Only for images) + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun height(): Optional = height.getOptional("height") + + /** + * Is the file marked as private. It can be either `true` or `false`. Send `isPrivateFile` + * in `responseFields` in API request to get the value of this field. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun isPrivateFile(): Optional = isPrivateFile.getOptional("isPrivateFile") + + /** + * Is the file published or in draft state. It can be either `true` or `false`. Send + * `isPublished` in `responseFields` in API request to get the value of this field. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun isPublished(): Optional = isPublished.getOptional("isPublished") + + /** + * Legacy metadata. Send `metadata` in `responseFields` in API request to get metadata in + * the upload API response. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun metadata(): Optional = metadata.getOptional("metadata") + + /** + * Name of the asset. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun name(): Optional = name.getOptional("name") + + /** + * Size of the image file in Bytes. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun size(): Optional = size.getOptional("size") + + /** + * The array of tags associated with the asset. If no tags are set, it will be `null`. Send + * `tags` in `responseFields` in API request to get the value of this field. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun tags(): Optional> = tags.getOptional("tags") + + /** + * In the case of an image, a small thumbnail URL. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun thumbnailUrl(): Optional = thumbnailUrl.getOptional("thumbnailUrl") + + /** + * A publicly accessible URL of the file. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun url(): Optional = url.getOptional("url") + + /** + * An object containing the file or file version's `id` (versionId) and `name`. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun versionInfo(): Optional = versionInfo.getOptional("versionInfo") + + /** + * The video codec used in the video (only for video). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun videoCodec(): Optional = videoCodec.getOptional("videoCodec") + + /** + * Width of the image in pixels (Only for Images) + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun width(): Optional = width.getOptional("width") + + /** + * Returns the raw JSON value of [aiTags]. + * + * Unlike [aiTags], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("AITags") @ExcludeMissing fun _aiTags(): JsonField> = aiTags + + /** + * Returns the raw JSON value of [audioCodec]. + * + * Unlike [audioCodec], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("audioCodec") + @ExcludeMissing + fun _audioCodec(): JsonField = audioCodec + + /** + * Returns the raw JSON value of [bitRate]. + * + * Unlike [bitRate], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("bitRate") @ExcludeMissing fun _bitRate(): JsonField = bitRate + + /** + * Returns the raw JSON value of [customCoordinates]. + * + * Unlike [customCoordinates], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("customCoordinates") + @ExcludeMissing + fun _customCoordinates(): JsonField = customCoordinates + + /** + * Returns the raw JSON value of [customMetadata]. + * + * Unlike [customMetadata], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("customMetadata") + @ExcludeMissing + fun _customMetadata(): JsonField = customMetadata + + /** + * Returns the raw JSON value of [description]. + * + * Unlike [description], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("description") + @ExcludeMissing + fun _description(): JsonField = description + + /** + * Returns the raw JSON value of [duration]. + * + * Unlike [duration], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("duration") @ExcludeMissing fun _duration(): JsonField = duration + + /** + * Returns the raw JSON value of [embeddedMetadata]. + * + * Unlike [embeddedMetadata], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("embeddedMetadata") + @ExcludeMissing + fun _embeddedMetadata(): JsonField = embeddedMetadata + + /** + * Returns the raw JSON value of [extensionStatus]. + * + * Unlike [extensionStatus], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("extensionStatus") + @ExcludeMissing + fun _extensionStatus(): JsonField = extensionStatus + + /** + * Returns the raw JSON value of [fileId]. + * + * Unlike [fileId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("fileId") @ExcludeMissing fun _fileId(): JsonField = fileId + + /** + * Returns the raw JSON value of [filePath]. + * + * Unlike [filePath], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("filePath") @ExcludeMissing fun _filePath(): JsonField = filePath + + /** + * Returns the raw JSON value of [fileType]. + * + * Unlike [fileType], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("fileType") @ExcludeMissing fun _fileType(): JsonField = fileType + + /** + * Returns the raw JSON value of [height]. + * + * Unlike [height], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("height") @ExcludeMissing fun _height(): JsonField = height + + /** + * Returns the raw JSON value of [isPrivateFile]. + * + * Unlike [isPrivateFile], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("isPrivateFile") + @ExcludeMissing + fun _isPrivateFile(): JsonField = isPrivateFile + + /** + * Returns the raw JSON value of [isPublished]. + * + * Unlike [isPublished], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("isPublished") + @ExcludeMissing + fun _isPublished(): JsonField = isPublished + + /** + * Returns the raw JSON value of [metadata]. + * + * Unlike [metadata], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("metadata") @ExcludeMissing fun _metadata(): JsonField = metadata + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + + /** + * Returns the raw JSON value of [size]. + * + * Unlike [size], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("size") @ExcludeMissing fun _size(): JsonField = size + + /** + * Returns the raw JSON value of [tags]. + * + * Unlike [tags], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("tags") @ExcludeMissing fun _tags(): JsonField> = tags + + /** + * Returns the raw JSON value of [thumbnailUrl]. + * + * Unlike [thumbnailUrl], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("thumbnailUrl") + @ExcludeMissing + fun _thumbnailUrl(): JsonField = thumbnailUrl + + /** + * Returns the raw JSON value of [url]. + * + * Unlike [url], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("url") @ExcludeMissing fun _url(): JsonField = url + + /** + * Returns the raw JSON value of [versionInfo]. + * + * Unlike [versionInfo], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("versionInfo") + @ExcludeMissing + fun _versionInfo(): JsonField = versionInfo + + /** + * Returns the raw JSON value of [videoCodec]. + * + * Unlike [videoCodec], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("videoCodec") + @ExcludeMissing + fun _videoCodec(): JsonField = videoCodec + + /** + * Returns the raw JSON value of [width]. + * + * Unlike [width], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("width") @ExcludeMissing fun _width(): JsonField = width + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Data]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Data]. */ + class Builder internal constructor() { + + private var aiTags: JsonField>? = null + private var audioCodec: JsonField = JsonMissing.of() + private var bitRate: JsonField = JsonMissing.of() + private var customCoordinates: JsonField = JsonMissing.of() + private var customMetadata: JsonField = JsonMissing.of() + private var description: JsonField = JsonMissing.of() + private var duration: JsonField = JsonMissing.of() + private var embeddedMetadata: JsonField = JsonMissing.of() + private var extensionStatus: JsonField = JsonMissing.of() + private var fileId: JsonField = JsonMissing.of() + private var filePath: JsonField = JsonMissing.of() + private var fileType: JsonField = JsonMissing.of() + private var height: JsonField = JsonMissing.of() + private var isPrivateFile: JsonField = JsonMissing.of() + private var isPublished: JsonField = JsonMissing.of() + private var metadata: JsonField = JsonMissing.of() + private var name: JsonField = JsonMissing.of() + private var size: JsonField = JsonMissing.of() + private var tags: JsonField>? = null + private var thumbnailUrl: JsonField = JsonMissing.of() + private var url: JsonField = JsonMissing.of() + private var versionInfo: JsonField = JsonMissing.of() + private var videoCodec: JsonField = JsonMissing.of() + private var width: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(data: Data) = apply { + aiTags = data.aiTags.map { it.toMutableList() } + audioCodec = data.audioCodec + bitRate = data.bitRate + customCoordinates = data.customCoordinates + customMetadata = data.customMetadata + description = data.description + duration = data.duration + embeddedMetadata = data.embeddedMetadata + extensionStatus = data.extensionStatus + fileId = data.fileId + filePath = data.filePath + fileType = data.fileType + height = data.height + isPrivateFile = data.isPrivateFile + isPublished = data.isPublished + metadata = data.metadata + name = data.name + size = data.size + tags = data.tags.map { it.toMutableList() } + thumbnailUrl = data.thumbnailUrl + url = data.url + versionInfo = data.versionInfo + videoCodec = data.videoCodec + width = data.width + additionalProperties = data.additionalProperties.toMutableMap() + } + + /** An array of tags assigned to the uploaded file by auto tagging. */ + fun aiTags(aiTags: List?) = aiTags(JsonField.ofNullable(aiTags)) + + /** Alias for calling [Builder.aiTags] with `aiTags.orElse(null)`. */ + fun aiTags(aiTags: Optional>) = aiTags(aiTags.getOrNull()) + + /** + * Sets [Builder.aiTags] to an arbitrary JSON value. + * + * You should usually call [Builder.aiTags] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun aiTags(aiTags: JsonField>) = apply { + this.aiTags = aiTags.map { it.toMutableList() } + } + + /** + * Adds a single [AiTag] to [aiTags]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addAiTag(aiTag: AiTag) = apply { + aiTags = + (aiTags ?: JsonField.of(mutableListOf())).also { + checkKnown("aiTags", it).add(aiTag) + } + } + + /** The audio codec used in the video (only for video). */ + fun audioCodec(audioCodec: String) = audioCodec(JsonField.of(audioCodec)) + + /** + * Sets [Builder.audioCodec] to an arbitrary JSON value. + * + * You should usually call [Builder.audioCodec] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun audioCodec(audioCodec: JsonField) = apply { this.audioCodec = audioCodec } + + /** The bit rate of the video in kbps (only for video). */ + fun bitRate(bitRate: Long) = bitRate(JsonField.of(bitRate)) + + /** + * Sets [Builder.bitRate] to an arbitrary JSON value. + * + * You should usually call [Builder.bitRate] with a well-typed [Long] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun bitRate(bitRate: JsonField) = apply { this.bitRate = bitRate } + + /** + * Value of custom coordinates associated with the image in the format + * `x,y,width,height`. If `customCoordinates` are not defined, then it is `null`. Send + * `customCoordinates` in `responseFields` in API request to get the value of this + * field. + */ + fun customCoordinates(customCoordinates: String?) = + customCoordinates(JsonField.ofNullable(customCoordinates)) + + /** + * Alias for calling [Builder.customCoordinates] with `customCoordinates.orElse(null)`. + */ + fun customCoordinates(customCoordinates: Optional) = + customCoordinates(customCoordinates.getOrNull()) + + /** + * Sets [Builder.customCoordinates] to an arbitrary JSON value. + * + * You should usually call [Builder.customCoordinates] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun customCoordinates(customCoordinates: JsonField) = apply { + this.customCoordinates = customCoordinates + } + + /** + * A key-value data associated with the asset. Use `responseField` in API request to get + * `customMetadata` in the upload API response. Before setting any custom metadata on an + * asset, you have to create the field using custom metadata fields API. Send + * `customMetadata` in `responseFields` in API request to get the value of this field. + */ + fun customMetadata(customMetadata: CustomMetadata) = + customMetadata(JsonField.of(customMetadata)) + + /** + * Sets [Builder.customMetadata] to an arbitrary JSON value. + * + * You should usually call [Builder.customMetadata] with a well-typed [CustomMetadata] + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun customMetadata(customMetadata: JsonField) = apply { + this.customMetadata = customMetadata + } + + /** + * Optional text to describe the contents of the file. Can be set by the user or the + * ai-auto-description extension. + */ + fun description(description: String) = description(JsonField.of(description)) + + /** + * Sets [Builder.description] to an arbitrary JSON value. + * + * You should usually call [Builder.description] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun description(description: JsonField) = apply { + this.description = description + } + + /** The duration of the video in seconds (only for video). */ + fun duration(duration: Long) = duration(JsonField.of(duration)) + + /** + * Sets [Builder.duration] to an arbitrary JSON value. + * + * You should usually call [Builder.duration] with a well-typed [Long] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun duration(duration: JsonField) = apply { this.duration = duration } + + /** + * Consolidated embedded metadata associated with the file. It includes exif, iptc, and + * xmp data. Send `embeddedMetadata` in `responseFields` in API request to get + * embeddedMetadata in the upload API response. + */ + fun embeddedMetadata(embeddedMetadata: EmbeddedMetadata) = + embeddedMetadata(JsonField.of(embeddedMetadata)) + + /** + * Sets [Builder.embeddedMetadata] to an arbitrary JSON value. + * + * You should usually call [Builder.embeddedMetadata] with a well-typed + * [EmbeddedMetadata] value instead. This method is primarily for setting the field to + * an undocumented or not yet supported value. + */ + fun embeddedMetadata(embeddedMetadata: JsonField) = apply { + this.embeddedMetadata = embeddedMetadata + } + + /** + * Extension names with their processing status at the time of completion of the + * request. It could have one of the following status values: + * + * `success`: The extension has been successfully applied. `failed`: The extension has + * failed and will not be retried. `pending`: The extension will finish processing in + * some time. On completion, the final status (success / failed) will be sent to the + * `webhookUrl` provided. + * + * If no extension was requested, then this parameter is not returned. + */ + fun extensionStatus(extensionStatus: ExtensionStatus) = + extensionStatus(JsonField.of(extensionStatus)) + + /** + * Sets [Builder.extensionStatus] to an arbitrary JSON value. + * + * You should usually call [Builder.extensionStatus] with a well-typed [ExtensionStatus] + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun extensionStatus(extensionStatus: JsonField) = apply { + this.extensionStatus = extensionStatus + } + + /** + * Unique fileId. Store this fileld in your database, as this will be used to perform + * update action on this file. + */ + fun fileId(fileId: String) = fileId(JsonField.of(fileId)) + + /** + * Sets [Builder.fileId] to an arbitrary JSON value. + * + * You should usually call [Builder.fileId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun fileId(fileId: JsonField) = apply { this.fileId = fileId } + + /** + * The relative path of the file in the media library e.g. + * `/marketing-assets/new-banner.jpg`. + */ + fun filePath(filePath: String) = filePath(JsonField.of(filePath)) + + /** + * Sets [Builder.filePath] to an arbitrary JSON value. + * + * You should usually call [Builder.filePath] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun filePath(filePath: JsonField) = apply { this.filePath = filePath } + + /** Type of the uploaded file. Possible values are `image`, `non-image`. */ + fun fileType(fileType: String) = fileType(JsonField.of(fileType)) + + /** + * Sets [Builder.fileType] to an arbitrary JSON value. + * + * You should usually call [Builder.fileType] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun fileType(fileType: JsonField) = apply { this.fileType = fileType } + + /** Height of the image in pixels (Only for images) */ + fun height(height: Double) = height(JsonField.of(height)) + + /** + * Sets [Builder.height] to an arbitrary JSON value. + * + * You should usually call [Builder.height] with a well-typed [Double] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun height(height: JsonField) = apply { this.height = height } + + /** + * Is the file marked as private. It can be either `true` or `false`. Send + * `isPrivateFile` in `responseFields` in API request to get the value of this field. + */ + fun isPrivateFile(isPrivateFile: Boolean) = isPrivateFile(JsonField.of(isPrivateFile)) + + /** + * Sets [Builder.isPrivateFile] to an arbitrary JSON value. + * + * You should usually call [Builder.isPrivateFile] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun isPrivateFile(isPrivateFile: JsonField) = apply { + this.isPrivateFile = isPrivateFile + } + + /** + * Is the file published or in draft state. It can be either `true` or `false`. Send + * `isPublished` in `responseFields` in API request to get the value of this field. + */ + fun isPublished(isPublished: Boolean) = isPublished(JsonField.of(isPublished)) + + /** + * Sets [Builder.isPublished] to an arbitrary JSON value. + * + * You should usually call [Builder.isPublished] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun isPublished(isPublished: JsonField) = apply { + this.isPublished = isPublished + } + + /** + * Legacy metadata. Send `metadata` in `responseFields` in API request to get metadata + * in the upload API response. + */ + fun metadata(metadata: Metadata) = metadata(JsonField.of(metadata)) + + /** + * Sets [Builder.metadata] to an arbitrary JSON value. + * + * You should usually call [Builder.metadata] with a well-typed [Metadata] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun metadata(metadata: JsonField) = apply { this.metadata = metadata } + + /** Name of the asset. */ + fun name(name: String) = name(JsonField.of(name)) + + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun name(name: JsonField) = apply { this.name = name } + + /** Size of the image file in Bytes. */ + fun size(size: Double) = size(JsonField.of(size)) + + /** + * Sets [Builder.size] to an arbitrary JSON value. + * + * You should usually call [Builder.size] with a well-typed [Double] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun size(size: JsonField) = apply { this.size = size } + + /** + * The array of tags associated with the asset. If no tags are set, it will be `null`. + * Send `tags` in `responseFields` in API request to get the value of this field. + */ + fun tags(tags: List?) = tags(JsonField.ofNullable(tags)) + + /** Alias for calling [Builder.tags] with `tags.orElse(null)`. */ + fun tags(tags: Optional>) = tags(tags.getOrNull()) + + /** + * Sets [Builder.tags] to an arbitrary JSON value. + * + * You should usually call [Builder.tags] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun tags(tags: JsonField>) = apply { + this.tags = tags.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [tags]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addTag(tag: String) = apply { + tags = + (tags ?: JsonField.of(mutableListOf())).also { checkKnown("tags", it).add(tag) } + } + + /** In the case of an image, a small thumbnail URL. */ + fun thumbnailUrl(thumbnailUrl: String) = thumbnailUrl(JsonField.of(thumbnailUrl)) + + /** + * Sets [Builder.thumbnailUrl] to an arbitrary JSON value. + * + * You should usually call [Builder.thumbnailUrl] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun thumbnailUrl(thumbnailUrl: JsonField) = apply { + this.thumbnailUrl = thumbnailUrl + } + + /** A publicly accessible URL of the file. */ + fun url(url: String) = url(JsonField.of(url)) + + /** + * Sets [Builder.url] to an arbitrary JSON value. + * + * You should usually call [Builder.url] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun url(url: JsonField) = apply { this.url = url } + + /** An object containing the file or file version's `id` (versionId) and `name`. */ + fun versionInfo(versionInfo: VersionInfo) = versionInfo(JsonField.of(versionInfo)) + + /** + * Sets [Builder.versionInfo] to an arbitrary JSON value. + * + * You should usually call [Builder.versionInfo] with a well-typed [VersionInfo] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun versionInfo(versionInfo: JsonField) = apply { + this.versionInfo = versionInfo + } + + /** The video codec used in the video (only for video). */ + fun videoCodec(videoCodec: String) = videoCodec(JsonField.of(videoCodec)) + + /** + * Sets [Builder.videoCodec] to an arbitrary JSON value. + * + * You should usually call [Builder.videoCodec] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun videoCodec(videoCodec: JsonField) = apply { this.videoCodec = videoCodec } + + /** Width of the image in pixels (Only for Images) */ + fun width(width: Double) = width(JsonField.of(width)) + + /** + * Sets [Builder.width] to an arbitrary JSON value. + * + * You should usually call [Builder.width] with a well-typed [Double] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun width(width: JsonField) = apply { this.width = width } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Data]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Data = + Data( + (aiTags ?: JsonMissing.of()).map { it.toImmutable() }, + audioCodec, + bitRate, + customCoordinates, + customMetadata, + description, + duration, + embeddedMetadata, + extensionStatus, + fileId, + filePath, + fileType, + height, + isPrivateFile, + isPublished, + metadata, + name, + size, + (tags ?: JsonMissing.of()).map { it.toImmutable() }, + thumbnailUrl, + url, + versionInfo, + videoCodec, + width, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Data = apply { + if (validated) { + return@apply + } + + aiTags().ifPresent { it.forEach { it.validate() } } + audioCodec() + bitRate() + customCoordinates() + customMetadata().ifPresent { it.validate() } + description() + duration() + embeddedMetadata().ifPresent { it.validate() } + extensionStatus().ifPresent { it.validate() } + fileId() + filePath() + fileType() + height() + isPrivateFile() + isPublished() + metadata().ifPresent { it.validate() } + name() + size() + tags() + thumbnailUrl() + url() + versionInfo().ifPresent { it.validate() } + videoCodec() + width() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (aiTags.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + (if (audioCodec.asKnown().isPresent) 1 else 0) + + (if (bitRate.asKnown().isPresent) 1 else 0) + + (if (customCoordinates.asKnown().isPresent) 1 else 0) + + (customMetadata.asKnown().getOrNull()?.validity() ?: 0) + + (if (description.asKnown().isPresent) 1 else 0) + + (if (duration.asKnown().isPresent) 1 else 0) + + (embeddedMetadata.asKnown().getOrNull()?.validity() ?: 0) + + (extensionStatus.asKnown().getOrNull()?.validity() ?: 0) + + (if (fileId.asKnown().isPresent) 1 else 0) + + (if (filePath.asKnown().isPresent) 1 else 0) + + (if (fileType.asKnown().isPresent) 1 else 0) + + (if (height.asKnown().isPresent) 1 else 0) + + (if (isPrivateFile.asKnown().isPresent) 1 else 0) + + (if (isPublished.asKnown().isPresent) 1 else 0) + + (metadata.asKnown().getOrNull()?.validity() ?: 0) + + (if (name.asKnown().isPresent) 1 else 0) + + (if (size.asKnown().isPresent) 1 else 0) + + (tags.asKnown().getOrNull()?.size ?: 0) + + (if (thumbnailUrl.asKnown().isPresent) 1 else 0) + + (if (url.asKnown().isPresent) 1 else 0) + + (versionInfo.asKnown().getOrNull()?.validity() ?: 0) + + (if (videoCodec.asKnown().isPresent) 1 else 0) + + (if (width.asKnown().isPresent) 1 else 0) + + class AiTag + private constructor( + private val confidence: JsonField, + private val name: JsonField, + private val source: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("confidence") + @ExcludeMissing + confidence: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("source") @ExcludeMissing source: JsonField = JsonMissing.of(), + ) : this(confidence, name, source, mutableMapOf()) + + /** + * Confidence score of the tag. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun confidence(): Optional = confidence.getOptional("confidence") + + /** + * Name of the tag. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun name(): Optional = name.getOptional("name") + + /** + * Array of `AITags` associated with the image. If no `AITags` are set, it will be null. + * These tags can be added using the `google-auto-tagging` or `aws-auto-tagging` + * extensions. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun source(): Optional = source.getOptional("source") + + /** + * Returns the raw JSON value of [confidence]. + * + * Unlike [confidence], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("confidence") + @ExcludeMissing + fun _confidence(): JsonField = confidence + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + + /** + * Returns the raw JSON value of [source]. + * + * Unlike [source], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("source") @ExcludeMissing fun _source(): JsonField = source + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [AiTag]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [AiTag]. */ + class Builder internal constructor() { + + private var confidence: JsonField = JsonMissing.of() + private var name: JsonField = JsonMissing.of() + private var source: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(aiTag: AiTag) = apply { + confidence = aiTag.confidence + name = aiTag.name + source = aiTag.source + additionalProperties = aiTag.additionalProperties.toMutableMap() + } + + /** Confidence score of the tag. */ + fun confidence(confidence: Double) = confidence(JsonField.of(confidence)) + + /** + * Sets [Builder.confidence] to an arbitrary JSON value. + * + * You should usually call [Builder.confidence] with a well-typed [Double] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun confidence(confidence: JsonField) = apply { + this.confidence = confidence + } + + /** Name of the tag. */ + fun name(name: String) = name(JsonField.of(name)) + + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun name(name: JsonField) = apply { this.name = name } + + /** + * Array of `AITags` associated with the image. If no `AITags` are set, it will be + * null. These tags can be added using the `google-auto-tagging` or + * `aws-auto-tagging` extensions. + */ + fun source(source: String) = source(JsonField.of(source)) + + /** + * Sets [Builder.source] to an arbitrary JSON value. + * + * You should usually call [Builder.source] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun source(source: JsonField) = apply { this.source = source } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [AiTag]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): AiTag = + AiTag(confidence, name, source, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): AiTag = apply { + if (validated) { + return@apply + } + + confidence() + name() + source() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (confidence.asKnown().isPresent) 1 else 0) + + (if (name.asKnown().isPresent) 1 else 0) + + (if (source.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is AiTag && + confidence == other.confidence && + name == other.name && + source == other.source && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(confidence, name, source, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "AiTag{confidence=$confidence, name=$name, source=$source, additionalProperties=$additionalProperties}" + } + + /** + * A key-value data associated with the asset. Use `responseField` in API request to get + * `customMetadata` in the upload API response. Before setting any custom metadata on an + * asset, you have to create the field using custom metadata fields API. Send + * `customMetadata` in `responseFields` in API request to get the value of this field. + */ + class CustomMetadata + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [CustomMetadata]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [CustomMetadata]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(customMetadata: CustomMetadata) = apply { + additionalProperties = customMetadata.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [CustomMetadata]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): CustomMetadata = CustomMetadata(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): CustomMetadata = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is CustomMetadata && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "CustomMetadata{additionalProperties=$additionalProperties}" + } + + /** + * Consolidated embedded metadata associated with the file. It includes exif, iptc, and xmp + * data. Send `embeddedMetadata` in `responseFields` in API request to get embeddedMetadata + * in the upload API response. + */ + class EmbeddedMetadata + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [EmbeddedMetadata]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [EmbeddedMetadata]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(embeddedMetadata: EmbeddedMetadata) = apply { + additionalProperties = embeddedMetadata.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [EmbeddedMetadata]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): EmbeddedMetadata = EmbeddedMetadata(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): EmbeddedMetadata = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is EmbeddedMetadata && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "EmbeddedMetadata{additionalProperties=$additionalProperties}" + } + + /** + * Extension names with their processing status at the time of completion of the request. It + * could have one of the following status values: + * + * `success`: The extension has been successfully applied. `failed`: The extension has + * failed and will not be retried. `pending`: The extension will finish processing in some + * time. On completion, the final status (success / failed) will be sent to the `webhookUrl` + * provided. + * + * If no extension was requested, then this parameter is not returned. + */ + class ExtensionStatus + private constructor( + private val aiAutoDescription: JsonField, + private val awsAutoTagging: JsonField, + private val googleAutoTagging: JsonField, + private val removeBg: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("ai-auto-description") + @ExcludeMissing + aiAutoDescription: JsonField = JsonMissing.of(), + @JsonProperty("aws-auto-tagging") + @ExcludeMissing + awsAutoTagging: JsonField = JsonMissing.of(), + @JsonProperty("google-auto-tagging") + @ExcludeMissing + googleAutoTagging: JsonField = JsonMissing.of(), + @JsonProperty("remove-bg") + @ExcludeMissing + removeBg: JsonField = JsonMissing.of(), + ) : this(aiAutoDescription, awsAutoTagging, googleAutoTagging, removeBg, mutableMapOf()) + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun aiAutoDescription(): Optional = + aiAutoDescription.getOptional("ai-auto-description") + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun awsAutoTagging(): Optional = + awsAutoTagging.getOptional("aws-auto-tagging") + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun googleAutoTagging(): Optional = + googleAutoTagging.getOptional("google-auto-tagging") + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun removeBg(): Optional = removeBg.getOptional("remove-bg") + + /** + * Returns the raw JSON value of [aiAutoDescription]. + * + * Unlike [aiAutoDescription], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("ai-auto-description") + @ExcludeMissing + fun _aiAutoDescription(): JsonField = aiAutoDescription + + /** + * Returns the raw JSON value of [awsAutoTagging]. + * + * Unlike [awsAutoTagging], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("aws-auto-tagging") + @ExcludeMissing + fun _awsAutoTagging(): JsonField = awsAutoTagging + + /** + * Returns the raw JSON value of [googleAutoTagging]. + * + * Unlike [googleAutoTagging], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("google-auto-tagging") + @ExcludeMissing + fun _googleAutoTagging(): JsonField = googleAutoTagging + + /** + * Returns the raw JSON value of [removeBg]. + * + * Unlike [removeBg], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("remove-bg") + @ExcludeMissing + fun _removeBg(): JsonField = removeBg + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [ExtensionStatus]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ExtensionStatus]. */ + class Builder internal constructor() { + + private var aiAutoDescription: JsonField = JsonMissing.of() + private var awsAutoTagging: JsonField = JsonMissing.of() + private var googleAutoTagging: JsonField = JsonMissing.of() + private var removeBg: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(extensionStatus: ExtensionStatus) = apply { + aiAutoDescription = extensionStatus.aiAutoDescription + awsAutoTagging = extensionStatus.awsAutoTagging + googleAutoTagging = extensionStatus.googleAutoTagging + removeBg = extensionStatus.removeBg + additionalProperties = extensionStatus.additionalProperties.toMutableMap() + } + + fun aiAutoDescription(aiAutoDescription: AiAutoDescription) = + aiAutoDescription(JsonField.of(aiAutoDescription)) + + /** + * Sets [Builder.aiAutoDescription] to an arbitrary JSON value. + * + * You should usually call [Builder.aiAutoDescription] with a well-typed + * [AiAutoDescription] value instead. This method is primarily for setting the field + * to an undocumented or not yet supported value. + */ + fun aiAutoDescription(aiAutoDescription: JsonField) = apply { + this.aiAutoDescription = aiAutoDescription + } + + fun awsAutoTagging(awsAutoTagging: AwsAutoTagging) = + awsAutoTagging(JsonField.of(awsAutoTagging)) + + /** + * Sets [Builder.awsAutoTagging] to an arbitrary JSON value. + * + * You should usually call [Builder.awsAutoTagging] with a well-typed + * [AwsAutoTagging] value instead. This method is primarily for setting the field to + * an undocumented or not yet supported value. + */ + fun awsAutoTagging(awsAutoTagging: JsonField) = apply { + this.awsAutoTagging = awsAutoTagging + } + + fun googleAutoTagging(googleAutoTagging: GoogleAutoTagging) = + googleAutoTagging(JsonField.of(googleAutoTagging)) + + /** + * Sets [Builder.googleAutoTagging] to an arbitrary JSON value. + * + * You should usually call [Builder.googleAutoTagging] with a well-typed + * [GoogleAutoTagging] value instead. This method is primarily for setting the field + * to an undocumented or not yet supported value. + */ + fun googleAutoTagging(googleAutoTagging: JsonField) = apply { + this.googleAutoTagging = googleAutoTagging + } + + fun removeBg(removeBg: RemoveBg) = removeBg(JsonField.of(removeBg)) + + /** + * Sets [Builder.removeBg] to an arbitrary JSON value. + * + * You should usually call [Builder.removeBg] with a well-typed [RemoveBg] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun removeBg(removeBg: JsonField) = apply { this.removeBg = removeBg } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ExtensionStatus]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): ExtensionStatus = + ExtensionStatus( + aiAutoDescription, + awsAutoTagging, + googleAutoTagging, + removeBg, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): ExtensionStatus = apply { + if (validated) { + return@apply + } + + aiAutoDescription().ifPresent { it.validate() } + awsAutoTagging().ifPresent { it.validate() } + googleAutoTagging().ifPresent { it.validate() } + removeBg().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (aiAutoDescription.asKnown().getOrNull()?.validity() ?: 0) + + (awsAutoTagging.asKnown().getOrNull()?.validity() ?: 0) + + (googleAutoTagging.asKnown().getOrNull()?.validity() ?: 0) + + (removeBg.asKnown().getOrNull()?.validity() ?: 0) + + class AiAutoDescription + @JsonCreator + private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that + * doesn't match any known member, and you want to know that value. For example, if + * the SDK is on an older version than the API, then the API may respond with new + * members that the SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val SUCCESS = of("success") + + @JvmField val PENDING = of("pending") + + @JvmField val FAILED = of("failed") + + @JvmStatic fun of(value: String) = AiAutoDescription(JsonField.of(value)) + } + + /** An enum containing [AiAutoDescription]'s known values. */ + enum class Known { + SUCCESS, + PENDING, + FAILED, + } + + /** + * An enum containing [AiAutoDescription]'s known values, as well as an [_UNKNOWN] + * member. + * + * An instance of [AiAutoDescription] can contain an unknown value in a couple of + * cases: + * - It was deserialized from data that doesn't match any known member. For example, + * if the SDK is on an older version than the API, then the API may respond with + * new members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + SUCCESS, + PENDING, + FAILED, + /** + * An enum member indicating that [AiAutoDescription] was instantiated with an + * unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if + * you want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + SUCCESS -> Value.SUCCESS + PENDING -> Value.PENDING + FAILED -> Value.FAILED + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and + * don't want to throw for the unknown case. + * + * @throws ImageKitInvalidDataException if this class instance's value is a not a + * known member. + */ + fun known(): Known = + when (this) { + SUCCESS -> Known.SUCCESS + PENDING -> Known.PENDING + FAILED -> Known.FAILED + else -> + throw ImageKitInvalidDataException("Unknown AiAutoDescription: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for + * debugging and generally doesn't throw. + * + * @throws ImageKitInvalidDataException if this class instance's value does not have + * the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + ImageKitInvalidDataException("Value is not a String") + } + + private var validated: Boolean = false + + fun validate(): AiAutoDescription = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is AiAutoDescription && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + class AwsAutoTagging + @JsonCreator + private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that + * doesn't match any known member, and you want to know that value. For example, if + * the SDK is on an older version than the API, then the API may respond with new + * members that the SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val SUCCESS = of("success") + + @JvmField val PENDING = of("pending") + + @JvmField val FAILED = of("failed") + + @JvmStatic fun of(value: String) = AwsAutoTagging(JsonField.of(value)) + } + + /** An enum containing [AwsAutoTagging]'s known values. */ + enum class Known { + SUCCESS, + PENDING, + FAILED, + } + + /** + * An enum containing [AwsAutoTagging]'s known values, as well as an [_UNKNOWN] + * member. + * + * An instance of [AwsAutoTagging] can contain an unknown value in a couple of + * cases: + * - It was deserialized from data that doesn't match any known member. For example, + * if the SDK is on an older version than the API, then the API may respond with + * new members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + SUCCESS, + PENDING, + FAILED, + /** + * An enum member indicating that [AwsAutoTagging] was instantiated with an + * unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if + * you want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + SUCCESS -> Value.SUCCESS + PENDING -> Value.PENDING + FAILED -> Value.FAILED + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and + * don't want to throw for the unknown case. + * + * @throws ImageKitInvalidDataException if this class instance's value is a not a + * known member. + */ + fun known(): Known = + when (this) { + SUCCESS -> Known.SUCCESS + PENDING -> Known.PENDING + FAILED -> Known.FAILED + else -> throw ImageKitInvalidDataException("Unknown AwsAutoTagging: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for + * debugging and generally doesn't throw. + * + * @throws ImageKitInvalidDataException if this class instance's value does not have + * the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + ImageKitInvalidDataException("Value is not a String") + } + + private var validated: Boolean = false + + fun validate(): AwsAutoTagging = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is AwsAutoTagging && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + class GoogleAutoTagging + @JsonCreator + private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that + * doesn't match any known member, and you want to know that value. For example, if + * the SDK is on an older version than the API, then the API may respond with new + * members that the SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val SUCCESS = of("success") + + @JvmField val PENDING = of("pending") + + @JvmField val FAILED = of("failed") + + @JvmStatic fun of(value: String) = GoogleAutoTagging(JsonField.of(value)) + } + + /** An enum containing [GoogleAutoTagging]'s known values. */ + enum class Known { + SUCCESS, + PENDING, + FAILED, + } + + /** + * An enum containing [GoogleAutoTagging]'s known values, as well as an [_UNKNOWN] + * member. + * + * An instance of [GoogleAutoTagging] can contain an unknown value in a couple of + * cases: + * - It was deserialized from data that doesn't match any known member. For example, + * if the SDK is on an older version than the API, then the API may respond with + * new members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + SUCCESS, + PENDING, + FAILED, + /** + * An enum member indicating that [GoogleAutoTagging] was instantiated with an + * unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if + * you want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + SUCCESS -> Value.SUCCESS + PENDING -> Value.PENDING + FAILED -> Value.FAILED + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and + * don't want to throw for the unknown case. + * + * @throws ImageKitInvalidDataException if this class instance's value is a not a + * known member. + */ + fun known(): Known = + when (this) { + SUCCESS -> Known.SUCCESS + PENDING -> Known.PENDING + FAILED -> Known.FAILED + else -> + throw ImageKitInvalidDataException("Unknown GoogleAutoTagging: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for + * debugging and generally doesn't throw. + * + * @throws ImageKitInvalidDataException if this class instance's value does not have + * the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + ImageKitInvalidDataException("Value is not a String") + } + + private var validated: Boolean = false + + fun validate(): GoogleAutoTagging = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is GoogleAutoTagging && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + class RemoveBg @JsonCreator private constructor(private val value: JsonField) : + Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that + * doesn't match any known member, and you want to know that value. For example, if + * the SDK is on an older version than the API, then the API may respond with new + * members that the SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val SUCCESS = of("success") + + @JvmField val PENDING = of("pending") + + @JvmField val FAILED = of("failed") + + @JvmStatic fun of(value: String) = RemoveBg(JsonField.of(value)) + } + + /** An enum containing [RemoveBg]'s known values. */ + enum class Known { + SUCCESS, + PENDING, + FAILED, + } + + /** + * An enum containing [RemoveBg]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [RemoveBg] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, + * if the SDK is on an older version than the API, then the API may respond with + * new members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + SUCCESS, + PENDING, + FAILED, + /** + * An enum member indicating that [RemoveBg] was instantiated with an unknown + * value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if + * you want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + SUCCESS -> Value.SUCCESS + PENDING -> Value.PENDING + FAILED -> Value.FAILED + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and + * don't want to throw for the unknown case. + * + * @throws ImageKitInvalidDataException if this class instance's value is a not a + * known member. + */ + fun known(): Known = + when (this) { + SUCCESS -> Known.SUCCESS + PENDING -> Known.PENDING + FAILED -> Known.FAILED + else -> throw ImageKitInvalidDataException("Unknown RemoveBg: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for + * debugging and generally doesn't throw. + * + * @throws ImageKitInvalidDataException if this class instance's value does not have + * the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + ImageKitInvalidDataException("Value is not a String") + } + + private var validated: Boolean = false + + fun validate(): RemoveBg = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is RemoveBg && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ExtensionStatus && + aiAutoDescription == other.aiAutoDescription && + awsAutoTagging == other.awsAutoTagging && + googleAutoTagging == other.googleAutoTagging && + removeBg == other.removeBg && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + aiAutoDescription, + awsAutoTagging, + googleAutoTagging, + removeBg, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ExtensionStatus{aiAutoDescription=$aiAutoDescription, awsAutoTagging=$awsAutoTagging, googleAutoTagging=$googleAutoTagging, removeBg=$removeBg, additionalProperties=$additionalProperties}" + } + + /** An object containing the file or file version's `id` (versionId) and `name`. */ + class VersionInfo + private constructor( + private val id: JsonField, + private val name: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + ) : this(id, name, mutableMapOf()) + + /** + * Unique identifier of the file version. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun id(): Optional = id.getOptional("id") + + /** + * Name of the file version. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun name(): Optional = name.getOptional("name") + + /** + * Returns the raw JSON value of [id]. + * + * Unlike [id], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [VersionInfo]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [VersionInfo]. */ + class Builder internal constructor() { + + private var id: JsonField = JsonMissing.of() + private var name: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(versionInfo: VersionInfo) = apply { + id = versionInfo.id + name = versionInfo.name + additionalProperties = versionInfo.additionalProperties.toMutableMap() + } + + /** Unique identifier of the file version. */ + fun id(id: String) = id(JsonField.of(id)) + + /** + * Sets [Builder.id] to an arbitrary JSON value. + * + * You should usually call [Builder.id] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun id(id: JsonField) = apply { this.id = id } + + /** Name of the file version. */ + fun name(name: String) = name(JsonField.of(name)) + + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun name(name: JsonField) = apply { this.name = name } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [VersionInfo]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): VersionInfo = + VersionInfo(id, name, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): VersionInfo = apply { + if (validated) { + return@apply + } + + id() + name() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (id.asKnown().isPresent) 1 else 0) + (if (name.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is VersionInfo && + id == other.id && + name == other.name && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(id, name, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "VersionInfo{id=$id, name=$name, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Data && + aiTags == other.aiTags && + audioCodec == other.audioCodec && + bitRate == other.bitRate && + customCoordinates == other.customCoordinates && + customMetadata == other.customMetadata && + description == other.description && + duration == other.duration && + embeddedMetadata == other.embeddedMetadata && + extensionStatus == other.extensionStatus && + fileId == other.fileId && + filePath == other.filePath && + fileType == other.fileType && + height == other.height && + isPrivateFile == other.isPrivateFile && + isPublished == other.isPublished && + metadata == other.metadata && + name == other.name && + size == other.size && + tags == other.tags && + thumbnailUrl == other.thumbnailUrl && + url == other.url && + versionInfo == other.versionInfo && + videoCodec == other.videoCodec && + width == other.width && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + aiTags, + audioCodec, + bitRate, + customCoordinates, + customMetadata, + description, + duration, + embeddedMetadata, + extensionStatus, + fileId, + filePath, + fileType, + height, + isPrivateFile, + isPublished, + metadata, + name, + size, + tags, + thumbnailUrl, + url, + versionInfo, + videoCodec, + width, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Data{aiTags=$aiTags, audioCodec=$audioCodec, bitRate=$bitRate, customCoordinates=$customCoordinates, customMetadata=$customMetadata, description=$description, duration=$duration, embeddedMetadata=$embeddedMetadata, extensionStatus=$extensionStatus, fileId=$fileId, filePath=$filePath, fileType=$fileType, height=$height, isPrivateFile=$isPrivateFile, isPublished=$isPublished, metadata=$metadata, name=$name, size=$size, tags=$tags, thumbnailUrl=$thumbnailUrl, url=$url, versionInfo=$versionInfo, videoCodec=$videoCodec, width=$width, additionalProperties=$additionalProperties}" + } + + class Request + private constructor( + private val transformation: JsonField, + private val xRequestId: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("transformation") + @ExcludeMissing + transformation: JsonField = JsonMissing.of(), + @JsonProperty("x_request_id") + @ExcludeMissing + xRequestId: JsonField = JsonMissing.of(), + ) : this(transformation, xRequestId, mutableMapOf()) + + /** + * The requested pre-transformation string. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun transformation(): String = transformation.getRequired("transformation") + + /** + * Unique identifier for the originating request. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun xRequestId(): String = xRequestId.getRequired("x_request_id") + + /** + * Returns the raw JSON value of [transformation]. + * + * Unlike [transformation], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("transformation") + @ExcludeMissing + fun _transformation(): JsonField = transformation + + /** + * Returns the raw JSON value of [xRequestId]. + * + * Unlike [xRequestId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("x_request_id") + @ExcludeMissing + fun _xRequestId(): JsonField = xRequestId + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Request]. + * + * The following fields are required: + * ```java + * .transformation() + * .xRequestId() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Request]. */ + class Builder internal constructor() { + + private var transformation: JsonField? = null + private var xRequestId: JsonField? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(request: Request) = apply { + transformation = request.transformation + xRequestId = request.xRequestId + additionalProperties = request.additionalProperties.toMutableMap() + } + + /** The requested pre-transformation string. */ + fun transformation(transformation: String) = + transformation(JsonField.of(transformation)) + + /** + * Sets [Builder.transformation] to an arbitrary JSON value. + * + * You should usually call [Builder.transformation] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun transformation(transformation: JsonField) = apply { + this.transformation = transformation + } + + /** Unique identifier for the originating request. */ + fun xRequestId(xRequestId: String) = xRequestId(JsonField.of(xRequestId)) + + /** + * Sets [Builder.xRequestId] to an arbitrary JSON value. + * + * You should usually call [Builder.xRequestId] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun xRequestId(xRequestId: JsonField) = apply { this.xRequestId = xRequestId } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Request]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .transformation() + * .xRequestId() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Request = + Request( + checkRequired("transformation", transformation), + checkRequired("xRequestId", xRequestId), + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Request = apply { + if (validated) { + return@apply + } + + transformation() + xRequestId() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (transformation.asKnown().isPresent) 1 else 0) + + (if (xRequestId.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Request && + transformation == other.transformation && + xRequestId == other.xRequestId && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(transformation, xRequestId, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Request{transformation=$transformation, xRequestId=$xRequestId, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is UploadPreTransformSuccessEvent && + id == other.id && + type == other.type && + createdAt == other.createdAt && + data == other.data && + request == other.request && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(id, type, createdAt, data, request, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "UploadPreTransformSuccessEvent{id=$id, type=$type, createdAt=$createdAt, data=$data, request=$request, additionalProperties=$additionalProperties}" +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/webhooks/VideoTransformationAcceptedEvent.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/webhooks/VideoTransformationAcceptedEvent.kt new file mode 100644 index 0000000..61dbf8a --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/webhooks/VideoTransformationAcceptedEvent.kt @@ -0,0 +1,2305 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.webhooks + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.imagekit.api.core.Enum +import com.imagekit.api.core.ExcludeMissing +import com.imagekit.api.core.JsonField +import com.imagekit.api.core.JsonMissing +import com.imagekit.api.core.JsonValue +import com.imagekit.api.core.checkKnown +import com.imagekit.api.core.checkRequired +import com.imagekit.api.core.toImmutable +import com.imagekit.api.errors.ImageKitInvalidDataException +import java.time.OffsetDateTime +import java.util.Collections +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** + * Triggered when a new video transformation request is accepted for processing. This event confirms + * that ImageKit has received and queued your transformation request. Use this for debugging and + * tracking transformation lifecycle. + */ +class VideoTransformationAcceptedEvent +private constructor( + private val id: JsonField, + private val type: JsonField, + private val createdAt: JsonField, + private val data: JsonField, + private val request: JsonField, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonField = JsonMissing.of(), + @JsonProperty("created_at") + @ExcludeMissing + createdAt: JsonField = JsonMissing.of(), + @JsonProperty("data") @ExcludeMissing data: JsonField = JsonMissing.of(), + @JsonProperty("request") @ExcludeMissing request: JsonField = JsonMissing.of(), + ) : this(id, type, createdAt, data, request, mutableMapOf()) + + fun toBaseWebhookEvent(): BaseWebhookEvent = + BaseWebhookEvent.builder().id(id).type(type).build() + + /** + * Unique identifier for the event. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun id(): String = id.getRequired("id") + + /** + * The type of webhook event. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun type(): String = type.getRequired("type") + + /** + * Timestamp when the event was created in ISO8601 format. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun createdAt(): OffsetDateTime = createdAt.getRequired("created_at") + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun data(): Data = data.getRequired("data") + + /** + * Information about the original request that triggered the video transformation. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun request(): Request = request.getRequired("request") + + /** + * Returns the raw JSON value of [id]. + * + * Unlike [id], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id + + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + + /** + * Returns the raw JSON value of [createdAt]. + * + * Unlike [createdAt], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("created_at") + @ExcludeMissing + fun _createdAt(): JsonField = createdAt + + /** + * Returns the raw JSON value of [data]. + * + * Unlike [data], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("data") @ExcludeMissing fun _data(): JsonField = data + + /** + * Returns the raw JSON value of [request]. + * + * Unlike [request], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("request") @ExcludeMissing fun _request(): JsonField = request + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [VideoTransformationAcceptedEvent]. + * + * The following fields are required: + * ```java + * .id() + * .type() + * .createdAt() + * .data() + * .request() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [VideoTransformationAcceptedEvent]. */ + class Builder internal constructor() { + + private var id: JsonField? = null + private var type: JsonField? = null + private var createdAt: JsonField? = null + private var data: JsonField? = null + private var request: JsonField? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(videoTransformationAcceptedEvent: VideoTransformationAcceptedEvent) = + apply { + id = videoTransformationAcceptedEvent.id + type = videoTransformationAcceptedEvent.type + createdAt = videoTransformationAcceptedEvent.createdAt + data = videoTransformationAcceptedEvent.data + request = videoTransformationAcceptedEvent.request + additionalProperties = + videoTransformationAcceptedEvent.additionalProperties.toMutableMap() + } + + /** Unique identifier for the event. */ + fun id(id: String) = id(JsonField.of(id)) + + /** + * Sets [Builder.id] to an arbitrary JSON value. + * + * You should usually call [Builder.id] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun id(id: JsonField) = apply { this.id = id } + + /** The type of webhook event. */ + fun type(type: String) = type(JsonField.of(type)) + + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun type(type: JsonField) = apply { this.type = type } + + /** Timestamp when the event was created in ISO8601 format. */ + fun createdAt(createdAt: OffsetDateTime) = createdAt(JsonField.of(createdAt)) + + /** + * Sets [Builder.createdAt] to an arbitrary JSON value. + * + * You should usually call [Builder.createdAt] with a well-typed [OffsetDateTime] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun createdAt(createdAt: JsonField) = apply { this.createdAt = createdAt } + + fun data(data: Data) = data(JsonField.of(data)) + + /** + * Sets [Builder.data] to an arbitrary JSON value. + * + * You should usually call [Builder.data] with a well-typed [Data] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun data(data: JsonField) = apply { this.data = data } + + /** Information about the original request that triggered the video transformation. */ + fun request(request: Request) = request(JsonField.of(request)) + + /** + * Sets [Builder.request] to an arbitrary JSON value. + * + * You should usually call [Builder.request] with a well-typed [Request] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun request(request: JsonField) = apply { this.request = request } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [VideoTransformationAcceptedEvent]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .id() + * .type() + * .createdAt() + * .data() + * .request() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): VideoTransformationAcceptedEvent = + VideoTransformationAcceptedEvent( + checkRequired("id", id), + checkRequired("type", type), + checkRequired("createdAt", createdAt), + checkRequired("data", data), + checkRequired("request", request), + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): VideoTransformationAcceptedEvent = apply { + if (validated) { + return@apply + } + + id() + type() + createdAt() + data().validate() + request().validate() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (id.asKnown().isPresent) 1 else 0) + + (if (type.asKnown().isPresent) 1 else 0) + + (if (createdAt.asKnown().isPresent) 1 else 0) + + (data.asKnown().getOrNull()?.validity() ?: 0) + + (request.asKnown().getOrNull()?.validity() ?: 0) + + class Data + private constructor( + private val asset: JsonField, + private val transformation: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("asset") @ExcludeMissing asset: JsonField = JsonMissing.of(), + @JsonProperty("transformation") + @ExcludeMissing + transformation: JsonField = JsonMissing.of(), + ) : this(asset, transformation, mutableMapOf()) + + /** + * Information about the source video asset being transformed. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun asset(): Asset = asset.getRequired("asset") + + /** + * Base information about a video transformation request. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun transformation(): Transformation = transformation.getRequired("transformation") + + /** + * Returns the raw JSON value of [asset]. + * + * Unlike [asset], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("asset") @ExcludeMissing fun _asset(): JsonField = asset + + /** + * Returns the raw JSON value of [transformation]. + * + * Unlike [transformation], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("transformation") + @ExcludeMissing + fun _transformation(): JsonField = transformation + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Data]. + * + * The following fields are required: + * ```java + * .asset() + * .transformation() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Data]. */ + class Builder internal constructor() { + + private var asset: JsonField? = null + private var transformation: JsonField? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(data: Data) = apply { + asset = data.asset + transformation = data.transformation + additionalProperties = data.additionalProperties.toMutableMap() + } + + /** Information about the source video asset being transformed. */ + fun asset(asset: Asset) = asset(JsonField.of(asset)) + + /** + * Sets [Builder.asset] to an arbitrary JSON value. + * + * You should usually call [Builder.asset] with a well-typed [Asset] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun asset(asset: JsonField) = apply { this.asset = asset } + + /** Base information about a video transformation request. */ + fun transformation(transformation: Transformation) = + transformation(JsonField.of(transformation)) + + /** + * Sets [Builder.transformation] to an arbitrary JSON value. + * + * You should usually call [Builder.transformation] with a well-typed [Transformation] + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun transformation(transformation: JsonField) = apply { + this.transformation = transformation + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Data]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .asset() + * .transformation() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Data = + Data( + checkRequired("asset", asset), + checkRequired("transformation", transformation), + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Data = apply { + if (validated) { + return@apply + } + + asset().validate() + transformation().validate() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (asset.asKnown().getOrNull()?.validity() ?: 0) + + (transformation.asKnown().getOrNull()?.validity() ?: 0) + + /** Information about the source video asset being transformed. */ + class Asset + private constructor( + private val url: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("url") @ExcludeMissing url: JsonField = JsonMissing.of() + ) : this(url, mutableMapOf()) + + /** + * URL to download or access the source video file. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected + * value). + */ + fun url(): String = url.getRequired("url") + + /** + * Returns the raw JSON value of [url]. + * + * Unlike [url], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("url") @ExcludeMissing fun _url(): JsonField = url + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Asset]. + * + * The following fields are required: + * ```java + * .url() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Asset]. */ + class Builder internal constructor() { + + private var url: JsonField? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(asset: Asset) = apply { + url = asset.url + additionalProperties = asset.additionalProperties.toMutableMap() + } + + /** URL to download or access the source video file. */ + fun url(url: String) = url(JsonField.of(url)) + + /** + * Sets [Builder.url] to an arbitrary JSON value. + * + * You should usually call [Builder.url] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun url(url: JsonField) = apply { this.url = url } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Asset]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .url() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Asset = + Asset(checkRequired("url", url), additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Asset = apply { + if (validated) { + return@apply + } + + url() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = (if (url.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Asset && + url == other.url && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(url, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "Asset{url=$url, additionalProperties=$additionalProperties}" + } + + /** Base information about a video transformation request. */ + class Transformation + private constructor( + private val type: JsonField, + private val options: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("type") @ExcludeMissing type: JsonField = JsonMissing.of(), + @JsonProperty("options") + @ExcludeMissing + options: JsonField = JsonMissing.of(), + ) : this(type, options, mutableMapOf()) + + /** + * Type of video transformation: + * - `video-transformation`: Standard video processing (resize, format conversion, etc.) + * - `gif-to-video`: Convert animated GIF to video format + * - `video-thumbnail`: Generate thumbnail image from video + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected + * value). + */ + fun type(): Type = type.getRequired("type") + + /** + * Configuration options for video transformations. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun options(): Optional = options.getOptional("options") + + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + + /** + * Returns the raw JSON value of [options]. + * + * Unlike [options], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("options") @ExcludeMissing fun _options(): JsonField = options + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Transformation]. + * + * The following fields are required: + * ```java + * .type() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Transformation]. */ + class Builder internal constructor() { + + private var type: JsonField? = null + private var options: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(transformation: Transformation) = apply { + type = transformation.type + options = transformation.options + additionalProperties = transformation.additionalProperties.toMutableMap() + } + + /** + * Type of video transformation: + * - `video-transformation`: Standard video processing (resize, format conversion, + * etc.) + * - `gif-to-video`: Convert animated GIF to video format + * - `video-thumbnail`: Generate thumbnail image from video + */ + fun type(type: Type) = type(JsonField.of(type)) + + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [Type] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun type(type: JsonField) = apply { this.type = type } + + /** Configuration options for video transformations. */ + fun options(options: Options) = options(JsonField.of(options)) + + /** + * Sets [Builder.options] to an arbitrary JSON value. + * + * You should usually call [Builder.options] with a well-typed [Options] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun options(options: JsonField) = apply { this.options = options } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Transformation]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .type() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Transformation = + Transformation( + checkRequired("type", type), + options, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Transformation = apply { + if (validated) { + return@apply + } + + type().validate() + options().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (type.asKnown().getOrNull()?.validity() ?: 0) + + (options.asKnown().getOrNull()?.validity() ?: 0) + + /** + * Type of video transformation: + * - `video-transformation`: Standard video processing (resize, format conversion, etc.) + * - `gif-to-video`: Convert animated GIF to video format + * - `video-thumbnail`: Generate thumbnail image from video + */ + class Type @JsonCreator private constructor(private val value: JsonField) : + Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that + * doesn't match any known member, and you want to know that value. For example, if + * the SDK is on an older version than the API, then the API may respond with new + * members that the SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val VIDEO_TRANSFORMATION = of("video-transformation") + + @JvmField val GIF_TO_VIDEO = of("gif-to-video") + + @JvmField val VIDEO_THUMBNAIL = of("video-thumbnail") + + @JvmStatic fun of(value: String) = Type(JsonField.of(value)) + } + + /** An enum containing [Type]'s known values. */ + enum class Known { + VIDEO_TRANSFORMATION, + GIF_TO_VIDEO, + VIDEO_THUMBNAIL, + } + + /** + * An enum containing [Type]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [Type] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, + * if the SDK is on an older version than the API, then the API may respond with + * new members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + VIDEO_TRANSFORMATION, + GIF_TO_VIDEO, + VIDEO_THUMBNAIL, + /** + * An enum member indicating that [Type] was instantiated with an unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if + * you want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + VIDEO_TRANSFORMATION -> Value.VIDEO_TRANSFORMATION + GIF_TO_VIDEO -> Value.GIF_TO_VIDEO + VIDEO_THUMBNAIL -> Value.VIDEO_THUMBNAIL + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and + * don't want to throw for the unknown case. + * + * @throws ImageKitInvalidDataException if this class instance's value is a not a + * known member. + */ + fun known(): Known = + when (this) { + VIDEO_TRANSFORMATION -> Known.VIDEO_TRANSFORMATION + GIF_TO_VIDEO -> Known.GIF_TO_VIDEO + VIDEO_THUMBNAIL -> Known.VIDEO_THUMBNAIL + else -> throw ImageKitInvalidDataException("Unknown Type: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for + * debugging and generally doesn't throw. + * + * @throws ImageKitInvalidDataException if this class instance's value does not have + * the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + ImageKitInvalidDataException("Value is not a String") + } + + private var validated: Boolean = false + + fun validate(): Type = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Type && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + /** Configuration options for video transformations. */ + class Options + private constructor( + private val audioCodec: JsonField, + private val autoRotate: JsonField, + private val format: JsonField, + private val quality: JsonField, + private val streamProtocol: JsonField, + private val variants: JsonField>, + private val videoCodec: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("audio_codec") + @ExcludeMissing + audioCodec: JsonField = JsonMissing.of(), + @JsonProperty("auto_rotate") + @ExcludeMissing + autoRotate: JsonField = JsonMissing.of(), + @JsonProperty("format") + @ExcludeMissing + format: JsonField = JsonMissing.of(), + @JsonProperty("quality") + @ExcludeMissing + quality: JsonField = JsonMissing.of(), + @JsonProperty("stream_protocol") + @ExcludeMissing + streamProtocol: JsonField = JsonMissing.of(), + @JsonProperty("variants") + @ExcludeMissing + variants: JsonField> = JsonMissing.of(), + @JsonProperty("video_codec") + @ExcludeMissing + videoCodec: JsonField = JsonMissing.of(), + ) : this( + audioCodec, + autoRotate, + format, + quality, + streamProtocol, + variants, + videoCodec, + mutableMapOf(), + ) + + /** + * Audio codec used for encoding (aac or opus). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun audioCodec(): Optional = audioCodec.getOptional("audio_codec") + + /** + * Whether to automatically rotate the video based on metadata. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun autoRotate(): Optional = autoRotate.getOptional("auto_rotate") + + /** + * Output format for the transformed video or thumbnail. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun format(): Optional = format.getOptional("format") + + /** + * Quality setting for the output video. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun quality(): Optional = quality.getOptional("quality") + + /** + * Streaming protocol for adaptive bitrate streaming. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun streamProtocol(): Optional = + streamProtocol.getOptional("stream_protocol") + + /** + * Array of quality representations for adaptive bitrate streaming. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun variants(): Optional> = variants.getOptional("variants") + + /** + * Video codec used for encoding (h264, vp9, or av1). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun videoCodec(): Optional = videoCodec.getOptional("video_codec") + + /** + * Returns the raw JSON value of [audioCodec]. + * + * Unlike [audioCodec], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("audio_codec") + @ExcludeMissing + fun _audioCodec(): JsonField = audioCodec + + /** + * Returns the raw JSON value of [autoRotate]. + * + * Unlike [autoRotate], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("auto_rotate") + @ExcludeMissing + fun _autoRotate(): JsonField = autoRotate + + /** + * Returns the raw JSON value of [format]. + * + * Unlike [format], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("format") @ExcludeMissing fun _format(): JsonField = format + + /** + * Returns the raw JSON value of [quality]. + * + * Unlike [quality], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("quality") @ExcludeMissing fun _quality(): JsonField = quality + + /** + * Returns the raw JSON value of [streamProtocol]. + * + * Unlike [streamProtocol], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("stream_protocol") + @ExcludeMissing + fun _streamProtocol(): JsonField = streamProtocol + + /** + * Returns the raw JSON value of [variants]. + * + * Unlike [variants], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("variants") + @ExcludeMissing + fun _variants(): JsonField> = variants + + /** + * Returns the raw JSON value of [videoCodec]. + * + * Unlike [videoCodec], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("video_codec") + @ExcludeMissing + fun _videoCodec(): JsonField = videoCodec + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Options]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Options]. */ + class Builder internal constructor() { + + private var audioCodec: JsonField = JsonMissing.of() + private var autoRotate: JsonField = JsonMissing.of() + private var format: JsonField = JsonMissing.of() + private var quality: JsonField = JsonMissing.of() + private var streamProtocol: JsonField = JsonMissing.of() + private var variants: JsonField>? = null + private var videoCodec: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(options: Options) = apply { + audioCodec = options.audioCodec + autoRotate = options.autoRotate + format = options.format + quality = options.quality + streamProtocol = options.streamProtocol + variants = options.variants.map { it.toMutableList() } + videoCodec = options.videoCodec + additionalProperties = options.additionalProperties.toMutableMap() + } + + /** Audio codec used for encoding (aac or opus). */ + fun audioCodec(audioCodec: AudioCodec) = audioCodec(JsonField.of(audioCodec)) + + /** + * Sets [Builder.audioCodec] to an arbitrary JSON value. + * + * You should usually call [Builder.audioCodec] with a well-typed [AudioCodec] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun audioCodec(audioCodec: JsonField) = apply { + this.audioCodec = audioCodec + } + + /** Whether to automatically rotate the video based on metadata. */ + fun autoRotate(autoRotate: Boolean) = autoRotate(JsonField.of(autoRotate)) + + /** + * Sets [Builder.autoRotate] to an arbitrary JSON value. + * + * You should usually call [Builder.autoRotate] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun autoRotate(autoRotate: JsonField) = apply { + this.autoRotate = autoRotate + } + + /** Output format for the transformed video or thumbnail. */ + fun format(format: Format) = format(JsonField.of(format)) + + /** + * Sets [Builder.format] to an arbitrary JSON value. + * + * You should usually call [Builder.format] with a well-typed [Format] value + * instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun format(format: JsonField) = apply { this.format = format } + + /** Quality setting for the output video. */ + fun quality(quality: Long) = quality(JsonField.of(quality)) + + /** + * Sets [Builder.quality] to an arbitrary JSON value. + * + * You should usually call [Builder.quality] with a well-typed [Long] value + * instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun quality(quality: JsonField) = apply { this.quality = quality } + + /** Streaming protocol for adaptive bitrate streaming. */ + fun streamProtocol(streamProtocol: StreamProtocol) = + streamProtocol(JsonField.of(streamProtocol)) + + /** + * Sets [Builder.streamProtocol] to an arbitrary JSON value. + * + * You should usually call [Builder.streamProtocol] with a well-typed + * [StreamProtocol] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ + fun streamProtocol(streamProtocol: JsonField) = apply { + this.streamProtocol = streamProtocol + } + + /** Array of quality representations for adaptive bitrate streaming. */ + fun variants(variants: List) = variants(JsonField.of(variants)) + + /** + * Sets [Builder.variants] to an arbitrary JSON value. + * + * You should usually call [Builder.variants] with a well-typed `List` + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun variants(variants: JsonField>) = apply { + this.variants = variants.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [variants]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addVariant(variant: String) = apply { + variants = + (variants ?: JsonField.of(mutableListOf())).also { + checkKnown("variants", it).add(variant) + } + } + + /** Video codec used for encoding (h264, vp9, or av1). */ + fun videoCodec(videoCodec: VideoCodec) = videoCodec(JsonField.of(videoCodec)) + + /** + * Sets [Builder.videoCodec] to an arbitrary JSON value. + * + * You should usually call [Builder.videoCodec] with a well-typed [VideoCodec] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun videoCodec(videoCodec: JsonField) = apply { + this.videoCodec = videoCodec + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Options]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Options = + Options( + audioCodec, + autoRotate, + format, + quality, + streamProtocol, + (variants ?: JsonMissing.of()).map { it.toImmutable() }, + videoCodec, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Options = apply { + if (validated) { + return@apply + } + + audioCodec().ifPresent { it.validate() } + autoRotate() + format().ifPresent { it.validate() } + quality() + streamProtocol().ifPresent { it.validate() } + variants() + videoCodec().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (audioCodec.asKnown().getOrNull()?.validity() ?: 0) + + (if (autoRotate.asKnown().isPresent) 1 else 0) + + (format.asKnown().getOrNull()?.validity() ?: 0) + + (if (quality.asKnown().isPresent) 1 else 0) + + (streamProtocol.asKnown().getOrNull()?.validity() ?: 0) + + (variants.asKnown().getOrNull()?.size ?: 0) + + (videoCodec.asKnown().getOrNull()?.validity() ?: 0) + + /** Audio codec used for encoding (aac or opus). */ + class AudioCodec + @JsonCreator + private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that + * doesn't match any known member, and you want to know that value. For example, + * if the SDK is on an older version than the API, then the API may respond with + * new members that the SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue + fun _value(): JsonField = value + + companion object { + + @JvmField val AAC = of("aac") + + @JvmField val OPUS = of("opus") + + @JvmStatic fun of(value: String) = AudioCodec(JsonField.of(value)) + } + + /** An enum containing [AudioCodec]'s known values. */ + enum class Known { + AAC, + OPUS, + } + + /** + * An enum containing [AudioCodec]'s known values, as well as an [_UNKNOWN] + * member. + * + * An instance of [AudioCodec] can contain an unknown value in a couple of + * cases: + * - It was deserialized from data that doesn't match any known member. For + * example, if the SDK is on an older version than the API, then the API may + * respond with new members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + AAC, + OPUS, + /** + * An enum member indicating that [AudioCodec] was instantiated with an + * unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or + * if you want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + AAC -> Value.AAC + OPUS -> Value.OPUS + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known + * and don't want to throw for the unknown case. + * + * @throws ImageKitInvalidDataException if this class instance's value is a not + * a known member. + */ + fun known(): Known = + when (this) { + AAC -> Known.AAC + OPUS -> Known.OPUS + else -> throw ImageKitInvalidDataException("Unknown AudioCodec: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for + * debugging and generally doesn't throw. + * + * @throws ImageKitInvalidDataException if this class instance's value does not + * have the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + ImageKitInvalidDataException("Value is not a String") + } + + private var validated: Boolean = false + + fun validate(): AudioCodec = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is AudioCodec && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + /** Output format for the transformed video or thumbnail. */ + class Format + @JsonCreator + private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that + * doesn't match any known member, and you want to know that value. For example, + * if the SDK is on an older version than the API, then the API may respond with + * new members that the SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue + fun _value(): JsonField = value + + companion object { + + @JvmField val MP4 = of("mp4") + + @JvmField val WEBM = of("webm") + + @JvmField val JPG = of("jpg") + + @JvmField val PNG = of("png") + + @JvmField val WEBP = of("webp") + + @JvmStatic fun of(value: String) = Format(JsonField.of(value)) + } + + /** An enum containing [Format]'s known values. */ + enum class Known { + MP4, + WEBM, + JPG, + PNG, + WEBP, + } + + /** + * An enum containing [Format]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [Format] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For + * example, if the SDK is on an older version than the API, then the API may + * respond with new members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + MP4, + WEBM, + JPG, + PNG, + WEBP, + /** + * An enum member indicating that [Format] was instantiated with an unknown + * value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or + * if you want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + MP4 -> Value.MP4 + WEBM -> Value.WEBM + JPG -> Value.JPG + PNG -> Value.PNG + WEBP -> Value.WEBP + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known + * and don't want to throw for the unknown case. + * + * @throws ImageKitInvalidDataException if this class instance's value is a not + * a known member. + */ + fun known(): Known = + when (this) { + MP4 -> Known.MP4 + WEBM -> Known.WEBM + JPG -> Known.JPG + PNG -> Known.PNG + WEBP -> Known.WEBP + else -> throw ImageKitInvalidDataException("Unknown Format: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for + * debugging and generally doesn't throw. + * + * @throws ImageKitInvalidDataException if this class instance's value does not + * have the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + ImageKitInvalidDataException("Value is not a String") + } + + private var validated: Boolean = false + + fun validate(): Format = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Format && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + /** Streaming protocol for adaptive bitrate streaming. */ + class StreamProtocol + @JsonCreator + private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that + * doesn't match any known member, and you want to know that value. For example, + * if the SDK is on an older version than the API, then the API may respond with + * new members that the SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue + fun _value(): JsonField = value + + companion object { + + @JvmField val HLS = of("HLS") + + @JvmField val DASH = of("DASH") + + @JvmStatic fun of(value: String) = StreamProtocol(JsonField.of(value)) + } + + /** An enum containing [StreamProtocol]'s known values. */ + enum class Known { + HLS, + DASH, + } + + /** + * An enum containing [StreamProtocol]'s known values, as well as an [_UNKNOWN] + * member. + * + * An instance of [StreamProtocol] can contain an unknown value in a couple of + * cases: + * - It was deserialized from data that doesn't match any known member. For + * example, if the SDK is on an older version than the API, then the API may + * respond with new members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + HLS, + DASH, + /** + * An enum member indicating that [StreamProtocol] was instantiated with an + * unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or + * if you want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + HLS -> Value.HLS + DASH -> Value.DASH + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known + * and don't want to throw for the unknown case. + * + * @throws ImageKitInvalidDataException if this class instance's value is a not + * a known member. + */ + fun known(): Known = + when (this) { + HLS -> Known.HLS + DASH -> Known.DASH + else -> + throw ImageKitInvalidDataException("Unknown StreamProtocol: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for + * debugging and generally doesn't throw. + * + * @throws ImageKitInvalidDataException if this class instance's value does not + * have the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + ImageKitInvalidDataException("Value is not a String") + } + + private var validated: Boolean = false + + fun validate(): StreamProtocol = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is StreamProtocol && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + /** Video codec used for encoding (h264, vp9, or av1). */ + class VideoCodec + @JsonCreator + private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that + * doesn't match any known member, and you want to know that value. For example, + * if the SDK is on an older version than the API, then the API may respond with + * new members that the SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue + fun _value(): JsonField = value + + companion object { + + @JvmField val H264 = of("h264") + + @JvmField val VP9 = of("vp9") + + @JvmField val AV1 = of("av1") + + @JvmStatic fun of(value: String) = VideoCodec(JsonField.of(value)) + } + + /** An enum containing [VideoCodec]'s known values. */ + enum class Known { + H264, + VP9, + AV1, + } + + /** + * An enum containing [VideoCodec]'s known values, as well as an [_UNKNOWN] + * member. + * + * An instance of [VideoCodec] can contain an unknown value in a couple of + * cases: + * - It was deserialized from data that doesn't match any known member. For + * example, if the SDK is on an older version than the API, then the API may + * respond with new members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + H264, + VP9, + AV1, + /** + * An enum member indicating that [VideoCodec] was instantiated with an + * unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or + * if you want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + H264 -> Value.H264 + VP9 -> Value.VP9 + AV1 -> Value.AV1 + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known + * and don't want to throw for the unknown case. + * + * @throws ImageKitInvalidDataException if this class instance's value is a not + * a known member. + */ + fun known(): Known = + when (this) { + H264 -> Known.H264 + VP9 -> Known.VP9 + AV1 -> Known.AV1 + else -> throw ImageKitInvalidDataException("Unknown VideoCodec: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for + * debugging and generally doesn't throw. + * + * @throws ImageKitInvalidDataException if this class instance's value does not + * have the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + ImageKitInvalidDataException("Value is not a String") + } + + private var validated: Boolean = false + + fun validate(): VideoCodec = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is VideoCodec && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Options && + audioCodec == other.audioCodec && + autoRotate == other.autoRotate && + format == other.format && + quality == other.quality && + streamProtocol == other.streamProtocol && + variants == other.variants && + videoCodec == other.videoCodec && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + audioCodec, + autoRotate, + format, + quality, + streamProtocol, + variants, + videoCodec, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Options{audioCodec=$audioCodec, autoRotate=$autoRotate, format=$format, quality=$quality, streamProtocol=$streamProtocol, variants=$variants, videoCodec=$videoCodec, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Transformation && + type == other.type && + options == other.options && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(type, options, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Transformation{type=$type, options=$options, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Data && + asset == other.asset && + transformation == other.transformation && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(asset, transformation, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Data{asset=$asset, transformation=$transformation, additionalProperties=$additionalProperties}" + } + + /** Information about the original request that triggered the video transformation. */ + class Request + private constructor( + private val url: JsonField, + private val xRequestId: JsonField, + private val userAgent: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("url") @ExcludeMissing url: JsonField = JsonMissing.of(), + @JsonProperty("x_request_id") + @ExcludeMissing + xRequestId: JsonField = JsonMissing.of(), + @JsonProperty("user_agent") + @ExcludeMissing + userAgent: JsonField = JsonMissing.of(), + ) : this(url, xRequestId, userAgent, mutableMapOf()) + + /** + * Full URL of the transformation request that was submitted. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun url(): String = url.getRequired("url") + + /** + * Unique identifier for the originating transformation request. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun xRequestId(): String = xRequestId.getRequired("x_request_id") + + /** + * User-Agent header from the original request that triggered the transformation. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun userAgent(): Optional = userAgent.getOptional("user_agent") + + /** + * Returns the raw JSON value of [url]. + * + * Unlike [url], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("url") @ExcludeMissing fun _url(): JsonField = url + + /** + * Returns the raw JSON value of [xRequestId]. + * + * Unlike [xRequestId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("x_request_id") + @ExcludeMissing + fun _xRequestId(): JsonField = xRequestId + + /** + * Returns the raw JSON value of [userAgent]. + * + * Unlike [userAgent], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("user_agent") @ExcludeMissing fun _userAgent(): JsonField = userAgent + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Request]. + * + * The following fields are required: + * ```java + * .url() + * .xRequestId() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Request]. */ + class Builder internal constructor() { + + private var url: JsonField? = null + private var xRequestId: JsonField? = null + private var userAgent: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(request: Request) = apply { + url = request.url + xRequestId = request.xRequestId + userAgent = request.userAgent + additionalProperties = request.additionalProperties.toMutableMap() + } + + /** Full URL of the transformation request that was submitted. */ + fun url(url: String) = url(JsonField.of(url)) + + /** + * Sets [Builder.url] to an arbitrary JSON value. + * + * You should usually call [Builder.url] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun url(url: JsonField) = apply { this.url = url } + + /** Unique identifier for the originating transformation request. */ + fun xRequestId(xRequestId: String) = xRequestId(JsonField.of(xRequestId)) + + /** + * Sets [Builder.xRequestId] to an arbitrary JSON value. + * + * You should usually call [Builder.xRequestId] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun xRequestId(xRequestId: JsonField) = apply { this.xRequestId = xRequestId } + + /** User-Agent header from the original request that triggered the transformation. */ + fun userAgent(userAgent: String) = userAgent(JsonField.of(userAgent)) + + /** + * Sets [Builder.userAgent] to an arbitrary JSON value. + * + * You should usually call [Builder.userAgent] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun userAgent(userAgent: JsonField) = apply { this.userAgent = userAgent } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Request]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .url() + * .xRequestId() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Request = + Request( + checkRequired("url", url), + checkRequired("xRequestId", xRequestId), + userAgent, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Request = apply { + if (validated) { + return@apply + } + + url() + xRequestId() + userAgent() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (url.asKnown().isPresent) 1 else 0) + + (if (xRequestId.asKnown().isPresent) 1 else 0) + + (if (userAgent.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Request && + url == other.url && + xRequestId == other.xRequestId && + userAgent == other.userAgent && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(url, xRequestId, userAgent, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Request{url=$url, xRequestId=$xRequestId, userAgent=$userAgent, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is VideoTransformationAcceptedEvent && + id == other.id && + type == other.type && + createdAt == other.createdAt && + data == other.data && + request == other.request && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(id, type, createdAt, data, request, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "VideoTransformationAcceptedEvent{id=$id, type=$type, createdAt=$createdAt, data=$data, request=$request, additionalProperties=$additionalProperties}" +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/webhooks/VideoTransformationErrorEvent.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/webhooks/VideoTransformationErrorEvent.kt new file mode 100644 index 0000000..176f400 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/webhooks/VideoTransformationErrorEvent.kt @@ -0,0 +1,2654 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.webhooks + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.imagekit.api.core.Enum +import com.imagekit.api.core.ExcludeMissing +import com.imagekit.api.core.JsonField +import com.imagekit.api.core.JsonMissing +import com.imagekit.api.core.JsonValue +import com.imagekit.api.core.checkKnown +import com.imagekit.api.core.checkRequired +import com.imagekit.api.core.toImmutable +import com.imagekit.api.errors.ImageKitInvalidDataException +import java.time.OffsetDateTime +import java.util.Collections +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** + * Triggered when an error occurs during video encoding. Listen to this webhook to log error reasons + * and debug issues. Check your origin and URL endpoint settings if the reason is related to + * download failure. For other errors, contact ImageKit support. + */ +class VideoTransformationErrorEvent +private constructor( + private val id: JsonField, + private val type: JsonField, + private val createdAt: JsonField, + private val data: JsonField, + private val request: JsonField, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonField = JsonMissing.of(), + @JsonProperty("created_at") + @ExcludeMissing + createdAt: JsonField = JsonMissing.of(), + @JsonProperty("data") @ExcludeMissing data: JsonField = JsonMissing.of(), + @JsonProperty("request") @ExcludeMissing request: JsonField = JsonMissing.of(), + ) : this(id, type, createdAt, data, request, mutableMapOf()) + + fun toBaseWebhookEvent(): BaseWebhookEvent = + BaseWebhookEvent.builder().id(id).type(type).build() + + /** + * Unique identifier for the event. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun id(): String = id.getRequired("id") + + /** + * The type of webhook event. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun type(): String = type.getRequired("type") + + /** + * Timestamp when the event was created in ISO8601 format. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun createdAt(): OffsetDateTime = createdAt.getRequired("created_at") + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun data(): Data = data.getRequired("data") + + /** + * Information about the original request that triggered the video transformation. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun request(): Request = request.getRequired("request") + + /** + * Returns the raw JSON value of [id]. + * + * Unlike [id], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id + + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + + /** + * Returns the raw JSON value of [createdAt]. + * + * Unlike [createdAt], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("created_at") + @ExcludeMissing + fun _createdAt(): JsonField = createdAt + + /** + * Returns the raw JSON value of [data]. + * + * Unlike [data], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("data") @ExcludeMissing fun _data(): JsonField = data + + /** + * Returns the raw JSON value of [request]. + * + * Unlike [request], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("request") @ExcludeMissing fun _request(): JsonField = request + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [VideoTransformationErrorEvent]. + * + * The following fields are required: + * ```java + * .id() + * .type() + * .createdAt() + * .data() + * .request() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [VideoTransformationErrorEvent]. */ + class Builder internal constructor() { + + private var id: JsonField? = null + private var type: JsonField? = null + private var createdAt: JsonField? = null + private var data: JsonField? = null + private var request: JsonField? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(videoTransformationErrorEvent: VideoTransformationErrorEvent) = apply { + id = videoTransformationErrorEvent.id + type = videoTransformationErrorEvent.type + createdAt = videoTransformationErrorEvent.createdAt + data = videoTransformationErrorEvent.data + request = videoTransformationErrorEvent.request + additionalProperties = videoTransformationErrorEvent.additionalProperties.toMutableMap() + } + + /** Unique identifier for the event. */ + fun id(id: String) = id(JsonField.of(id)) + + /** + * Sets [Builder.id] to an arbitrary JSON value. + * + * You should usually call [Builder.id] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun id(id: JsonField) = apply { this.id = id } + + /** The type of webhook event. */ + fun type(type: String) = type(JsonField.of(type)) + + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun type(type: JsonField) = apply { this.type = type } + + /** Timestamp when the event was created in ISO8601 format. */ + fun createdAt(createdAt: OffsetDateTime) = createdAt(JsonField.of(createdAt)) + + /** + * Sets [Builder.createdAt] to an arbitrary JSON value. + * + * You should usually call [Builder.createdAt] with a well-typed [OffsetDateTime] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun createdAt(createdAt: JsonField) = apply { this.createdAt = createdAt } + + fun data(data: Data) = data(JsonField.of(data)) + + /** + * Sets [Builder.data] to an arbitrary JSON value. + * + * You should usually call [Builder.data] with a well-typed [Data] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun data(data: JsonField) = apply { this.data = data } + + /** Information about the original request that triggered the video transformation. */ + fun request(request: Request) = request(JsonField.of(request)) + + /** + * Sets [Builder.request] to an arbitrary JSON value. + * + * You should usually call [Builder.request] with a well-typed [Request] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun request(request: JsonField) = apply { this.request = request } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [VideoTransformationErrorEvent]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .id() + * .type() + * .createdAt() + * .data() + * .request() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): VideoTransformationErrorEvent = + VideoTransformationErrorEvent( + checkRequired("id", id), + checkRequired("type", type), + checkRequired("createdAt", createdAt), + checkRequired("data", data), + checkRequired("request", request), + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): VideoTransformationErrorEvent = apply { + if (validated) { + return@apply + } + + id() + type() + createdAt() + data().validate() + request().validate() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (id.asKnown().isPresent) 1 else 0) + + (if (type.asKnown().isPresent) 1 else 0) + + (if (createdAt.asKnown().isPresent) 1 else 0) + + (data.asKnown().getOrNull()?.validity() ?: 0) + + (request.asKnown().getOrNull()?.validity() ?: 0) + + class Data + private constructor( + private val asset: JsonField, + private val transformation: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("asset") @ExcludeMissing asset: JsonField = JsonMissing.of(), + @JsonProperty("transformation") + @ExcludeMissing + transformation: JsonField = JsonMissing.of(), + ) : this(asset, transformation, mutableMapOf()) + + /** + * Information about the source video asset being transformed. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun asset(): Asset = asset.getRequired("asset") + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun transformation(): Transformation = transformation.getRequired("transformation") + + /** + * Returns the raw JSON value of [asset]. + * + * Unlike [asset], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("asset") @ExcludeMissing fun _asset(): JsonField = asset + + /** + * Returns the raw JSON value of [transformation]. + * + * Unlike [transformation], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("transformation") + @ExcludeMissing + fun _transformation(): JsonField = transformation + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Data]. + * + * The following fields are required: + * ```java + * .asset() + * .transformation() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Data]. */ + class Builder internal constructor() { + + private var asset: JsonField? = null + private var transformation: JsonField? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(data: Data) = apply { + asset = data.asset + transformation = data.transformation + additionalProperties = data.additionalProperties.toMutableMap() + } + + /** Information about the source video asset being transformed. */ + fun asset(asset: Asset) = asset(JsonField.of(asset)) + + /** + * Sets [Builder.asset] to an arbitrary JSON value. + * + * You should usually call [Builder.asset] with a well-typed [Asset] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun asset(asset: JsonField) = apply { this.asset = asset } + + fun transformation(transformation: Transformation) = + transformation(JsonField.of(transformation)) + + /** + * Sets [Builder.transformation] to an arbitrary JSON value. + * + * You should usually call [Builder.transformation] with a well-typed [Transformation] + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun transformation(transformation: JsonField) = apply { + this.transformation = transformation + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Data]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .asset() + * .transformation() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Data = + Data( + checkRequired("asset", asset), + checkRequired("transformation", transformation), + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Data = apply { + if (validated) { + return@apply + } + + asset().validate() + transformation().validate() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (asset.asKnown().getOrNull()?.validity() ?: 0) + + (transformation.asKnown().getOrNull()?.validity() ?: 0) + + /** Information about the source video asset being transformed. */ + class Asset + private constructor( + private val url: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("url") @ExcludeMissing url: JsonField = JsonMissing.of() + ) : this(url, mutableMapOf()) + + /** + * URL to download or access the source video file. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected + * value). + */ + fun url(): String = url.getRequired("url") + + /** + * Returns the raw JSON value of [url]. + * + * Unlike [url], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("url") @ExcludeMissing fun _url(): JsonField = url + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Asset]. + * + * The following fields are required: + * ```java + * .url() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Asset]. */ + class Builder internal constructor() { + + private var url: JsonField? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(asset: Asset) = apply { + url = asset.url + additionalProperties = asset.additionalProperties.toMutableMap() + } + + /** URL to download or access the source video file. */ + fun url(url: String) = url(JsonField.of(url)) + + /** + * Sets [Builder.url] to an arbitrary JSON value. + * + * You should usually call [Builder.url] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun url(url: JsonField) = apply { this.url = url } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Asset]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .url() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Asset = + Asset(checkRequired("url", url), additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Asset = apply { + if (validated) { + return@apply + } + + url() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = (if (url.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Asset && + url == other.url && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(url, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "Asset{url=$url, additionalProperties=$additionalProperties}" + } + + class Transformation + private constructor( + private val type: JsonField, + private val error: JsonField, + private val options: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("type") @ExcludeMissing type: JsonField = JsonMissing.of(), + @JsonProperty("error") @ExcludeMissing error: JsonField = JsonMissing.of(), + @JsonProperty("options") + @ExcludeMissing + options: JsonField = JsonMissing.of(), + ) : this(type, error, options, mutableMapOf()) + + /** + * Type of video transformation: + * - `video-transformation`: Standard video processing (resize, format conversion, etc.) + * - `gif-to-video`: Convert animated GIF to video format + * - `video-thumbnail`: Generate thumbnail image from video + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected + * value). + */ + fun type(): Type = type.getRequired("type") + + /** + * Details about the transformation error. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun error(): Optional = error.getOptional("error") + + /** + * Configuration options for video transformations. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun options(): Optional = options.getOptional("options") + + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + + /** + * Returns the raw JSON value of [error]. + * + * Unlike [error], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("error") @ExcludeMissing fun _error(): JsonField = error + + /** + * Returns the raw JSON value of [options]. + * + * Unlike [options], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("options") @ExcludeMissing fun _options(): JsonField = options + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Transformation]. + * + * The following fields are required: + * ```java + * .type() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Transformation]. */ + class Builder internal constructor() { + + private var type: JsonField? = null + private var error: JsonField = JsonMissing.of() + private var options: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(transformation: Transformation) = apply { + type = transformation.type + error = transformation.error + options = transformation.options + additionalProperties = transformation.additionalProperties.toMutableMap() + } + + /** + * Type of video transformation: + * - `video-transformation`: Standard video processing (resize, format conversion, + * etc.) + * - `gif-to-video`: Convert animated GIF to video format + * - `video-thumbnail`: Generate thumbnail image from video + */ + fun type(type: Type) = type(JsonField.of(type)) + + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [Type] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun type(type: JsonField) = apply { this.type = type } + + /** Details about the transformation error. */ + fun error(error: Error) = error(JsonField.of(error)) + + /** + * Sets [Builder.error] to an arbitrary JSON value. + * + * You should usually call [Builder.error] with a well-typed [Error] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun error(error: JsonField) = apply { this.error = error } + + /** Configuration options for video transformations. */ + fun options(options: Options) = options(JsonField.of(options)) + + /** + * Sets [Builder.options] to an arbitrary JSON value. + * + * You should usually call [Builder.options] with a well-typed [Options] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun options(options: JsonField) = apply { this.options = options } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Transformation]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .type() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Transformation = + Transformation( + checkRequired("type", type), + error, + options, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Transformation = apply { + if (validated) { + return@apply + } + + type().validate() + error().ifPresent { it.validate() } + options().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (type.asKnown().getOrNull()?.validity() ?: 0) + + (error.asKnown().getOrNull()?.validity() ?: 0) + + (options.asKnown().getOrNull()?.validity() ?: 0) + + /** + * Type of video transformation: + * - `video-transformation`: Standard video processing (resize, format conversion, etc.) + * - `gif-to-video`: Convert animated GIF to video format + * - `video-thumbnail`: Generate thumbnail image from video + */ + class Type @JsonCreator private constructor(private val value: JsonField) : + Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that + * doesn't match any known member, and you want to know that value. For example, if + * the SDK is on an older version than the API, then the API may respond with new + * members that the SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val VIDEO_TRANSFORMATION = of("video-transformation") + + @JvmField val GIF_TO_VIDEO = of("gif-to-video") + + @JvmField val VIDEO_THUMBNAIL = of("video-thumbnail") + + @JvmStatic fun of(value: String) = Type(JsonField.of(value)) + } + + /** An enum containing [Type]'s known values. */ + enum class Known { + VIDEO_TRANSFORMATION, + GIF_TO_VIDEO, + VIDEO_THUMBNAIL, + } + + /** + * An enum containing [Type]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [Type] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, + * if the SDK is on an older version than the API, then the API may respond with + * new members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + VIDEO_TRANSFORMATION, + GIF_TO_VIDEO, + VIDEO_THUMBNAIL, + /** + * An enum member indicating that [Type] was instantiated with an unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if + * you want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + VIDEO_TRANSFORMATION -> Value.VIDEO_TRANSFORMATION + GIF_TO_VIDEO -> Value.GIF_TO_VIDEO + VIDEO_THUMBNAIL -> Value.VIDEO_THUMBNAIL + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and + * don't want to throw for the unknown case. + * + * @throws ImageKitInvalidDataException if this class instance's value is a not a + * known member. + */ + fun known(): Known = + when (this) { + VIDEO_TRANSFORMATION -> Known.VIDEO_TRANSFORMATION + GIF_TO_VIDEO -> Known.GIF_TO_VIDEO + VIDEO_THUMBNAIL -> Known.VIDEO_THUMBNAIL + else -> throw ImageKitInvalidDataException("Unknown Type: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for + * debugging and generally doesn't throw. + * + * @throws ImageKitInvalidDataException if this class instance's value does not have + * the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + ImageKitInvalidDataException("Value is not a String") + } + + private var validated: Boolean = false + + fun validate(): Type = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Type && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + /** Details about the transformation error. */ + class Error + private constructor( + private val reason: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("reason") + @ExcludeMissing + reason: JsonField = JsonMissing.of() + ) : this(reason, mutableMapOf()) + + /** + * Specific reason for the transformation failure: + * - `encoding_failed`: Error during video encoding process + * - `download_failed`: Could not download source video + * - `internal_server_error`: Unexpected server error + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or + * is unexpectedly missing or null (e.g. if the server responded with an + * unexpected value). + */ + fun reason(): Reason = reason.getRequired("reason") + + /** + * Returns the raw JSON value of [reason]. + * + * Unlike [reason], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("reason") @ExcludeMissing fun _reason(): JsonField = reason + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Error]. + * + * The following fields are required: + * ```java + * .reason() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Error]. */ + class Builder internal constructor() { + + private var reason: JsonField? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(error: Error) = apply { + reason = error.reason + additionalProperties = error.additionalProperties.toMutableMap() + } + + /** + * Specific reason for the transformation failure: + * - `encoding_failed`: Error during video encoding process + * - `download_failed`: Could not download source video + * - `internal_server_error`: Unexpected server error + */ + fun reason(reason: Reason) = reason(JsonField.of(reason)) + + /** + * Sets [Builder.reason] to an arbitrary JSON value. + * + * You should usually call [Builder.reason] with a well-typed [Reason] value + * instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun reason(reason: JsonField) = apply { this.reason = reason } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Error]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .reason() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Error = + Error(checkRequired("reason", reason), additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Error = apply { + if (validated) { + return@apply + } + + reason().validate() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = (reason.asKnown().getOrNull()?.validity() ?: 0) + + /** + * Specific reason for the transformation failure: + * - `encoding_failed`: Error during video encoding process + * - `download_failed`: Could not download source video + * - `internal_server_error`: Unexpected server error + */ + class Reason + @JsonCreator + private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that + * doesn't match any known member, and you want to know that value. For example, + * if the SDK is on an older version than the API, then the API may respond with + * new members that the SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue + fun _value(): JsonField = value + + companion object { + + @JvmField val ENCODING_FAILED = of("encoding_failed") + + @JvmField val DOWNLOAD_FAILED = of("download_failed") + + @JvmField val INTERNAL_SERVER_ERROR = of("internal_server_error") + + @JvmStatic fun of(value: String) = Reason(JsonField.of(value)) + } + + /** An enum containing [Reason]'s known values. */ + enum class Known { + ENCODING_FAILED, + DOWNLOAD_FAILED, + INTERNAL_SERVER_ERROR, + } + + /** + * An enum containing [Reason]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [Reason] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For + * example, if the SDK is on an older version than the API, then the API may + * respond with new members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + ENCODING_FAILED, + DOWNLOAD_FAILED, + INTERNAL_SERVER_ERROR, + /** + * An enum member indicating that [Reason] was instantiated with an unknown + * value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or + * if you want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + ENCODING_FAILED -> Value.ENCODING_FAILED + DOWNLOAD_FAILED -> Value.DOWNLOAD_FAILED + INTERNAL_SERVER_ERROR -> Value.INTERNAL_SERVER_ERROR + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known + * and don't want to throw for the unknown case. + * + * @throws ImageKitInvalidDataException if this class instance's value is a not + * a known member. + */ + fun known(): Known = + when (this) { + ENCODING_FAILED -> Known.ENCODING_FAILED + DOWNLOAD_FAILED -> Known.DOWNLOAD_FAILED + INTERNAL_SERVER_ERROR -> Known.INTERNAL_SERVER_ERROR + else -> throw ImageKitInvalidDataException("Unknown Reason: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for + * debugging and generally doesn't throw. + * + * @throws ImageKitInvalidDataException if this class instance's value does not + * have the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + ImageKitInvalidDataException("Value is not a String") + } + + private var validated: Boolean = false + + fun validate(): Reason = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Reason && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Error && + reason == other.reason && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(reason, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Error{reason=$reason, additionalProperties=$additionalProperties}" + } + + /** Configuration options for video transformations. */ + class Options + private constructor( + private val audioCodec: JsonField, + private val autoRotate: JsonField, + private val format: JsonField, + private val quality: JsonField, + private val streamProtocol: JsonField, + private val variants: JsonField>, + private val videoCodec: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("audio_codec") + @ExcludeMissing + audioCodec: JsonField = JsonMissing.of(), + @JsonProperty("auto_rotate") + @ExcludeMissing + autoRotate: JsonField = JsonMissing.of(), + @JsonProperty("format") + @ExcludeMissing + format: JsonField = JsonMissing.of(), + @JsonProperty("quality") + @ExcludeMissing + quality: JsonField = JsonMissing.of(), + @JsonProperty("stream_protocol") + @ExcludeMissing + streamProtocol: JsonField = JsonMissing.of(), + @JsonProperty("variants") + @ExcludeMissing + variants: JsonField> = JsonMissing.of(), + @JsonProperty("video_codec") + @ExcludeMissing + videoCodec: JsonField = JsonMissing.of(), + ) : this( + audioCodec, + autoRotate, + format, + quality, + streamProtocol, + variants, + videoCodec, + mutableMapOf(), + ) + + /** + * Audio codec used for encoding (aac or opus). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun audioCodec(): Optional = audioCodec.getOptional("audio_codec") + + /** + * Whether to automatically rotate the video based on metadata. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun autoRotate(): Optional = autoRotate.getOptional("auto_rotate") + + /** + * Output format for the transformed video or thumbnail. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun format(): Optional = format.getOptional("format") + + /** + * Quality setting for the output video. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun quality(): Optional = quality.getOptional("quality") + + /** + * Streaming protocol for adaptive bitrate streaming. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun streamProtocol(): Optional = + streamProtocol.getOptional("stream_protocol") + + /** + * Array of quality representations for adaptive bitrate streaming. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun variants(): Optional> = variants.getOptional("variants") + + /** + * Video codec used for encoding (h264, vp9, or av1). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun videoCodec(): Optional = videoCodec.getOptional("video_codec") + + /** + * Returns the raw JSON value of [audioCodec]. + * + * Unlike [audioCodec], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("audio_codec") + @ExcludeMissing + fun _audioCodec(): JsonField = audioCodec + + /** + * Returns the raw JSON value of [autoRotate]. + * + * Unlike [autoRotate], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("auto_rotate") + @ExcludeMissing + fun _autoRotate(): JsonField = autoRotate + + /** + * Returns the raw JSON value of [format]. + * + * Unlike [format], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("format") @ExcludeMissing fun _format(): JsonField = format + + /** + * Returns the raw JSON value of [quality]. + * + * Unlike [quality], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("quality") @ExcludeMissing fun _quality(): JsonField = quality + + /** + * Returns the raw JSON value of [streamProtocol]. + * + * Unlike [streamProtocol], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("stream_protocol") + @ExcludeMissing + fun _streamProtocol(): JsonField = streamProtocol + + /** + * Returns the raw JSON value of [variants]. + * + * Unlike [variants], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("variants") + @ExcludeMissing + fun _variants(): JsonField> = variants + + /** + * Returns the raw JSON value of [videoCodec]. + * + * Unlike [videoCodec], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("video_codec") + @ExcludeMissing + fun _videoCodec(): JsonField = videoCodec + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Options]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Options]. */ + class Builder internal constructor() { + + private var audioCodec: JsonField = JsonMissing.of() + private var autoRotate: JsonField = JsonMissing.of() + private var format: JsonField = JsonMissing.of() + private var quality: JsonField = JsonMissing.of() + private var streamProtocol: JsonField = JsonMissing.of() + private var variants: JsonField>? = null + private var videoCodec: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(options: Options) = apply { + audioCodec = options.audioCodec + autoRotate = options.autoRotate + format = options.format + quality = options.quality + streamProtocol = options.streamProtocol + variants = options.variants.map { it.toMutableList() } + videoCodec = options.videoCodec + additionalProperties = options.additionalProperties.toMutableMap() + } + + /** Audio codec used for encoding (aac or opus). */ + fun audioCodec(audioCodec: AudioCodec) = audioCodec(JsonField.of(audioCodec)) + + /** + * Sets [Builder.audioCodec] to an arbitrary JSON value. + * + * You should usually call [Builder.audioCodec] with a well-typed [AudioCodec] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun audioCodec(audioCodec: JsonField) = apply { + this.audioCodec = audioCodec + } + + /** Whether to automatically rotate the video based on metadata. */ + fun autoRotate(autoRotate: Boolean) = autoRotate(JsonField.of(autoRotate)) + + /** + * Sets [Builder.autoRotate] to an arbitrary JSON value. + * + * You should usually call [Builder.autoRotate] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun autoRotate(autoRotate: JsonField) = apply { + this.autoRotate = autoRotate + } + + /** Output format for the transformed video or thumbnail. */ + fun format(format: Format) = format(JsonField.of(format)) + + /** + * Sets [Builder.format] to an arbitrary JSON value. + * + * You should usually call [Builder.format] with a well-typed [Format] value + * instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun format(format: JsonField) = apply { this.format = format } + + /** Quality setting for the output video. */ + fun quality(quality: Long) = quality(JsonField.of(quality)) + + /** + * Sets [Builder.quality] to an arbitrary JSON value. + * + * You should usually call [Builder.quality] with a well-typed [Long] value + * instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun quality(quality: JsonField) = apply { this.quality = quality } + + /** Streaming protocol for adaptive bitrate streaming. */ + fun streamProtocol(streamProtocol: StreamProtocol) = + streamProtocol(JsonField.of(streamProtocol)) + + /** + * Sets [Builder.streamProtocol] to an arbitrary JSON value. + * + * You should usually call [Builder.streamProtocol] with a well-typed + * [StreamProtocol] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ + fun streamProtocol(streamProtocol: JsonField) = apply { + this.streamProtocol = streamProtocol + } + + /** Array of quality representations for adaptive bitrate streaming. */ + fun variants(variants: List) = variants(JsonField.of(variants)) + + /** + * Sets [Builder.variants] to an arbitrary JSON value. + * + * You should usually call [Builder.variants] with a well-typed `List` + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun variants(variants: JsonField>) = apply { + this.variants = variants.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [variants]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addVariant(variant: String) = apply { + variants = + (variants ?: JsonField.of(mutableListOf())).also { + checkKnown("variants", it).add(variant) + } + } + + /** Video codec used for encoding (h264, vp9, or av1). */ + fun videoCodec(videoCodec: VideoCodec) = videoCodec(JsonField.of(videoCodec)) + + /** + * Sets [Builder.videoCodec] to an arbitrary JSON value. + * + * You should usually call [Builder.videoCodec] with a well-typed [VideoCodec] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun videoCodec(videoCodec: JsonField) = apply { + this.videoCodec = videoCodec + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Options]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Options = + Options( + audioCodec, + autoRotate, + format, + quality, + streamProtocol, + (variants ?: JsonMissing.of()).map { it.toImmutable() }, + videoCodec, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Options = apply { + if (validated) { + return@apply + } + + audioCodec().ifPresent { it.validate() } + autoRotate() + format().ifPresent { it.validate() } + quality() + streamProtocol().ifPresent { it.validate() } + variants() + videoCodec().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (audioCodec.asKnown().getOrNull()?.validity() ?: 0) + + (if (autoRotate.asKnown().isPresent) 1 else 0) + + (format.asKnown().getOrNull()?.validity() ?: 0) + + (if (quality.asKnown().isPresent) 1 else 0) + + (streamProtocol.asKnown().getOrNull()?.validity() ?: 0) + + (variants.asKnown().getOrNull()?.size ?: 0) + + (videoCodec.asKnown().getOrNull()?.validity() ?: 0) + + /** Audio codec used for encoding (aac or opus). */ + class AudioCodec + @JsonCreator + private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that + * doesn't match any known member, and you want to know that value. For example, + * if the SDK is on an older version than the API, then the API may respond with + * new members that the SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue + fun _value(): JsonField = value + + companion object { + + @JvmField val AAC = of("aac") + + @JvmField val OPUS = of("opus") + + @JvmStatic fun of(value: String) = AudioCodec(JsonField.of(value)) + } + + /** An enum containing [AudioCodec]'s known values. */ + enum class Known { + AAC, + OPUS, + } + + /** + * An enum containing [AudioCodec]'s known values, as well as an [_UNKNOWN] + * member. + * + * An instance of [AudioCodec] can contain an unknown value in a couple of + * cases: + * - It was deserialized from data that doesn't match any known member. For + * example, if the SDK is on an older version than the API, then the API may + * respond with new members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + AAC, + OPUS, + /** + * An enum member indicating that [AudioCodec] was instantiated with an + * unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or + * if you want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + AAC -> Value.AAC + OPUS -> Value.OPUS + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known + * and don't want to throw for the unknown case. + * + * @throws ImageKitInvalidDataException if this class instance's value is a not + * a known member. + */ + fun known(): Known = + when (this) { + AAC -> Known.AAC + OPUS -> Known.OPUS + else -> throw ImageKitInvalidDataException("Unknown AudioCodec: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for + * debugging and generally doesn't throw. + * + * @throws ImageKitInvalidDataException if this class instance's value does not + * have the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + ImageKitInvalidDataException("Value is not a String") + } + + private var validated: Boolean = false + + fun validate(): AudioCodec = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is AudioCodec && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + /** Output format for the transformed video or thumbnail. */ + class Format + @JsonCreator + private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that + * doesn't match any known member, and you want to know that value. For example, + * if the SDK is on an older version than the API, then the API may respond with + * new members that the SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue + fun _value(): JsonField = value + + companion object { + + @JvmField val MP4 = of("mp4") + + @JvmField val WEBM = of("webm") + + @JvmField val JPG = of("jpg") + + @JvmField val PNG = of("png") + + @JvmField val WEBP = of("webp") + + @JvmStatic fun of(value: String) = Format(JsonField.of(value)) + } + + /** An enum containing [Format]'s known values. */ + enum class Known { + MP4, + WEBM, + JPG, + PNG, + WEBP, + } + + /** + * An enum containing [Format]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [Format] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For + * example, if the SDK is on an older version than the API, then the API may + * respond with new members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + MP4, + WEBM, + JPG, + PNG, + WEBP, + /** + * An enum member indicating that [Format] was instantiated with an unknown + * value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or + * if you want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + MP4 -> Value.MP4 + WEBM -> Value.WEBM + JPG -> Value.JPG + PNG -> Value.PNG + WEBP -> Value.WEBP + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known + * and don't want to throw for the unknown case. + * + * @throws ImageKitInvalidDataException if this class instance's value is a not + * a known member. + */ + fun known(): Known = + when (this) { + MP4 -> Known.MP4 + WEBM -> Known.WEBM + JPG -> Known.JPG + PNG -> Known.PNG + WEBP -> Known.WEBP + else -> throw ImageKitInvalidDataException("Unknown Format: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for + * debugging and generally doesn't throw. + * + * @throws ImageKitInvalidDataException if this class instance's value does not + * have the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + ImageKitInvalidDataException("Value is not a String") + } + + private var validated: Boolean = false + + fun validate(): Format = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Format && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + /** Streaming protocol for adaptive bitrate streaming. */ + class StreamProtocol + @JsonCreator + private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that + * doesn't match any known member, and you want to know that value. For example, + * if the SDK is on an older version than the API, then the API may respond with + * new members that the SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue + fun _value(): JsonField = value + + companion object { + + @JvmField val HLS = of("HLS") + + @JvmField val DASH = of("DASH") + + @JvmStatic fun of(value: String) = StreamProtocol(JsonField.of(value)) + } + + /** An enum containing [StreamProtocol]'s known values. */ + enum class Known { + HLS, + DASH, + } + + /** + * An enum containing [StreamProtocol]'s known values, as well as an [_UNKNOWN] + * member. + * + * An instance of [StreamProtocol] can contain an unknown value in a couple of + * cases: + * - It was deserialized from data that doesn't match any known member. For + * example, if the SDK is on an older version than the API, then the API may + * respond with new members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + HLS, + DASH, + /** + * An enum member indicating that [StreamProtocol] was instantiated with an + * unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or + * if you want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + HLS -> Value.HLS + DASH -> Value.DASH + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known + * and don't want to throw for the unknown case. + * + * @throws ImageKitInvalidDataException if this class instance's value is a not + * a known member. + */ + fun known(): Known = + when (this) { + HLS -> Known.HLS + DASH -> Known.DASH + else -> + throw ImageKitInvalidDataException("Unknown StreamProtocol: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for + * debugging and generally doesn't throw. + * + * @throws ImageKitInvalidDataException if this class instance's value does not + * have the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + ImageKitInvalidDataException("Value is not a String") + } + + private var validated: Boolean = false + + fun validate(): StreamProtocol = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is StreamProtocol && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + /** Video codec used for encoding (h264, vp9, or av1). */ + class VideoCodec + @JsonCreator + private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that + * doesn't match any known member, and you want to know that value. For example, + * if the SDK is on an older version than the API, then the API may respond with + * new members that the SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue + fun _value(): JsonField = value + + companion object { + + @JvmField val H264 = of("h264") + + @JvmField val VP9 = of("vp9") + + @JvmField val AV1 = of("av1") + + @JvmStatic fun of(value: String) = VideoCodec(JsonField.of(value)) + } + + /** An enum containing [VideoCodec]'s known values. */ + enum class Known { + H264, + VP9, + AV1, + } + + /** + * An enum containing [VideoCodec]'s known values, as well as an [_UNKNOWN] + * member. + * + * An instance of [VideoCodec] can contain an unknown value in a couple of + * cases: + * - It was deserialized from data that doesn't match any known member. For + * example, if the SDK is on an older version than the API, then the API may + * respond with new members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + H264, + VP9, + AV1, + /** + * An enum member indicating that [VideoCodec] was instantiated with an + * unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or + * if you want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + H264 -> Value.H264 + VP9 -> Value.VP9 + AV1 -> Value.AV1 + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known + * and don't want to throw for the unknown case. + * + * @throws ImageKitInvalidDataException if this class instance's value is a not + * a known member. + */ + fun known(): Known = + when (this) { + H264 -> Known.H264 + VP9 -> Known.VP9 + AV1 -> Known.AV1 + else -> throw ImageKitInvalidDataException("Unknown VideoCodec: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for + * debugging and generally doesn't throw. + * + * @throws ImageKitInvalidDataException if this class instance's value does not + * have the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + ImageKitInvalidDataException("Value is not a String") + } + + private var validated: Boolean = false + + fun validate(): VideoCodec = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is VideoCodec && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Options && + audioCodec == other.audioCodec && + autoRotate == other.autoRotate && + format == other.format && + quality == other.quality && + streamProtocol == other.streamProtocol && + variants == other.variants && + videoCodec == other.videoCodec && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + audioCodec, + autoRotate, + format, + quality, + streamProtocol, + variants, + videoCodec, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Options{audioCodec=$audioCodec, autoRotate=$autoRotate, format=$format, quality=$quality, streamProtocol=$streamProtocol, variants=$variants, videoCodec=$videoCodec, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Transformation && + type == other.type && + error == other.error && + options == other.options && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(type, error, options, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Transformation{type=$type, error=$error, options=$options, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Data && + asset == other.asset && + transformation == other.transformation && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(asset, transformation, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Data{asset=$asset, transformation=$transformation, additionalProperties=$additionalProperties}" + } + + /** Information about the original request that triggered the video transformation. */ + class Request + private constructor( + private val url: JsonField, + private val xRequestId: JsonField, + private val userAgent: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("url") @ExcludeMissing url: JsonField = JsonMissing.of(), + @JsonProperty("x_request_id") + @ExcludeMissing + xRequestId: JsonField = JsonMissing.of(), + @JsonProperty("user_agent") + @ExcludeMissing + userAgent: JsonField = JsonMissing.of(), + ) : this(url, xRequestId, userAgent, mutableMapOf()) + + /** + * Full URL of the transformation request that was submitted. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun url(): String = url.getRequired("url") + + /** + * Unique identifier for the originating transformation request. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun xRequestId(): String = xRequestId.getRequired("x_request_id") + + /** + * User-Agent header from the original request that triggered the transformation. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun userAgent(): Optional = userAgent.getOptional("user_agent") + + /** + * Returns the raw JSON value of [url]. + * + * Unlike [url], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("url") @ExcludeMissing fun _url(): JsonField = url + + /** + * Returns the raw JSON value of [xRequestId]. + * + * Unlike [xRequestId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("x_request_id") + @ExcludeMissing + fun _xRequestId(): JsonField = xRequestId + + /** + * Returns the raw JSON value of [userAgent]. + * + * Unlike [userAgent], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("user_agent") @ExcludeMissing fun _userAgent(): JsonField = userAgent + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Request]. + * + * The following fields are required: + * ```java + * .url() + * .xRequestId() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Request]. */ + class Builder internal constructor() { + + private var url: JsonField? = null + private var xRequestId: JsonField? = null + private var userAgent: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(request: Request) = apply { + url = request.url + xRequestId = request.xRequestId + userAgent = request.userAgent + additionalProperties = request.additionalProperties.toMutableMap() + } + + /** Full URL of the transformation request that was submitted. */ + fun url(url: String) = url(JsonField.of(url)) + + /** + * Sets [Builder.url] to an arbitrary JSON value. + * + * You should usually call [Builder.url] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun url(url: JsonField) = apply { this.url = url } + + /** Unique identifier for the originating transformation request. */ + fun xRequestId(xRequestId: String) = xRequestId(JsonField.of(xRequestId)) + + /** + * Sets [Builder.xRequestId] to an arbitrary JSON value. + * + * You should usually call [Builder.xRequestId] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun xRequestId(xRequestId: JsonField) = apply { this.xRequestId = xRequestId } + + /** User-Agent header from the original request that triggered the transformation. */ + fun userAgent(userAgent: String) = userAgent(JsonField.of(userAgent)) + + /** + * Sets [Builder.userAgent] to an arbitrary JSON value. + * + * You should usually call [Builder.userAgent] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun userAgent(userAgent: JsonField) = apply { this.userAgent = userAgent } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Request]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .url() + * .xRequestId() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Request = + Request( + checkRequired("url", url), + checkRequired("xRequestId", xRequestId), + userAgent, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Request = apply { + if (validated) { + return@apply + } + + url() + xRequestId() + userAgent() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (url.asKnown().isPresent) 1 else 0) + + (if (xRequestId.asKnown().isPresent) 1 else 0) + + (if (userAgent.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Request && + url == other.url && + xRequestId == other.xRequestId && + userAgent == other.userAgent && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(url, xRequestId, userAgent, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Request{url=$url, xRequestId=$xRequestId, userAgent=$userAgent, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is VideoTransformationErrorEvent && + id == other.id && + type == other.type && + createdAt == other.createdAt && + data == other.data && + request == other.request && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(id, type, createdAt, data, request, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "VideoTransformationErrorEvent{id=$id, type=$type, createdAt=$createdAt, data=$data, request=$request, additionalProperties=$additionalProperties}" +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/webhooks/VideoTransformationReadyEvent.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/webhooks/VideoTransformationReadyEvent.kt new file mode 100644 index 0000000..005fcea --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/models/webhooks/VideoTransformationReadyEvent.kt @@ -0,0 +1,3082 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.webhooks + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.imagekit.api.core.Enum +import com.imagekit.api.core.ExcludeMissing +import com.imagekit.api.core.JsonField +import com.imagekit.api.core.JsonMissing +import com.imagekit.api.core.JsonValue +import com.imagekit.api.core.checkKnown +import com.imagekit.api.core.checkRequired +import com.imagekit.api.core.toImmutable +import com.imagekit.api.errors.ImageKitInvalidDataException +import java.time.OffsetDateTime +import java.util.Collections +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** + * Triggered when video encoding is finished and the transformed resource is ready to be served. + * This is the key event to listen for - update your database or CMS flags when you receive this so + * your application can start showing the transformed video to users. + */ +class VideoTransformationReadyEvent +private constructor( + private val id: JsonField, + private val type: JsonField, + private val createdAt: JsonField, + private val data: JsonField, + private val request: JsonField, + private val timings: JsonField, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonField = JsonMissing.of(), + @JsonProperty("created_at") + @ExcludeMissing + createdAt: JsonField = JsonMissing.of(), + @JsonProperty("data") @ExcludeMissing data: JsonField = JsonMissing.of(), + @JsonProperty("request") @ExcludeMissing request: JsonField = JsonMissing.of(), + @JsonProperty("timings") @ExcludeMissing timings: JsonField = JsonMissing.of(), + ) : this(id, type, createdAt, data, request, timings, mutableMapOf()) + + fun toBaseWebhookEvent(): BaseWebhookEvent = + BaseWebhookEvent.builder().id(id).type(type).build() + + /** + * Unique identifier for the event. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun id(): String = id.getRequired("id") + + /** + * The type of webhook event. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun type(): String = type.getRequired("type") + + /** + * Timestamp when the event was created in ISO8601 format. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun createdAt(): OffsetDateTime = createdAt.getRequired("created_at") + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun data(): Data = data.getRequired("data") + + /** + * Information about the original request that triggered the video transformation. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun request(): Request = request.getRequired("request") + + /** + * Performance metrics for the transformation process. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun timings(): Optional = timings.getOptional("timings") + + /** + * Returns the raw JSON value of [id]. + * + * Unlike [id], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id + + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + + /** + * Returns the raw JSON value of [createdAt]. + * + * Unlike [createdAt], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("created_at") + @ExcludeMissing + fun _createdAt(): JsonField = createdAt + + /** + * Returns the raw JSON value of [data]. + * + * Unlike [data], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("data") @ExcludeMissing fun _data(): JsonField = data + + /** + * Returns the raw JSON value of [request]. + * + * Unlike [request], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("request") @ExcludeMissing fun _request(): JsonField = request + + /** + * Returns the raw JSON value of [timings]. + * + * Unlike [timings], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("timings") @ExcludeMissing fun _timings(): JsonField = timings + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [VideoTransformationReadyEvent]. + * + * The following fields are required: + * ```java + * .id() + * .type() + * .createdAt() + * .data() + * .request() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [VideoTransformationReadyEvent]. */ + class Builder internal constructor() { + + private var id: JsonField? = null + private var type: JsonField? = null + private var createdAt: JsonField? = null + private var data: JsonField? = null + private var request: JsonField? = null + private var timings: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(videoTransformationReadyEvent: VideoTransformationReadyEvent) = apply { + id = videoTransformationReadyEvent.id + type = videoTransformationReadyEvent.type + createdAt = videoTransformationReadyEvent.createdAt + data = videoTransformationReadyEvent.data + request = videoTransformationReadyEvent.request + timings = videoTransformationReadyEvent.timings + additionalProperties = videoTransformationReadyEvent.additionalProperties.toMutableMap() + } + + /** Unique identifier for the event. */ + fun id(id: String) = id(JsonField.of(id)) + + /** + * Sets [Builder.id] to an arbitrary JSON value. + * + * You should usually call [Builder.id] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun id(id: JsonField) = apply { this.id = id } + + /** The type of webhook event. */ + fun type(type: String) = type(JsonField.of(type)) + + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun type(type: JsonField) = apply { this.type = type } + + /** Timestamp when the event was created in ISO8601 format. */ + fun createdAt(createdAt: OffsetDateTime) = createdAt(JsonField.of(createdAt)) + + /** + * Sets [Builder.createdAt] to an arbitrary JSON value. + * + * You should usually call [Builder.createdAt] with a well-typed [OffsetDateTime] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun createdAt(createdAt: JsonField) = apply { this.createdAt = createdAt } + + fun data(data: Data) = data(JsonField.of(data)) + + /** + * Sets [Builder.data] to an arbitrary JSON value. + * + * You should usually call [Builder.data] with a well-typed [Data] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun data(data: JsonField) = apply { this.data = data } + + /** Information about the original request that triggered the video transformation. */ + fun request(request: Request) = request(JsonField.of(request)) + + /** + * Sets [Builder.request] to an arbitrary JSON value. + * + * You should usually call [Builder.request] with a well-typed [Request] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun request(request: JsonField) = apply { this.request = request } + + /** Performance metrics for the transformation process. */ + fun timings(timings: Timings) = timings(JsonField.of(timings)) + + /** + * Sets [Builder.timings] to an arbitrary JSON value. + * + * You should usually call [Builder.timings] with a well-typed [Timings] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun timings(timings: JsonField) = apply { this.timings = timings } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [VideoTransformationReadyEvent]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .id() + * .type() + * .createdAt() + * .data() + * .request() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): VideoTransformationReadyEvent = + VideoTransformationReadyEvent( + checkRequired("id", id), + checkRequired("type", type), + checkRequired("createdAt", createdAt), + checkRequired("data", data), + checkRequired("request", request), + timings, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): VideoTransformationReadyEvent = apply { + if (validated) { + return@apply + } + + id() + type() + createdAt() + data().validate() + request().validate() + timings().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (id.asKnown().isPresent) 1 else 0) + + (if (type.asKnown().isPresent) 1 else 0) + + (if (createdAt.asKnown().isPresent) 1 else 0) + + (data.asKnown().getOrNull()?.validity() ?: 0) + + (request.asKnown().getOrNull()?.validity() ?: 0) + + (timings.asKnown().getOrNull()?.validity() ?: 0) + + class Data + private constructor( + private val asset: JsonField, + private val transformation: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("asset") @ExcludeMissing asset: JsonField = JsonMissing.of(), + @JsonProperty("transformation") + @ExcludeMissing + transformation: JsonField = JsonMissing.of(), + ) : this(asset, transformation, mutableMapOf()) + + /** + * Information about the source video asset being transformed. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun asset(): Asset = asset.getRequired("asset") + + /** + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun transformation(): Transformation = transformation.getRequired("transformation") + + /** + * Returns the raw JSON value of [asset]. + * + * Unlike [asset], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("asset") @ExcludeMissing fun _asset(): JsonField = asset + + /** + * Returns the raw JSON value of [transformation]. + * + * Unlike [transformation], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("transformation") + @ExcludeMissing + fun _transformation(): JsonField = transformation + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Data]. + * + * The following fields are required: + * ```java + * .asset() + * .transformation() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Data]. */ + class Builder internal constructor() { + + private var asset: JsonField? = null + private var transformation: JsonField? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(data: Data) = apply { + asset = data.asset + transformation = data.transformation + additionalProperties = data.additionalProperties.toMutableMap() + } + + /** Information about the source video asset being transformed. */ + fun asset(asset: Asset) = asset(JsonField.of(asset)) + + /** + * Sets [Builder.asset] to an arbitrary JSON value. + * + * You should usually call [Builder.asset] with a well-typed [Asset] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun asset(asset: JsonField) = apply { this.asset = asset } + + fun transformation(transformation: Transformation) = + transformation(JsonField.of(transformation)) + + /** + * Sets [Builder.transformation] to an arbitrary JSON value. + * + * You should usually call [Builder.transformation] with a well-typed [Transformation] + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun transformation(transformation: JsonField) = apply { + this.transformation = transformation + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Data]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .asset() + * .transformation() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Data = + Data( + checkRequired("asset", asset), + checkRequired("transformation", transformation), + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Data = apply { + if (validated) { + return@apply + } + + asset().validate() + transformation().validate() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (asset.asKnown().getOrNull()?.validity() ?: 0) + + (transformation.asKnown().getOrNull()?.validity() ?: 0) + + /** Information about the source video asset being transformed. */ + class Asset + private constructor( + private val url: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("url") @ExcludeMissing url: JsonField = JsonMissing.of() + ) : this(url, mutableMapOf()) + + /** + * URL to download or access the source video file. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected + * value). + */ + fun url(): String = url.getRequired("url") + + /** + * Returns the raw JSON value of [url]. + * + * Unlike [url], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("url") @ExcludeMissing fun _url(): JsonField = url + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Asset]. + * + * The following fields are required: + * ```java + * .url() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Asset]. */ + class Builder internal constructor() { + + private var url: JsonField? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(asset: Asset) = apply { + url = asset.url + additionalProperties = asset.additionalProperties.toMutableMap() + } + + /** URL to download or access the source video file. */ + fun url(url: String) = url(JsonField.of(url)) + + /** + * Sets [Builder.url] to an arbitrary JSON value. + * + * You should usually call [Builder.url] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun url(url: JsonField) = apply { this.url = url } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Asset]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .url() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Asset = + Asset(checkRequired("url", url), additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Asset = apply { + if (validated) { + return@apply + } + + url() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = (if (url.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Asset && + url == other.url && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(url, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "Asset{url=$url, additionalProperties=$additionalProperties}" + } + + class Transformation + private constructor( + private val type: JsonField, + private val options: JsonField, + private val output: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("type") @ExcludeMissing type: JsonField = JsonMissing.of(), + @JsonProperty("options") + @ExcludeMissing + options: JsonField = JsonMissing.of(), + @JsonProperty("output") @ExcludeMissing output: JsonField = JsonMissing.of(), + ) : this(type, options, output, mutableMapOf()) + + /** + * Type of video transformation: + * - `video-transformation`: Standard video processing (resize, format conversion, etc.) + * - `gif-to-video`: Convert animated GIF to video format + * - `video-thumbnail`: Generate thumbnail image from video + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected + * value). + */ + fun type(): Type = type.getRequired("type") + + /** + * Configuration options for video transformations. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun options(): Optional = options.getOptional("options") + + /** + * Information about the transformed output video. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun output(): Optional = output.getOptional("output") + + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + + /** + * Returns the raw JSON value of [options]. + * + * Unlike [options], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("options") @ExcludeMissing fun _options(): JsonField = options + + /** + * Returns the raw JSON value of [output]. + * + * Unlike [output], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("output") @ExcludeMissing fun _output(): JsonField = output + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Transformation]. + * + * The following fields are required: + * ```java + * .type() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Transformation]. */ + class Builder internal constructor() { + + private var type: JsonField? = null + private var options: JsonField = JsonMissing.of() + private var output: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(transformation: Transformation) = apply { + type = transformation.type + options = transformation.options + output = transformation.output + additionalProperties = transformation.additionalProperties.toMutableMap() + } + + /** + * Type of video transformation: + * - `video-transformation`: Standard video processing (resize, format conversion, + * etc.) + * - `gif-to-video`: Convert animated GIF to video format + * - `video-thumbnail`: Generate thumbnail image from video + */ + fun type(type: Type) = type(JsonField.of(type)) + + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [Type] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun type(type: JsonField) = apply { this.type = type } + + /** Configuration options for video transformations. */ + fun options(options: Options) = options(JsonField.of(options)) + + /** + * Sets [Builder.options] to an arbitrary JSON value. + * + * You should usually call [Builder.options] with a well-typed [Options] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun options(options: JsonField) = apply { this.options = options } + + /** Information about the transformed output video. */ + fun output(output: Output) = output(JsonField.of(output)) + + /** + * Sets [Builder.output] to an arbitrary JSON value. + * + * You should usually call [Builder.output] with a well-typed [Output] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun output(output: JsonField) = apply { this.output = output } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Transformation]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .type() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Transformation = + Transformation( + checkRequired("type", type), + options, + output, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Transformation = apply { + if (validated) { + return@apply + } + + type().validate() + options().ifPresent { it.validate() } + output().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (type.asKnown().getOrNull()?.validity() ?: 0) + + (options.asKnown().getOrNull()?.validity() ?: 0) + + (output.asKnown().getOrNull()?.validity() ?: 0) + + /** + * Type of video transformation: + * - `video-transformation`: Standard video processing (resize, format conversion, etc.) + * - `gif-to-video`: Convert animated GIF to video format + * - `video-thumbnail`: Generate thumbnail image from video + */ + class Type @JsonCreator private constructor(private val value: JsonField) : + Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that + * doesn't match any known member, and you want to know that value. For example, if + * the SDK is on an older version than the API, then the API may respond with new + * members that the SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val VIDEO_TRANSFORMATION = of("video-transformation") + + @JvmField val GIF_TO_VIDEO = of("gif-to-video") + + @JvmField val VIDEO_THUMBNAIL = of("video-thumbnail") + + @JvmStatic fun of(value: String) = Type(JsonField.of(value)) + } + + /** An enum containing [Type]'s known values. */ + enum class Known { + VIDEO_TRANSFORMATION, + GIF_TO_VIDEO, + VIDEO_THUMBNAIL, + } + + /** + * An enum containing [Type]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [Type] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, + * if the SDK is on an older version than the API, then the API may respond with + * new members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + VIDEO_TRANSFORMATION, + GIF_TO_VIDEO, + VIDEO_THUMBNAIL, + /** + * An enum member indicating that [Type] was instantiated with an unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if + * you want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + VIDEO_TRANSFORMATION -> Value.VIDEO_TRANSFORMATION + GIF_TO_VIDEO -> Value.GIF_TO_VIDEO + VIDEO_THUMBNAIL -> Value.VIDEO_THUMBNAIL + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and + * don't want to throw for the unknown case. + * + * @throws ImageKitInvalidDataException if this class instance's value is a not a + * known member. + */ + fun known(): Known = + when (this) { + VIDEO_TRANSFORMATION -> Known.VIDEO_TRANSFORMATION + GIF_TO_VIDEO -> Known.GIF_TO_VIDEO + VIDEO_THUMBNAIL -> Known.VIDEO_THUMBNAIL + else -> throw ImageKitInvalidDataException("Unknown Type: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for + * debugging and generally doesn't throw. + * + * @throws ImageKitInvalidDataException if this class instance's value does not have + * the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + ImageKitInvalidDataException("Value is not a String") + } + + private var validated: Boolean = false + + fun validate(): Type = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Type && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + /** Configuration options for video transformations. */ + class Options + private constructor( + private val audioCodec: JsonField, + private val autoRotate: JsonField, + private val format: JsonField, + private val quality: JsonField, + private val streamProtocol: JsonField, + private val variants: JsonField>, + private val videoCodec: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("audio_codec") + @ExcludeMissing + audioCodec: JsonField = JsonMissing.of(), + @JsonProperty("auto_rotate") + @ExcludeMissing + autoRotate: JsonField = JsonMissing.of(), + @JsonProperty("format") + @ExcludeMissing + format: JsonField = JsonMissing.of(), + @JsonProperty("quality") + @ExcludeMissing + quality: JsonField = JsonMissing.of(), + @JsonProperty("stream_protocol") + @ExcludeMissing + streamProtocol: JsonField = JsonMissing.of(), + @JsonProperty("variants") + @ExcludeMissing + variants: JsonField> = JsonMissing.of(), + @JsonProperty("video_codec") + @ExcludeMissing + videoCodec: JsonField = JsonMissing.of(), + ) : this( + audioCodec, + autoRotate, + format, + quality, + streamProtocol, + variants, + videoCodec, + mutableMapOf(), + ) + + /** + * Audio codec used for encoding (aac or opus). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun audioCodec(): Optional = audioCodec.getOptional("audio_codec") + + /** + * Whether to automatically rotate the video based on metadata. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun autoRotate(): Optional = autoRotate.getOptional("auto_rotate") + + /** + * Output format for the transformed video or thumbnail. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun format(): Optional = format.getOptional("format") + + /** + * Quality setting for the output video. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun quality(): Optional = quality.getOptional("quality") + + /** + * Streaming protocol for adaptive bitrate streaming. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun streamProtocol(): Optional = + streamProtocol.getOptional("stream_protocol") + + /** + * Array of quality representations for adaptive bitrate streaming. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun variants(): Optional> = variants.getOptional("variants") + + /** + * Video codec used for encoding (h264, vp9, or av1). + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun videoCodec(): Optional = videoCodec.getOptional("video_codec") + + /** + * Returns the raw JSON value of [audioCodec]. + * + * Unlike [audioCodec], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("audio_codec") + @ExcludeMissing + fun _audioCodec(): JsonField = audioCodec + + /** + * Returns the raw JSON value of [autoRotate]. + * + * Unlike [autoRotate], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("auto_rotate") + @ExcludeMissing + fun _autoRotate(): JsonField = autoRotate + + /** + * Returns the raw JSON value of [format]. + * + * Unlike [format], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("format") @ExcludeMissing fun _format(): JsonField = format + + /** + * Returns the raw JSON value of [quality]. + * + * Unlike [quality], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("quality") @ExcludeMissing fun _quality(): JsonField = quality + + /** + * Returns the raw JSON value of [streamProtocol]. + * + * Unlike [streamProtocol], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("stream_protocol") + @ExcludeMissing + fun _streamProtocol(): JsonField = streamProtocol + + /** + * Returns the raw JSON value of [variants]. + * + * Unlike [variants], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("variants") + @ExcludeMissing + fun _variants(): JsonField> = variants + + /** + * Returns the raw JSON value of [videoCodec]. + * + * Unlike [videoCodec], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("video_codec") + @ExcludeMissing + fun _videoCodec(): JsonField = videoCodec + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Options]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Options]. */ + class Builder internal constructor() { + + private var audioCodec: JsonField = JsonMissing.of() + private var autoRotate: JsonField = JsonMissing.of() + private var format: JsonField = JsonMissing.of() + private var quality: JsonField = JsonMissing.of() + private var streamProtocol: JsonField = JsonMissing.of() + private var variants: JsonField>? = null + private var videoCodec: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(options: Options) = apply { + audioCodec = options.audioCodec + autoRotate = options.autoRotate + format = options.format + quality = options.quality + streamProtocol = options.streamProtocol + variants = options.variants.map { it.toMutableList() } + videoCodec = options.videoCodec + additionalProperties = options.additionalProperties.toMutableMap() + } + + /** Audio codec used for encoding (aac or opus). */ + fun audioCodec(audioCodec: AudioCodec) = audioCodec(JsonField.of(audioCodec)) + + /** + * Sets [Builder.audioCodec] to an arbitrary JSON value. + * + * You should usually call [Builder.audioCodec] with a well-typed [AudioCodec] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun audioCodec(audioCodec: JsonField) = apply { + this.audioCodec = audioCodec + } + + /** Whether to automatically rotate the video based on metadata. */ + fun autoRotate(autoRotate: Boolean) = autoRotate(JsonField.of(autoRotate)) + + /** + * Sets [Builder.autoRotate] to an arbitrary JSON value. + * + * You should usually call [Builder.autoRotate] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun autoRotate(autoRotate: JsonField) = apply { + this.autoRotate = autoRotate + } + + /** Output format for the transformed video or thumbnail. */ + fun format(format: Format) = format(JsonField.of(format)) + + /** + * Sets [Builder.format] to an arbitrary JSON value. + * + * You should usually call [Builder.format] with a well-typed [Format] value + * instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun format(format: JsonField) = apply { this.format = format } + + /** Quality setting for the output video. */ + fun quality(quality: Long) = quality(JsonField.of(quality)) + + /** + * Sets [Builder.quality] to an arbitrary JSON value. + * + * You should usually call [Builder.quality] with a well-typed [Long] value + * instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun quality(quality: JsonField) = apply { this.quality = quality } + + /** Streaming protocol for adaptive bitrate streaming. */ + fun streamProtocol(streamProtocol: StreamProtocol) = + streamProtocol(JsonField.of(streamProtocol)) + + /** + * Sets [Builder.streamProtocol] to an arbitrary JSON value. + * + * You should usually call [Builder.streamProtocol] with a well-typed + * [StreamProtocol] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ + fun streamProtocol(streamProtocol: JsonField) = apply { + this.streamProtocol = streamProtocol + } + + /** Array of quality representations for adaptive bitrate streaming. */ + fun variants(variants: List) = variants(JsonField.of(variants)) + + /** + * Sets [Builder.variants] to an arbitrary JSON value. + * + * You should usually call [Builder.variants] with a well-typed `List` + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun variants(variants: JsonField>) = apply { + this.variants = variants.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [variants]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addVariant(variant: String) = apply { + variants = + (variants ?: JsonField.of(mutableListOf())).also { + checkKnown("variants", it).add(variant) + } + } + + /** Video codec used for encoding (h264, vp9, or av1). */ + fun videoCodec(videoCodec: VideoCodec) = videoCodec(JsonField.of(videoCodec)) + + /** + * Sets [Builder.videoCodec] to an arbitrary JSON value. + * + * You should usually call [Builder.videoCodec] with a well-typed [VideoCodec] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun videoCodec(videoCodec: JsonField) = apply { + this.videoCodec = videoCodec + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Options]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Options = + Options( + audioCodec, + autoRotate, + format, + quality, + streamProtocol, + (variants ?: JsonMissing.of()).map { it.toImmutable() }, + videoCodec, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Options = apply { + if (validated) { + return@apply + } + + audioCodec().ifPresent { it.validate() } + autoRotate() + format().ifPresent { it.validate() } + quality() + streamProtocol().ifPresent { it.validate() } + variants() + videoCodec().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (audioCodec.asKnown().getOrNull()?.validity() ?: 0) + + (if (autoRotate.asKnown().isPresent) 1 else 0) + + (format.asKnown().getOrNull()?.validity() ?: 0) + + (if (quality.asKnown().isPresent) 1 else 0) + + (streamProtocol.asKnown().getOrNull()?.validity() ?: 0) + + (variants.asKnown().getOrNull()?.size ?: 0) + + (videoCodec.asKnown().getOrNull()?.validity() ?: 0) + + /** Audio codec used for encoding (aac or opus). */ + class AudioCodec + @JsonCreator + private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that + * doesn't match any known member, and you want to know that value. For example, + * if the SDK is on an older version than the API, then the API may respond with + * new members that the SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue + fun _value(): JsonField = value + + companion object { + + @JvmField val AAC = of("aac") + + @JvmField val OPUS = of("opus") + + @JvmStatic fun of(value: String) = AudioCodec(JsonField.of(value)) + } + + /** An enum containing [AudioCodec]'s known values. */ + enum class Known { + AAC, + OPUS, + } + + /** + * An enum containing [AudioCodec]'s known values, as well as an [_UNKNOWN] + * member. + * + * An instance of [AudioCodec] can contain an unknown value in a couple of + * cases: + * - It was deserialized from data that doesn't match any known member. For + * example, if the SDK is on an older version than the API, then the API may + * respond with new members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + AAC, + OPUS, + /** + * An enum member indicating that [AudioCodec] was instantiated with an + * unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or + * if you want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + AAC -> Value.AAC + OPUS -> Value.OPUS + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known + * and don't want to throw for the unknown case. + * + * @throws ImageKitInvalidDataException if this class instance's value is a not + * a known member. + */ + fun known(): Known = + when (this) { + AAC -> Known.AAC + OPUS -> Known.OPUS + else -> throw ImageKitInvalidDataException("Unknown AudioCodec: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for + * debugging and generally doesn't throw. + * + * @throws ImageKitInvalidDataException if this class instance's value does not + * have the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + ImageKitInvalidDataException("Value is not a String") + } + + private var validated: Boolean = false + + fun validate(): AudioCodec = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is AudioCodec && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + /** Output format for the transformed video or thumbnail. */ + class Format + @JsonCreator + private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that + * doesn't match any known member, and you want to know that value. For example, + * if the SDK is on an older version than the API, then the API may respond with + * new members that the SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue + fun _value(): JsonField = value + + companion object { + + @JvmField val MP4 = of("mp4") + + @JvmField val WEBM = of("webm") + + @JvmField val JPG = of("jpg") + + @JvmField val PNG = of("png") + + @JvmField val WEBP = of("webp") + + @JvmStatic fun of(value: String) = Format(JsonField.of(value)) + } + + /** An enum containing [Format]'s known values. */ + enum class Known { + MP4, + WEBM, + JPG, + PNG, + WEBP, + } + + /** + * An enum containing [Format]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [Format] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For + * example, if the SDK is on an older version than the API, then the API may + * respond with new members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + MP4, + WEBM, + JPG, + PNG, + WEBP, + /** + * An enum member indicating that [Format] was instantiated with an unknown + * value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or + * if you want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + MP4 -> Value.MP4 + WEBM -> Value.WEBM + JPG -> Value.JPG + PNG -> Value.PNG + WEBP -> Value.WEBP + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known + * and don't want to throw for the unknown case. + * + * @throws ImageKitInvalidDataException if this class instance's value is a not + * a known member. + */ + fun known(): Known = + when (this) { + MP4 -> Known.MP4 + WEBM -> Known.WEBM + JPG -> Known.JPG + PNG -> Known.PNG + WEBP -> Known.WEBP + else -> throw ImageKitInvalidDataException("Unknown Format: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for + * debugging and generally doesn't throw. + * + * @throws ImageKitInvalidDataException if this class instance's value does not + * have the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + ImageKitInvalidDataException("Value is not a String") + } + + private var validated: Boolean = false + + fun validate(): Format = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Format && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + /** Streaming protocol for adaptive bitrate streaming. */ + class StreamProtocol + @JsonCreator + private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that + * doesn't match any known member, and you want to know that value. For example, + * if the SDK is on an older version than the API, then the API may respond with + * new members that the SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue + fun _value(): JsonField = value + + companion object { + + @JvmField val HLS = of("HLS") + + @JvmField val DASH = of("DASH") + + @JvmStatic fun of(value: String) = StreamProtocol(JsonField.of(value)) + } + + /** An enum containing [StreamProtocol]'s known values. */ + enum class Known { + HLS, + DASH, + } + + /** + * An enum containing [StreamProtocol]'s known values, as well as an [_UNKNOWN] + * member. + * + * An instance of [StreamProtocol] can contain an unknown value in a couple of + * cases: + * - It was deserialized from data that doesn't match any known member. For + * example, if the SDK is on an older version than the API, then the API may + * respond with new members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + HLS, + DASH, + /** + * An enum member indicating that [StreamProtocol] was instantiated with an + * unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or + * if you want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + HLS -> Value.HLS + DASH -> Value.DASH + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known + * and don't want to throw for the unknown case. + * + * @throws ImageKitInvalidDataException if this class instance's value is a not + * a known member. + */ + fun known(): Known = + when (this) { + HLS -> Known.HLS + DASH -> Known.DASH + else -> + throw ImageKitInvalidDataException("Unknown StreamProtocol: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for + * debugging and generally doesn't throw. + * + * @throws ImageKitInvalidDataException if this class instance's value does not + * have the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + ImageKitInvalidDataException("Value is not a String") + } + + private var validated: Boolean = false + + fun validate(): StreamProtocol = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is StreamProtocol && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + /** Video codec used for encoding (h264, vp9, or av1). */ + class VideoCodec + @JsonCreator + private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that + * doesn't match any known member, and you want to know that value. For example, + * if the SDK is on an older version than the API, then the API may respond with + * new members that the SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue + fun _value(): JsonField = value + + companion object { + + @JvmField val H264 = of("h264") + + @JvmField val VP9 = of("vp9") + + @JvmField val AV1 = of("av1") + + @JvmStatic fun of(value: String) = VideoCodec(JsonField.of(value)) + } + + /** An enum containing [VideoCodec]'s known values. */ + enum class Known { + H264, + VP9, + AV1, + } + + /** + * An enum containing [VideoCodec]'s known values, as well as an [_UNKNOWN] + * member. + * + * An instance of [VideoCodec] can contain an unknown value in a couple of + * cases: + * - It was deserialized from data that doesn't match any known member. For + * example, if the SDK is on an older version than the API, then the API may + * respond with new members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + H264, + VP9, + AV1, + /** + * An enum member indicating that [VideoCodec] was instantiated with an + * unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or + * if you want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + H264 -> Value.H264 + VP9 -> Value.VP9 + AV1 -> Value.AV1 + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known + * and don't want to throw for the unknown case. + * + * @throws ImageKitInvalidDataException if this class instance's value is a not + * a known member. + */ + fun known(): Known = + when (this) { + H264 -> Known.H264 + VP9 -> Known.VP9 + AV1 -> Known.AV1 + else -> throw ImageKitInvalidDataException("Unknown VideoCodec: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for + * debugging and generally doesn't throw. + * + * @throws ImageKitInvalidDataException if this class instance's value does not + * have the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + ImageKitInvalidDataException("Value is not a String") + } + + private var validated: Boolean = false + + fun validate(): VideoCodec = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is VideoCodec && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Options && + audioCodec == other.audioCodec && + autoRotate == other.autoRotate && + format == other.format && + quality == other.quality && + streamProtocol == other.streamProtocol && + variants == other.variants && + videoCodec == other.videoCodec && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + audioCodec, + autoRotate, + format, + quality, + streamProtocol, + variants, + videoCodec, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Options{audioCodec=$audioCodec, autoRotate=$autoRotate, format=$format, quality=$quality, streamProtocol=$streamProtocol, variants=$variants, videoCodec=$videoCodec, additionalProperties=$additionalProperties}" + } + + /** Information about the transformed output video. */ + class Output + private constructor( + private val url: JsonField, + private val videoMetadata: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("url") @ExcludeMissing url: JsonField = JsonMissing.of(), + @JsonProperty("video_metadata") + @ExcludeMissing + videoMetadata: JsonField = JsonMissing.of(), + ) : this(url, videoMetadata, mutableMapOf()) + + /** + * URL to access the transformed video. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or + * is unexpectedly missing or null (e.g. if the server responded with an + * unexpected value). + */ + fun url(): String = url.getRequired("url") + + /** + * Metadata of the output video file. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun videoMetadata(): Optional = + videoMetadata.getOptional("video_metadata") + + /** + * Returns the raw JSON value of [url]. + * + * Unlike [url], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("url") @ExcludeMissing fun _url(): JsonField = url + + /** + * Returns the raw JSON value of [videoMetadata]. + * + * Unlike [videoMetadata], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("video_metadata") + @ExcludeMissing + fun _videoMetadata(): JsonField = videoMetadata + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Output]. + * + * The following fields are required: + * ```java + * .url() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Output]. */ + class Builder internal constructor() { + + private var url: JsonField? = null + private var videoMetadata: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(output: Output) = apply { + url = output.url + videoMetadata = output.videoMetadata + additionalProperties = output.additionalProperties.toMutableMap() + } + + /** URL to access the transformed video. */ + fun url(url: String) = url(JsonField.of(url)) + + /** + * Sets [Builder.url] to an arbitrary JSON value. + * + * You should usually call [Builder.url] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun url(url: JsonField) = apply { this.url = url } + + /** Metadata of the output video file. */ + fun videoMetadata(videoMetadata: VideoMetadata) = + videoMetadata(JsonField.of(videoMetadata)) + + /** + * Sets [Builder.videoMetadata] to an arbitrary JSON value. + * + * You should usually call [Builder.videoMetadata] with a well-typed + * [VideoMetadata] value instead. This method is primarily for setting the field + * to an undocumented or not yet supported value. + */ + fun videoMetadata(videoMetadata: JsonField) = apply { + this.videoMetadata = videoMetadata + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Output]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .url() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Output = + Output( + checkRequired("url", url), + videoMetadata, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Output = apply { + if (validated) { + return@apply + } + + url() + videoMetadata().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (url.asKnown().isPresent) 1 else 0) + + (videoMetadata.asKnown().getOrNull()?.validity() ?: 0) + + /** Metadata of the output video file. */ + class VideoMetadata + private constructor( + private val bitrate: JsonField, + private val duration: JsonField, + private val height: JsonField, + private val width: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("bitrate") + @ExcludeMissing + bitrate: JsonField = JsonMissing.of(), + @JsonProperty("duration") + @ExcludeMissing + duration: JsonField = JsonMissing.of(), + @JsonProperty("height") + @ExcludeMissing + height: JsonField = JsonMissing.of(), + @JsonProperty("width") + @ExcludeMissing + width: JsonField = JsonMissing.of(), + ) : this(bitrate, duration, height, width, mutableMapOf()) + + /** + * Bitrate of the output video in bits per second. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type + * or is unexpectedly missing or null (e.g. if the server responded with an + * unexpected value). + */ + fun bitrate(): Long = bitrate.getRequired("bitrate") + + /** + * Duration of the output video in seconds. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type + * or is unexpectedly missing or null (e.g. if the server responded with an + * unexpected value). + */ + fun duration(): Double = duration.getRequired("duration") + + /** + * Height of the output video in pixels. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type + * or is unexpectedly missing or null (e.g. if the server responded with an + * unexpected value). + */ + fun height(): Long = height.getRequired("height") + + /** + * Width of the output video in pixels. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type + * or is unexpectedly missing or null (e.g. if the server responded with an + * unexpected value). + */ + fun width(): Long = width.getRequired("width") + + /** + * Returns the raw JSON value of [bitrate]. + * + * Unlike [bitrate], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("bitrate") + @ExcludeMissing + fun _bitrate(): JsonField = bitrate + + /** + * Returns the raw JSON value of [duration]. + * + * Unlike [duration], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("duration") + @ExcludeMissing + fun _duration(): JsonField = duration + + /** + * Returns the raw JSON value of [height]. + * + * Unlike [height], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("height") @ExcludeMissing fun _height(): JsonField = height + + /** + * Returns the raw JSON value of [width]. + * + * Unlike [width], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("width") @ExcludeMissing fun _width(): JsonField = width + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [VideoMetadata]. + * + * The following fields are required: + * ```java + * .bitrate() + * .duration() + * .height() + * .width() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [VideoMetadata]. */ + class Builder internal constructor() { + + private var bitrate: JsonField? = null + private var duration: JsonField? = null + private var height: JsonField? = null + private var width: JsonField? = null + private var additionalProperties: MutableMap = + mutableMapOf() + + @JvmSynthetic + internal fun from(videoMetadata: VideoMetadata) = apply { + bitrate = videoMetadata.bitrate + duration = videoMetadata.duration + height = videoMetadata.height + width = videoMetadata.width + additionalProperties = videoMetadata.additionalProperties.toMutableMap() + } + + /** Bitrate of the output video in bits per second. */ + fun bitrate(bitrate: Long) = bitrate(JsonField.of(bitrate)) + + /** + * Sets [Builder.bitrate] to an arbitrary JSON value. + * + * You should usually call [Builder.bitrate] with a well-typed [Long] value + * instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun bitrate(bitrate: JsonField) = apply { this.bitrate = bitrate } + + /** Duration of the output video in seconds. */ + fun duration(duration: Double) = duration(JsonField.of(duration)) + + /** + * Sets [Builder.duration] to an arbitrary JSON value. + * + * You should usually call [Builder.duration] with a well-typed [Double] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun duration(duration: JsonField) = apply { + this.duration = duration + } + + /** Height of the output video in pixels. */ + fun height(height: Long) = height(JsonField.of(height)) + + /** + * Sets [Builder.height] to an arbitrary JSON value. + * + * You should usually call [Builder.height] with a well-typed [Long] value + * instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun height(height: JsonField) = apply { this.height = height } + + /** Width of the output video in pixels. */ + fun width(width: Long) = width(JsonField.of(width)) + + /** + * Sets [Builder.width] to an arbitrary JSON value. + * + * You should usually call [Builder.width] with a well-typed [Long] value + * instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun width(width: JsonField) = apply { this.width = width } + + fun additionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties( + additionalProperties: Map + ) = apply { this.additionalProperties.putAll(additionalProperties) } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [VideoMetadata]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .bitrate() + * .duration() + * .height() + * .width() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): VideoMetadata = + VideoMetadata( + checkRequired("bitrate", bitrate), + checkRequired("duration", duration), + checkRequired("height", height), + checkRequired("width", width), + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): VideoMetadata = apply { + if (validated) { + return@apply + } + + bitrate() + duration() + height() + width() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (bitrate.asKnown().isPresent) 1 else 0) + + (if (duration.asKnown().isPresent) 1 else 0) + + (if (height.asKnown().isPresent) 1 else 0) + + (if (width.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is VideoMetadata && + bitrate == other.bitrate && + duration == other.duration && + height == other.height && + width == other.width && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(bitrate, duration, height, width, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "VideoMetadata{bitrate=$bitrate, duration=$duration, height=$height, width=$width, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Output && + url == other.url && + videoMetadata == other.videoMetadata && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(url, videoMetadata, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Output{url=$url, videoMetadata=$videoMetadata, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Transformation && + type == other.type && + options == other.options && + output == other.output && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(type, options, output, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Transformation{type=$type, options=$options, output=$output, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Data && + asset == other.asset && + transformation == other.transformation && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(asset, transformation, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Data{asset=$asset, transformation=$transformation, additionalProperties=$additionalProperties}" + } + + /** Information about the original request that triggered the video transformation. */ + class Request + private constructor( + private val url: JsonField, + private val xRequestId: JsonField, + private val userAgent: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("url") @ExcludeMissing url: JsonField = JsonMissing.of(), + @JsonProperty("x_request_id") + @ExcludeMissing + xRequestId: JsonField = JsonMissing.of(), + @JsonProperty("user_agent") + @ExcludeMissing + userAgent: JsonField = JsonMissing.of(), + ) : this(url, xRequestId, userAgent, mutableMapOf()) + + /** + * Full URL of the transformation request that was submitted. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun url(): String = url.getRequired("url") + + /** + * Unique identifier for the originating transformation request. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun xRequestId(): String = xRequestId.getRequired("x_request_id") + + /** + * User-Agent header from the original request that triggered the transformation. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun userAgent(): Optional = userAgent.getOptional("user_agent") + + /** + * Returns the raw JSON value of [url]. + * + * Unlike [url], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("url") @ExcludeMissing fun _url(): JsonField = url + + /** + * Returns the raw JSON value of [xRequestId]. + * + * Unlike [xRequestId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("x_request_id") + @ExcludeMissing + fun _xRequestId(): JsonField = xRequestId + + /** + * Returns the raw JSON value of [userAgent]. + * + * Unlike [userAgent], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("user_agent") @ExcludeMissing fun _userAgent(): JsonField = userAgent + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Request]. + * + * The following fields are required: + * ```java + * .url() + * .xRequestId() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Request]. */ + class Builder internal constructor() { + + private var url: JsonField? = null + private var xRequestId: JsonField? = null + private var userAgent: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(request: Request) = apply { + url = request.url + xRequestId = request.xRequestId + userAgent = request.userAgent + additionalProperties = request.additionalProperties.toMutableMap() + } + + /** Full URL of the transformation request that was submitted. */ + fun url(url: String) = url(JsonField.of(url)) + + /** + * Sets [Builder.url] to an arbitrary JSON value. + * + * You should usually call [Builder.url] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun url(url: JsonField) = apply { this.url = url } + + /** Unique identifier for the originating transformation request. */ + fun xRequestId(xRequestId: String) = xRequestId(JsonField.of(xRequestId)) + + /** + * Sets [Builder.xRequestId] to an arbitrary JSON value. + * + * You should usually call [Builder.xRequestId] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun xRequestId(xRequestId: JsonField) = apply { this.xRequestId = xRequestId } + + /** User-Agent header from the original request that triggered the transformation. */ + fun userAgent(userAgent: String) = userAgent(JsonField.of(userAgent)) + + /** + * Sets [Builder.userAgent] to an arbitrary JSON value. + * + * You should usually call [Builder.userAgent] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun userAgent(userAgent: JsonField) = apply { this.userAgent = userAgent } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Request]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .url() + * .xRequestId() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Request = + Request( + checkRequired("url", url), + checkRequired("xRequestId", xRequestId), + userAgent, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Request = apply { + if (validated) { + return@apply + } + + url() + xRequestId() + userAgent() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (url.asKnown().isPresent) 1 else 0) + + (if (xRequestId.asKnown().isPresent) 1 else 0) + + (if (userAgent.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Request && + url == other.url && + xRequestId == other.xRequestId && + userAgent == other.userAgent && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(url, xRequestId, userAgent, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Request{url=$url, xRequestId=$xRequestId, userAgent=$userAgent, additionalProperties=$additionalProperties}" + } + + /** Performance metrics for the transformation process. */ + class Timings + private constructor( + private val downloadDuration: JsonField, + private val encodingDuration: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("download_duration") + @ExcludeMissing + downloadDuration: JsonField = JsonMissing.of(), + @JsonProperty("encoding_duration") + @ExcludeMissing + encodingDuration: JsonField = JsonMissing.of(), + ) : this(downloadDuration, encodingDuration, mutableMapOf()) + + /** + * Time spent downloading the source video from your origin or media library, in + * milliseconds. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun downloadDuration(): Optional = downloadDuration.getOptional("download_duration") + + /** + * Time spent encoding the video, in milliseconds. + * + * @throws ImageKitInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun encodingDuration(): Optional = encodingDuration.getOptional("encoding_duration") + + /** + * Returns the raw JSON value of [downloadDuration]. + * + * Unlike [downloadDuration], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("download_duration") + @ExcludeMissing + fun _downloadDuration(): JsonField = downloadDuration + + /** + * Returns the raw JSON value of [encodingDuration]. + * + * Unlike [encodingDuration], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("encoding_duration") + @ExcludeMissing + fun _encodingDuration(): JsonField = encodingDuration + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Timings]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Timings]. */ + class Builder internal constructor() { + + private var downloadDuration: JsonField = JsonMissing.of() + private var encodingDuration: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(timings: Timings) = apply { + downloadDuration = timings.downloadDuration + encodingDuration = timings.encodingDuration + additionalProperties = timings.additionalProperties.toMutableMap() + } + + /** + * Time spent downloading the source video from your origin or media library, in + * milliseconds. + */ + fun downloadDuration(downloadDuration: Long) = + downloadDuration(JsonField.of(downloadDuration)) + + /** + * Sets [Builder.downloadDuration] to an arbitrary JSON value. + * + * You should usually call [Builder.downloadDuration] with a well-typed [Long] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun downloadDuration(downloadDuration: JsonField) = apply { + this.downloadDuration = downloadDuration + } + + /** Time spent encoding the video, in milliseconds. */ + fun encodingDuration(encodingDuration: Long) = + encodingDuration(JsonField.of(encodingDuration)) + + /** + * Sets [Builder.encodingDuration] to an arbitrary JSON value. + * + * You should usually call [Builder.encodingDuration] with a well-typed [Long] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun encodingDuration(encodingDuration: JsonField) = apply { + this.encodingDuration = encodingDuration + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Timings]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Timings = + Timings(downloadDuration, encodingDuration, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Timings = apply { + if (validated) { + return@apply + } + + downloadDuration() + encodingDuration() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ImageKitInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (downloadDuration.asKnown().isPresent) 1 else 0) + + (if (encodingDuration.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Timings && + downloadDuration == other.downloadDuration && + encodingDuration == other.encodingDuration && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(downloadDuration, encodingDuration, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Timings{downloadDuration=$downloadDuration, encodingDuration=$encodingDuration, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is VideoTransformationReadyEvent && + id == other.id && + type == other.type && + createdAt == other.createdAt && + data == other.data && + request == other.request && + timings == other.timings && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(id, type, createdAt, data, request, timings, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "VideoTransformationReadyEvent{id=$id, type=$type, createdAt=$createdAt, data=$data, request=$request, timings=$timings, additionalProperties=$additionalProperties}" +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/AccountServiceAsync.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/AccountServiceAsync.kt new file mode 100644 index 0000000..b8387b9 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/AccountServiceAsync.kt @@ -0,0 +1,51 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.async + +import com.imagekit.api.core.ClientOptions +import com.imagekit.api.services.async.accounts.OriginServiceAsync +import com.imagekit.api.services.async.accounts.UrlEndpointServiceAsync +import com.imagekit.api.services.async.accounts.UsageServiceAsync +import java.util.function.Consumer + +interface AccountServiceAsync { + + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): AccountServiceAsync + + fun usage(): UsageServiceAsync + + fun origins(): OriginServiceAsync + + fun urlEndpoints(): UrlEndpointServiceAsync + + /** + * A view of [AccountServiceAsync] that provides access to raw HTTP responses for each method. + */ + interface WithRawResponse { + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions( + modifier: Consumer + ): AccountServiceAsync.WithRawResponse + + fun usage(): UsageServiceAsync.WithRawResponse + + fun origins(): OriginServiceAsync.WithRawResponse + + fun urlEndpoints(): UrlEndpointServiceAsync.WithRawResponse + } +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/AccountServiceAsyncImpl.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/AccountServiceAsyncImpl.kt new file mode 100644 index 0000000..a6322df --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/AccountServiceAsyncImpl.kt @@ -0,0 +1,68 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.async + +import com.imagekit.api.core.ClientOptions +import com.imagekit.api.services.async.accounts.OriginServiceAsync +import com.imagekit.api.services.async.accounts.OriginServiceAsyncImpl +import com.imagekit.api.services.async.accounts.UrlEndpointServiceAsync +import com.imagekit.api.services.async.accounts.UrlEndpointServiceAsyncImpl +import com.imagekit.api.services.async.accounts.UsageServiceAsync +import com.imagekit.api.services.async.accounts.UsageServiceAsyncImpl +import java.util.function.Consumer + +class AccountServiceAsyncImpl internal constructor(private val clientOptions: ClientOptions) : + AccountServiceAsync { + + private val withRawResponse: AccountServiceAsync.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + private val usage: UsageServiceAsync by lazy { UsageServiceAsyncImpl(clientOptions) } + + private val origins: OriginServiceAsync by lazy { OriginServiceAsyncImpl(clientOptions) } + + private val urlEndpoints: UrlEndpointServiceAsync by lazy { + UrlEndpointServiceAsyncImpl(clientOptions) + } + + override fun withRawResponse(): AccountServiceAsync.WithRawResponse = withRawResponse + + override fun withOptions(modifier: Consumer): AccountServiceAsync = + AccountServiceAsyncImpl(clientOptions.toBuilder().apply(modifier::accept).build()) + + override fun usage(): UsageServiceAsync = usage + + override fun origins(): OriginServiceAsync = origins + + override fun urlEndpoints(): UrlEndpointServiceAsync = urlEndpoints + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + AccountServiceAsync.WithRawResponse { + + private val usage: UsageServiceAsync.WithRawResponse by lazy { + UsageServiceAsyncImpl.WithRawResponseImpl(clientOptions) + } + + private val origins: OriginServiceAsync.WithRawResponse by lazy { + OriginServiceAsyncImpl.WithRawResponseImpl(clientOptions) + } + + private val urlEndpoints: UrlEndpointServiceAsync.WithRawResponse by lazy { + UrlEndpointServiceAsyncImpl.WithRawResponseImpl(clientOptions) + } + + override fun withOptions( + modifier: Consumer + ): AccountServiceAsync.WithRawResponse = + AccountServiceAsyncImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + override fun usage(): UsageServiceAsync.WithRawResponse = usage + + override fun origins(): OriginServiceAsync.WithRawResponse = origins + + override fun urlEndpoints(): UrlEndpointServiceAsync.WithRawResponse = urlEndpoints + } +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/AssetServiceAsync.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/AssetServiceAsync.kt new file mode 100644 index 0000000..cd5259c --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/AssetServiceAsync.kt @@ -0,0 +1,87 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.async + +import com.imagekit.api.core.ClientOptions +import com.imagekit.api.core.RequestOptions +import com.imagekit.api.core.http.HttpResponseFor +import com.imagekit.api.models.assets.AssetListParams +import com.imagekit.api.models.assets.AssetListResponse +import java.util.concurrent.CompletableFuture +import java.util.function.Consumer + +interface AssetServiceAsync { + + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): AssetServiceAsync + + /** + * This API can list all the uploaded files and folders in your ImageKit.io media library. In + * addition, you can fine-tune your query by specifying various filters by generating a query + * string in a Lucene-like syntax and provide this generated string as the value of the + * `searchQuery`. + */ + fun list(): CompletableFuture> = list(AssetListParams.none()) + + /** @see list */ + fun list( + params: AssetListParams = AssetListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see list */ + fun list( + params: AssetListParams = AssetListParams.none() + ): CompletableFuture> = list(params, RequestOptions.none()) + + /** @see list */ + fun list(requestOptions: RequestOptions): CompletableFuture> = + list(AssetListParams.none(), requestOptions) + + /** A view of [AssetServiceAsync] that provides access to raw HTTP responses for each method. */ + interface WithRawResponse { + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions( + modifier: Consumer + ): AssetServiceAsync.WithRawResponse + + /** + * Returns a raw HTTP response for `get /v1/files`, but is otherwise the same as + * [AssetServiceAsync.list]. + */ + fun list(): CompletableFuture>> = + list(AssetListParams.none()) + + /** @see list */ + fun list( + params: AssetListParams = AssetListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture>> + + /** @see list */ + fun list( + params: AssetListParams = AssetListParams.none() + ): CompletableFuture>> = + list(params, RequestOptions.none()) + + /** @see list */ + fun list( + requestOptions: RequestOptions + ): CompletableFuture>> = + list(AssetListParams.none(), requestOptions) + } +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/AssetServiceAsyncImpl.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/AssetServiceAsyncImpl.kt new file mode 100644 index 0000000..316d388 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/AssetServiceAsyncImpl.kt @@ -0,0 +1,84 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.async + +import com.imagekit.api.core.ClientOptions +import com.imagekit.api.core.RequestOptions +import com.imagekit.api.core.handlers.errorBodyHandler +import com.imagekit.api.core.handlers.errorHandler +import com.imagekit.api.core.handlers.jsonHandler +import com.imagekit.api.core.http.HttpMethod +import com.imagekit.api.core.http.HttpRequest +import com.imagekit.api.core.http.HttpResponse +import com.imagekit.api.core.http.HttpResponse.Handler +import com.imagekit.api.core.http.HttpResponseFor +import com.imagekit.api.core.http.parseable +import com.imagekit.api.core.prepareAsync +import com.imagekit.api.models.assets.AssetListParams +import com.imagekit.api.models.assets.AssetListResponse +import java.util.concurrent.CompletableFuture +import java.util.function.Consumer + +class AssetServiceAsyncImpl internal constructor(private val clientOptions: ClientOptions) : + AssetServiceAsync { + + private val withRawResponse: AssetServiceAsync.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + override fun withRawResponse(): AssetServiceAsync.WithRawResponse = withRawResponse + + override fun withOptions(modifier: Consumer): AssetServiceAsync = + AssetServiceAsyncImpl(clientOptions.toBuilder().apply(modifier::accept).build()) + + override fun list( + params: AssetListParams, + requestOptions: RequestOptions, + ): CompletableFuture> = + // get /v1/files + withRawResponse().list(params, requestOptions).thenApply { it.parse() } + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + AssetServiceAsync.WithRawResponse { + + private val errorHandler: Handler = + errorHandler(errorBodyHandler(clientOptions.jsonMapper)) + + override fun withOptions( + modifier: Consumer + ): AssetServiceAsync.WithRawResponse = + AssetServiceAsyncImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + private val listHandler: Handler> = + jsonHandler>(clientOptions.jsonMapper) + + override fun list( + params: AssetListParams, + requestOptions: RequestOptions, + ): CompletableFuture>> { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "files") + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { listHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.forEach { it.validate() } + } + } + } + } + } + } +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/BetaServiceAsync.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/BetaServiceAsync.kt new file mode 100644 index 0000000..1025277 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/BetaServiceAsync.kt @@ -0,0 +1,37 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.async + +import com.imagekit.api.core.ClientOptions +import com.imagekit.api.services.async.beta.V2ServiceAsync +import java.util.function.Consumer + +interface BetaServiceAsync { + + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): BetaServiceAsync + + fun v2(): V2ServiceAsync + + /** A view of [BetaServiceAsync] that provides access to raw HTTP responses for each method. */ + interface WithRawResponse { + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): BetaServiceAsync.WithRawResponse + + fun v2(): V2ServiceAsync.WithRawResponse + } +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/BetaServiceAsyncImpl.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/BetaServiceAsyncImpl.kt new file mode 100644 index 0000000..1ad19f0 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/BetaServiceAsyncImpl.kt @@ -0,0 +1,42 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.async + +import com.imagekit.api.core.ClientOptions +import com.imagekit.api.services.async.beta.V2ServiceAsync +import com.imagekit.api.services.async.beta.V2ServiceAsyncImpl +import java.util.function.Consumer + +class BetaServiceAsyncImpl internal constructor(private val clientOptions: ClientOptions) : + BetaServiceAsync { + + private val withRawResponse: BetaServiceAsync.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + private val v2: V2ServiceAsync by lazy { V2ServiceAsyncImpl(clientOptions) } + + override fun withRawResponse(): BetaServiceAsync.WithRawResponse = withRawResponse + + override fun withOptions(modifier: Consumer): BetaServiceAsync = + BetaServiceAsyncImpl(clientOptions.toBuilder().apply(modifier::accept).build()) + + override fun v2(): V2ServiceAsync = v2 + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + BetaServiceAsync.WithRawResponse { + + private val v2: V2ServiceAsync.WithRawResponse by lazy { + V2ServiceAsyncImpl.WithRawResponseImpl(clientOptions) + } + + override fun withOptions( + modifier: Consumer + ): BetaServiceAsync.WithRawResponse = + BetaServiceAsyncImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + override fun v2(): V2ServiceAsync.WithRawResponse = v2 + } +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/CacheServiceAsync.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/CacheServiceAsync.kt new file mode 100644 index 0000000..76b4415 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/CacheServiceAsync.kt @@ -0,0 +1,39 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.async + +import com.imagekit.api.core.ClientOptions +import com.imagekit.api.services.async.cache.InvalidationServiceAsync +import java.util.function.Consumer + +interface CacheServiceAsync { + + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): CacheServiceAsync + + fun invalidation(): InvalidationServiceAsync + + /** A view of [CacheServiceAsync] that provides access to raw HTTP responses for each method. */ + interface WithRawResponse { + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions( + modifier: Consumer + ): CacheServiceAsync.WithRawResponse + + fun invalidation(): InvalidationServiceAsync.WithRawResponse + } +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/CacheServiceAsyncImpl.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/CacheServiceAsyncImpl.kt new file mode 100644 index 0000000..0690192 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/CacheServiceAsyncImpl.kt @@ -0,0 +1,44 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.async + +import com.imagekit.api.core.ClientOptions +import com.imagekit.api.services.async.cache.InvalidationServiceAsync +import com.imagekit.api.services.async.cache.InvalidationServiceAsyncImpl +import java.util.function.Consumer + +class CacheServiceAsyncImpl internal constructor(private val clientOptions: ClientOptions) : + CacheServiceAsync { + + private val withRawResponse: CacheServiceAsync.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + private val invalidation: InvalidationServiceAsync by lazy { + InvalidationServiceAsyncImpl(clientOptions) + } + + override fun withRawResponse(): CacheServiceAsync.WithRawResponse = withRawResponse + + override fun withOptions(modifier: Consumer): CacheServiceAsync = + CacheServiceAsyncImpl(clientOptions.toBuilder().apply(modifier::accept).build()) + + override fun invalidation(): InvalidationServiceAsync = invalidation + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + CacheServiceAsync.WithRawResponse { + + private val invalidation: InvalidationServiceAsync.WithRawResponse by lazy { + InvalidationServiceAsyncImpl.WithRawResponseImpl(clientOptions) + } + + override fun withOptions( + modifier: Consumer + ): CacheServiceAsync.WithRawResponse = + CacheServiceAsyncImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + override fun invalidation(): InvalidationServiceAsync.WithRawResponse = invalidation + } +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/CustomMetadataFieldServiceAsync.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/CustomMetadataFieldServiceAsync.kt new file mode 100644 index 0000000..6d7d7c1 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/CustomMetadataFieldServiceAsync.kt @@ -0,0 +1,280 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.async + +import com.imagekit.api.core.ClientOptions +import com.imagekit.api.core.RequestOptions +import com.imagekit.api.core.http.HttpResponseFor +import com.imagekit.api.models.custommetadatafields.CustomMetadataField +import com.imagekit.api.models.custommetadatafields.CustomMetadataFieldCreateParams +import com.imagekit.api.models.custommetadatafields.CustomMetadataFieldDeleteParams +import com.imagekit.api.models.custommetadatafields.CustomMetadataFieldDeleteResponse +import com.imagekit.api.models.custommetadatafields.CustomMetadataFieldListParams +import com.imagekit.api.models.custommetadatafields.CustomMetadataFieldUpdateParams +import java.util.concurrent.CompletableFuture +import java.util.function.Consumer + +interface CustomMetadataFieldServiceAsync { + + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): CustomMetadataFieldServiceAsync + + /** + * This API creates a new custom metadata field. Once a custom metadata field is created either + * through this API or using the dashboard UI, its value can be set on the assets. The value of + * a field for an asset can be set using the media library UI or programmatically through upload + * or update assets API. + */ + fun create(params: CustomMetadataFieldCreateParams): CompletableFuture = + create(params, RequestOptions.none()) + + /** @see create */ + fun create( + params: CustomMetadataFieldCreateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** This API updates the label or schema of an existing custom metadata field. */ + fun update(id: String): CompletableFuture = + update(id, CustomMetadataFieldUpdateParams.none()) + + /** @see update */ + fun update( + id: String, + params: CustomMetadataFieldUpdateParams = CustomMetadataFieldUpdateParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = + update(params.toBuilder().id(id).build(), requestOptions) + + /** @see update */ + fun update( + id: String, + params: CustomMetadataFieldUpdateParams = CustomMetadataFieldUpdateParams.none(), + ): CompletableFuture = update(id, params, RequestOptions.none()) + + /** @see update */ + fun update( + params: CustomMetadataFieldUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** @see update */ + fun update(params: CustomMetadataFieldUpdateParams): CompletableFuture = + update(params, RequestOptions.none()) + + /** @see update */ + fun update(id: String, requestOptions: RequestOptions): CompletableFuture = + update(id, CustomMetadataFieldUpdateParams.none(), requestOptions) + + /** + * This API returns the array of created custom metadata field objects. By default the API + * returns only non deleted field objects, but you can include deleted fields in the API + * response. + */ + fun list(): CompletableFuture> = + list(CustomMetadataFieldListParams.none()) + + /** @see list */ + fun list( + params: CustomMetadataFieldListParams = CustomMetadataFieldListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see list */ + fun list( + params: CustomMetadataFieldListParams = CustomMetadataFieldListParams.none() + ): CompletableFuture> = list(params, RequestOptions.none()) + + /** @see list */ + fun list(requestOptions: RequestOptions): CompletableFuture> = + list(CustomMetadataFieldListParams.none(), requestOptions) + + /** + * This API deletes a custom metadata field. Even after deleting a custom metadata field, you + * cannot create any new custom metadata field with the same name. + */ + fun delete(id: String): CompletableFuture = + delete(id, CustomMetadataFieldDeleteParams.none()) + + /** @see delete */ + fun delete( + id: String, + params: CustomMetadataFieldDeleteParams = CustomMetadataFieldDeleteParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = + delete(params.toBuilder().id(id).build(), requestOptions) + + /** @see delete */ + fun delete( + id: String, + params: CustomMetadataFieldDeleteParams = CustomMetadataFieldDeleteParams.none(), + ): CompletableFuture = + delete(id, params, RequestOptions.none()) + + /** @see delete */ + fun delete( + params: CustomMetadataFieldDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** @see delete */ + fun delete( + params: CustomMetadataFieldDeleteParams + ): CompletableFuture = delete(params, RequestOptions.none()) + + /** @see delete */ + fun delete( + id: String, + requestOptions: RequestOptions, + ): CompletableFuture = + delete(id, CustomMetadataFieldDeleteParams.none(), requestOptions) + + /** + * A view of [CustomMetadataFieldServiceAsync] that provides access to raw HTTP responses for + * each method. + */ + interface WithRawResponse { + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions( + modifier: Consumer + ): CustomMetadataFieldServiceAsync.WithRawResponse + + /** + * Returns a raw HTTP response for `post /v1/customMetadataFields`, but is otherwise the + * same as [CustomMetadataFieldServiceAsync.create]. + */ + fun create( + params: CustomMetadataFieldCreateParams + ): CompletableFuture> = + create(params, RequestOptions.none()) + + /** @see create */ + fun create( + params: CustomMetadataFieldCreateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** + * Returns a raw HTTP response for `patch /v1/customMetadataFields/{id}`, but is otherwise + * the same as [CustomMetadataFieldServiceAsync.update]. + */ + fun update(id: String): CompletableFuture> = + update(id, CustomMetadataFieldUpdateParams.none()) + + /** @see update */ + fun update( + id: String, + params: CustomMetadataFieldUpdateParams = CustomMetadataFieldUpdateParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> = + update(params.toBuilder().id(id).build(), requestOptions) + + /** @see update */ + fun update( + id: String, + params: CustomMetadataFieldUpdateParams = CustomMetadataFieldUpdateParams.none(), + ): CompletableFuture> = + update(id, params, RequestOptions.none()) + + /** @see update */ + fun update( + params: CustomMetadataFieldUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see update */ + fun update( + params: CustomMetadataFieldUpdateParams + ): CompletableFuture> = + update(params, RequestOptions.none()) + + /** @see update */ + fun update( + id: String, + requestOptions: RequestOptions, + ): CompletableFuture> = + update(id, CustomMetadataFieldUpdateParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `get /v1/customMetadataFields`, but is otherwise the same + * as [CustomMetadataFieldServiceAsync.list]. + */ + fun list(): CompletableFuture>> = + list(CustomMetadataFieldListParams.none()) + + /** @see list */ + fun list( + params: CustomMetadataFieldListParams = CustomMetadataFieldListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture>> + + /** @see list */ + fun list( + params: CustomMetadataFieldListParams = CustomMetadataFieldListParams.none() + ): CompletableFuture>> = + list(params, RequestOptions.none()) + + /** @see list */ + fun list( + requestOptions: RequestOptions + ): CompletableFuture>> = + list(CustomMetadataFieldListParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `delete /v1/customMetadataFields/{id}`, but is otherwise + * the same as [CustomMetadataFieldServiceAsync.delete]. + */ + fun delete( + id: String + ): CompletableFuture> = + delete(id, CustomMetadataFieldDeleteParams.none()) + + /** @see delete */ + fun delete( + id: String, + params: CustomMetadataFieldDeleteParams = CustomMetadataFieldDeleteParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> = + delete(params.toBuilder().id(id).build(), requestOptions) + + /** @see delete */ + fun delete( + id: String, + params: CustomMetadataFieldDeleteParams = CustomMetadataFieldDeleteParams.none(), + ): CompletableFuture> = + delete(id, params, RequestOptions.none()) + + /** @see delete */ + fun delete( + params: CustomMetadataFieldDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see delete */ + fun delete( + params: CustomMetadataFieldDeleteParams + ): CompletableFuture> = + delete(params, RequestOptions.none()) + + /** @see delete */ + fun delete( + id: String, + requestOptions: RequestOptions, + ): CompletableFuture> = + delete(id, CustomMetadataFieldDeleteParams.none(), requestOptions) + } +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/CustomMetadataFieldServiceAsyncImpl.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/CustomMetadataFieldServiceAsyncImpl.kt new file mode 100644 index 0000000..35d3ee2 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/CustomMetadataFieldServiceAsyncImpl.kt @@ -0,0 +1,216 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.async + +import com.imagekit.api.core.ClientOptions +import com.imagekit.api.core.RequestOptions +import com.imagekit.api.core.checkRequired +import com.imagekit.api.core.handlers.errorBodyHandler +import com.imagekit.api.core.handlers.errorHandler +import com.imagekit.api.core.handlers.jsonHandler +import com.imagekit.api.core.http.HttpMethod +import com.imagekit.api.core.http.HttpRequest +import com.imagekit.api.core.http.HttpResponse +import com.imagekit.api.core.http.HttpResponse.Handler +import com.imagekit.api.core.http.HttpResponseFor +import com.imagekit.api.core.http.json +import com.imagekit.api.core.http.parseable +import com.imagekit.api.core.prepareAsync +import com.imagekit.api.models.custommetadatafields.CustomMetadataField +import com.imagekit.api.models.custommetadatafields.CustomMetadataFieldCreateParams +import com.imagekit.api.models.custommetadatafields.CustomMetadataFieldDeleteParams +import com.imagekit.api.models.custommetadatafields.CustomMetadataFieldDeleteResponse +import com.imagekit.api.models.custommetadatafields.CustomMetadataFieldListParams +import com.imagekit.api.models.custommetadatafields.CustomMetadataFieldUpdateParams +import java.util.concurrent.CompletableFuture +import java.util.function.Consumer +import kotlin.jvm.optionals.getOrNull + +class CustomMetadataFieldServiceAsyncImpl +internal constructor(private val clientOptions: ClientOptions) : CustomMetadataFieldServiceAsync { + + private val withRawResponse: CustomMetadataFieldServiceAsync.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + override fun withRawResponse(): CustomMetadataFieldServiceAsync.WithRawResponse = + withRawResponse + + override fun withOptions( + modifier: Consumer + ): CustomMetadataFieldServiceAsync = + CustomMetadataFieldServiceAsyncImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + override fun create( + params: CustomMetadataFieldCreateParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // post /v1/customMetadataFields + withRawResponse().create(params, requestOptions).thenApply { it.parse() } + + override fun update( + params: CustomMetadataFieldUpdateParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // patch /v1/customMetadataFields/{id} + withRawResponse().update(params, requestOptions).thenApply { it.parse() } + + override fun list( + params: CustomMetadataFieldListParams, + requestOptions: RequestOptions, + ): CompletableFuture> = + // get /v1/customMetadataFields + withRawResponse().list(params, requestOptions).thenApply { it.parse() } + + override fun delete( + params: CustomMetadataFieldDeleteParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // delete /v1/customMetadataFields/{id} + withRawResponse().delete(params, requestOptions).thenApply { it.parse() } + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + CustomMetadataFieldServiceAsync.WithRawResponse { + + private val errorHandler: Handler = + errorHandler(errorBodyHandler(clientOptions.jsonMapper)) + + override fun withOptions( + modifier: Consumer + ): CustomMetadataFieldServiceAsync.WithRawResponse = + CustomMetadataFieldServiceAsyncImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + private val createHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun create( + params: CustomMetadataFieldCreateParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "customMetadataFields") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { createHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + + private val updateHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun update( + params: CustomMetadataFieldUpdateParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("id", params.id().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.PATCH) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "customMetadataFields", params._pathParam(0)) + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { updateHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + + private val listHandler: Handler> = + jsonHandler>(clientOptions.jsonMapper) + + override fun list( + params: CustomMetadataFieldListParams, + requestOptions: RequestOptions, + ): CompletableFuture>> { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "customMetadataFields") + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { listHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.forEach { it.validate() } + } + } + } + } + } + + private val deleteHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun delete( + params: CustomMetadataFieldDeleteParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("id", params.id().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.DELETE) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "customMetadataFields", params._pathParam(0)) + .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { deleteHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + } +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/FileServiceAsync.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/FileServiceAsync.kt new file mode 100644 index 0000000..f5db6fe --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/FileServiceAsync.kt @@ -0,0 +1,420 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.async + +import com.imagekit.api.core.ClientOptions +import com.imagekit.api.core.RequestOptions +import com.imagekit.api.core.http.HttpResponse +import com.imagekit.api.core.http.HttpResponseFor +import com.imagekit.api.models.files.File +import com.imagekit.api.models.files.FileCopyParams +import com.imagekit.api.models.files.FileCopyResponse +import com.imagekit.api.models.files.FileDeleteParams +import com.imagekit.api.models.files.FileGetParams +import com.imagekit.api.models.files.FileMoveParams +import com.imagekit.api.models.files.FileMoveResponse +import com.imagekit.api.models.files.FileRenameParams +import com.imagekit.api.models.files.FileRenameResponse +import com.imagekit.api.models.files.FileUpdateParams +import com.imagekit.api.models.files.FileUpdateResponse +import com.imagekit.api.models.files.FileUploadParams +import com.imagekit.api.models.files.FileUploadResponse +import com.imagekit.api.services.async.files.BulkServiceAsync +import com.imagekit.api.services.async.files.MetadataServiceAsync +import com.imagekit.api.services.async.files.VersionServiceAsync +import java.util.concurrent.CompletableFuture +import java.util.function.Consumer + +interface FileServiceAsync { + + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): FileServiceAsync + + fun bulk(): BulkServiceAsync + + fun versions(): VersionServiceAsync + + fun metadata(): MetadataServiceAsync + + /** + * This API updates the details or attributes of the current version of the file. You can update + * `tags`, `customCoordinates`, `customMetadata`, publication status, remove existing `AITags` + * and apply extensions using this API. + */ + fun update(fileId: String): CompletableFuture = + update(fileId, FileUpdateParams.none()) + + /** @see update */ + fun update( + fileId: String, + params: FileUpdateParams = FileUpdateParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = + update(params.toBuilder().fileId(fileId).build(), requestOptions) + + /** @see update */ + fun update( + fileId: String, + params: FileUpdateParams = FileUpdateParams.none(), + ): CompletableFuture = update(fileId, params, RequestOptions.none()) + + /** @see update */ + fun update( + params: FileUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** @see update */ + fun update(params: FileUpdateParams): CompletableFuture = + update(params, RequestOptions.none()) + + /** @see update */ + fun update( + fileId: String, + requestOptions: RequestOptions, + ): CompletableFuture = + update(fileId, FileUpdateParams.none(), requestOptions) + + /** + * This API deletes the file and all its file versions permanently. + * + * Note: If a file or specific transformation has been requested in the past, then the response + * is cached. Deleting a file does not purge the cache. You can purge the cache using purge + * cache API. + */ + fun delete(fileId: String): CompletableFuture = delete(fileId, FileDeleteParams.none()) + + /** @see delete */ + fun delete( + fileId: String, + params: FileDeleteParams = FileDeleteParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = delete(params.toBuilder().fileId(fileId).build(), requestOptions) + + /** @see delete */ + fun delete( + fileId: String, + params: FileDeleteParams = FileDeleteParams.none(), + ): CompletableFuture = delete(fileId, params, RequestOptions.none()) + + /** @see delete */ + fun delete( + params: FileDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** @see delete */ + fun delete(params: FileDeleteParams): CompletableFuture = + delete(params, RequestOptions.none()) + + /** @see delete */ + fun delete(fileId: String, requestOptions: RequestOptions): CompletableFuture = + delete(fileId, FileDeleteParams.none(), requestOptions) + + /** + * This will copy a file from one folder to another. + * + * Note: If any file at the destination has the same name as the source file, then the source + * file and its versions (if `includeFileVersions` is set to true) will be appended to the + * destination file version history. + */ + fun copy(params: FileCopyParams): CompletableFuture = + copy(params, RequestOptions.none()) + + /** @see copy */ + fun copy( + params: FileCopyParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** + * This API returns an object with details or attributes about the current version of the file. + */ + fun get(fileId: String): CompletableFuture = get(fileId, FileGetParams.none()) + + /** @see get */ + fun get( + fileId: String, + params: FileGetParams = FileGetParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = get(params.toBuilder().fileId(fileId).build(), requestOptions) + + /** @see get */ + fun get(fileId: String, params: FileGetParams = FileGetParams.none()): CompletableFuture = + get(fileId, params, RequestOptions.none()) + + /** @see get */ + fun get( + params: FileGetParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** @see get */ + fun get(params: FileGetParams): CompletableFuture = get(params, RequestOptions.none()) + + /** @see get */ + fun get(fileId: String, requestOptions: RequestOptions): CompletableFuture = + get(fileId, FileGetParams.none(), requestOptions) + + /** + * This will move a file and all its versions from one folder to another. + * + * Note: If any file at the destination has the same name as the source file, then the source + * file and its versions will be appended to the destination file. + */ + fun move(params: FileMoveParams): CompletableFuture = + move(params, RequestOptions.none()) + + /** @see move */ + fun move( + params: FileMoveParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** + * You can rename an already existing file in the media library using rename file API. This + * operation would rename all file versions of the file. + * + * Note: The old URLs will stop working. The file/file version URLs cached on CDN will continue + * to work unless a purge is requested. + */ + fun rename(params: FileRenameParams): CompletableFuture = + rename(params, RequestOptions.none()) + + /** @see rename */ + fun rename( + params: FileRenameParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** + * ImageKit.io allows you to upload files directly from both the server and client sides. For + * server-side uploads, private API key authentication is used. For client-side uploads, + * generate a one-time `token`, `signature`, and `expire` from your secure backend using private + * API. + * [Learn more](/docs/api-reference/upload-file/upload-file#how-to-implement-client-side-file-upload) + * about how to implement client-side file upload. + * + * The [V2 API](/docs/api-reference/upload-file/upload-file-v2) enhances security by verifying + * the entire payload using JWT. + * + * **File size limit** \ On the free plan, the maximum upload file sizes are 20MB for images, + * audio, and raw files and 100MB for videos. On the paid plan, these limits increase to 40MB + * for images, audio, and raw files and 2GB for videos. These limits can be further increased + * with higher-tier plans. + * + * **Version limit** \ A file can have a maximum of 100 versions. + * + * **Demo applications** + * - A full-fledged + * [upload widget using Uppy](https://github.com/imagekit-samples/uppy-uploader), supporting + * file selections from local storage, URL, Dropbox, Google Drive, Instagram, and more. + * - [Quick start guides](/docs/quick-start-guides) for various frameworks and technologies. + */ + fun upload(params: FileUploadParams): CompletableFuture = + upload(params, RequestOptions.none()) + + /** @see upload */ + fun upload( + params: FileUploadParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** A view of [FileServiceAsync] that provides access to raw HTTP responses for each method. */ + interface WithRawResponse { + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): FileServiceAsync.WithRawResponse + + fun bulk(): BulkServiceAsync.WithRawResponse + + fun versions(): VersionServiceAsync.WithRawResponse + + fun metadata(): MetadataServiceAsync.WithRawResponse + + /** + * Returns a raw HTTP response for `patch /v1/files/{fileId}/details`, but is otherwise the + * same as [FileServiceAsync.update]. + */ + fun update(fileId: String): CompletableFuture> = + update(fileId, FileUpdateParams.none()) + + /** @see update */ + fun update( + fileId: String, + params: FileUpdateParams = FileUpdateParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> = + update(params.toBuilder().fileId(fileId).build(), requestOptions) + + /** @see update */ + fun update( + fileId: String, + params: FileUpdateParams = FileUpdateParams.none(), + ): CompletableFuture> = + update(fileId, params, RequestOptions.none()) + + /** @see update */ + fun update( + params: FileUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see update */ + fun update( + params: FileUpdateParams + ): CompletableFuture> = + update(params, RequestOptions.none()) + + /** @see update */ + fun update( + fileId: String, + requestOptions: RequestOptions, + ): CompletableFuture> = + update(fileId, FileUpdateParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `delete /v1/files/{fileId}`, but is otherwise the same as + * [FileServiceAsync.delete]. + */ + fun delete(fileId: String): CompletableFuture = + delete(fileId, FileDeleteParams.none()) + + /** @see delete */ + fun delete( + fileId: String, + params: FileDeleteParams = FileDeleteParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = + delete(params.toBuilder().fileId(fileId).build(), requestOptions) + + /** @see delete */ + fun delete( + fileId: String, + params: FileDeleteParams = FileDeleteParams.none(), + ): CompletableFuture = delete(fileId, params, RequestOptions.none()) + + /** @see delete */ + fun delete( + params: FileDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** @see delete */ + fun delete(params: FileDeleteParams): CompletableFuture = + delete(params, RequestOptions.none()) + + /** @see delete */ + fun delete( + fileId: String, + requestOptions: RequestOptions, + ): CompletableFuture = delete(fileId, FileDeleteParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `post /v1/files/copy`, but is otherwise the same as + * [FileServiceAsync.copy]. + */ + fun copy(params: FileCopyParams): CompletableFuture> = + copy(params, RequestOptions.none()) + + /** @see copy */ + fun copy( + params: FileCopyParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** + * Returns a raw HTTP response for `get /v1/files/{fileId}/details`, but is otherwise the + * same as [FileServiceAsync.get]. + */ + fun get(fileId: String): CompletableFuture> = + get(fileId, FileGetParams.none()) + + /** @see get */ + fun get( + fileId: String, + params: FileGetParams = FileGetParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> = + get(params.toBuilder().fileId(fileId).build(), requestOptions) + + /** @see get */ + fun get( + fileId: String, + params: FileGetParams = FileGetParams.none(), + ): CompletableFuture> = get(fileId, params, RequestOptions.none()) + + /** @see get */ + fun get( + params: FileGetParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see get */ + fun get(params: FileGetParams): CompletableFuture> = + get(params, RequestOptions.none()) + + /** @see get */ + fun get( + fileId: String, + requestOptions: RequestOptions, + ): CompletableFuture> = + get(fileId, FileGetParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `post /v1/files/move`, but is otherwise the same as + * [FileServiceAsync.move]. + */ + fun move(params: FileMoveParams): CompletableFuture> = + move(params, RequestOptions.none()) + + /** @see move */ + fun move( + params: FileMoveParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** + * Returns a raw HTTP response for `put /v1/files/rename`, but is otherwise the same as + * [FileServiceAsync.rename]. + */ + fun rename( + params: FileRenameParams + ): CompletableFuture> = + rename(params, RequestOptions.none()) + + /** @see rename */ + fun rename( + params: FileRenameParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** + * Returns a raw HTTP response for `post /api/v1/files/upload`, but is otherwise the same as + * [FileServiceAsync.upload]. + */ + fun upload( + params: FileUploadParams + ): CompletableFuture> = + upload(params, RequestOptions.none()) + + /** @see upload */ + fun upload( + params: FileUploadParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + } +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/FileServiceAsyncImpl.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/FileServiceAsyncImpl.kt new file mode 100644 index 0000000..bafc472 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/FileServiceAsyncImpl.kt @@ -0,0 +1,368 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.async + +import com.imagekit.api.core.ClientOptions +import com.imagekit.api.core.RequestOptions +import com.imagekit.api.core.checkRequired +import com.imagekit.api.core.handlers.emptyHandler +import com.imagekit.api.core.handlers.errorBodyHandler +import com.imagekit.api.core.handlers.errorHandler +import com.imagekit.api.core.handlers.jsonHandler +import com.imagekit.api.core.http.HttpMethod +import com.imagekit.api.core.http.HttpRequest +import com.imagekit.api.core.http.HttpResponse +import com.imagekit.api.core.http.HttpResponse.Handler +import com.imagekit.api.core.http.HttpResponseFor +import com.imagekit.api.core.http.json +import com.imagekit.api.core.http.multipartFormData +import com.imagekit.api.core.http.parseable +import com.imagekit.api.core.prepareAsync +import com.imagekit.api.models.files.File +import com.imagekit.api.models.files.FileCopyParams +import com.imagekit.api.models.files.FileCopyResponse +import com.imagekit.api.models.files.FileDeleteParams +import com.imagekit.api.models.files.FileGetParams +import com.imagekit.api.models.files.FileMoveParams +import com.imagekit.api.models.files.FileMoveResponse +import com.imagekit.api.models.files.FileRenameParams +import com.imagekit.api.models.files.FileRenameResponse +import com.imagekit.api.models.files.FileUpdateParams +import com.imagekit.api.models.files.FileUpdateResponse +import com.imagekit.api.models.files.FileUploadParams +import com.imagekit.api.models.files.FileUploadResponse +import com.imagekit.api.services.async.files.BulkServiceAsync +import com.imagekit.api.services.async.files.BulkServiceAsyncImpl +import com.imagekit.api.services.async.files.MetadataServiceAsync +import com.imagekit.api.services.async.files.MetadataServiceAsyncImpl +import com.imagekit.api.services.async.files.VersionServiceAsync +import com.imagekit.api.services.async.files.VersionServiceAsyncImpl +import java.util.concurrent.CompletableFuture +import java.util.function.Consumer +import kotlin.jvm.optionals.getOrNull + +class FileServiceAsyncImpl internal constructor(private val clientOptions: ClientOptions) : + FileServiceAsync { + + private val withRawResponse: FileServiceAsync.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + private val bulk: BulkServiceAsync by lazy { BulkServiceAsyncImpl(clientOptions) } + + private val versions: VersionServiceAsync by lazy { VersionServiceAsyncImpl(clientOptions) } + + private val metadata: MetadataServiceAsync by lazy { MetadataServiceAsyncImpl(clientOptions) } + + override fun withRawResponse(): FileServiceAsync.WithRawResponse = withRawResponse + + override fun withOptions(modifier: Consumer): FileServiceAsync = + FileServiceAsyncImpl(clientOptions.toBuilder().apply(modifier::accept).build()) + + override fun bulk(): BulkServiceAsync = bulk + + override fun versions(): VersionServiceAsync = versions + + override fun metadata(): MetadataServiceAsync = metadata + + override fun update( + params: FileUpdateParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // patch /v1/files/{fileId}/details + withRawResponse().update(params, requestOptions).thenApply { it.parse() } + + override fun delete( + params: FileDeleteParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // delete /v1/files/{fileId} + withRawResponse().delete(params, requestOptions).thenAccept {} + + override fun copy( + params: FileCopyParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // post /v1/files/copy + withRawResponse().copy(params, requestOptions).thenApply { it.parse() } + + override fun get( + params: FileGetParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // get /v1/files/{fileId}/details + withRawResponse().get(params, requestOptions).thenApply { it.parse() } + + override fun move( + params: FileMoveParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // post /v1/files/move + withRawResponse().move(params, requestOptions).thenApply { it.parse() } + + override fun rename( + params: FileRenameParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // put /v1/files/rename + withRawResponse().rename(params, requestOptions).thenApply { it.parse() } + + override fun upload( + params: FileUploadParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // post /api/v1/files/upload + withRawResponse().upload(params, requestOptions).thenApply { it.parse() } + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + FileServiceAsync.WithRawResponse { + + private val errorHandler: Handler = + errorHandler(errorBodyHandler(clientOptions.jsonMapper)) + + private val bulk: BulkServiceAsync.WithRawResponse by lazy { + BulkServiceAsyncImpl.WithRawResponseImpl(clientOptions) + } + + private val versions: VersionServiceAsync.WithRawResponse by lazy { + VersionServiceAsyncImpl.WithRawResponseImpl(clientOptions) + } + + private val metadata: MetadataServiceAsync.WithRawResponse by lazy { + MetadataServiceAsyncImpl.WithRawResponseImpl(clientOptions) + } + + override fun withOptions( + modifier: Consumer + ): FileServiceAsync.WithRawResponse = + FileServiceAsyncImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + override fun bulk(): BulkServiceAsync.WithRawResponse = bulk + + override fun versions(): VersionServiceAsync.WithRawResponse = versions + + override fun metadata(): MetadataServiceAsync.WithRawResponse = metadata + + private val updateHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun update( + params: FileUpdateParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("fileId", params.fileId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.PATCH) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "files", params._pathParam(0), "details") + .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { updateHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + + private val deleteHandler: Handler = emptyHandler() + + override fun delete( + params: FileDeleteParams, + requestOptions: RequestOptions, + ): CompletableFuture { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("fileId", params.fileId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.DELETE) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "files", params._pathParam(0)) + .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response.use { deleteHandler.handle(it) } + } + } + } + + private val copyHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun copy( + params: FileCopyParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "files", "copy") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { copyHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + + private val getHandler: Handler = jsonHandler(clientOptions.jsonMapper) + + override fun get( + params: FileGetParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("fileId", params.fileId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "files", params._pathParam(0), "details") + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { getHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + + private val moveHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun move( + params: FileMoveParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "files", "move") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { moveHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + + private val renameHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun rename( + params: FileRenameParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.PUT) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "files", "rename") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { renameHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + + private val uploadHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun upload( + params: FileUploadParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl( + if (clientOptions.baseUrlOverridden()) clientOptions.baseUrl() + else "https://upload.imagekit.io" + ) + .addPathSegments("api", "v1", "files", "upload") + .body(multipartFormData(clientOptions.jsonMapper, params._body())) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { uploadHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + } +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/FolderServiceAsync.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/FolderServiceAsync.kt new file mode 100644 index 0000000..aaa08ff --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/FolderServiceAsync.kt @@ -0,0 +1,195 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.async + +import com.imagekit.api.core.ClientOptions +import com.imagekit.api.core.RequestOptions +import com.imagekit.api.core.http.HttpResponseFor +import com.imagekit.api.models.folders.FolderCopyParams +import com.imagekit.api.models.folders.FolderCopyResponse +import com.imagekit.api.models.folders.FolderCreateParams +import com.imagekit.api.models.folders.FolderCreateResponse +import com.imagekit.api.models.folders.FolderDeleteParams +import com.imagekit.api.models.folders.FolderDeleteResponse +import com.imagekit.api.models.folders.FolderMoveParams +import com.imagekit.api.models.folders.FolderMoveResponse +import com.imagekit.api.models.folders.FolderRenameParams +import com.imagekit.api.models.folders.FolderRenameResponse +import com.imagekit.api.services.async.folders.JobServiceAsync +import java.util.concurrent.CompletableFuture +import java.util.function.Consumer + +interface FolderServiceAsync { + + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): FolderServiceAsync + + fun job(): JobServiceAsync + + /** + * This will create a new folder. You can specify the folder name and location of the parent + * folder where this new folder should be created. + */ + fun create(params: FolderCreateParams): CompletableFuture = + create(params, RequestOptions.none()) + + /** @see create */ + fun create( + params: FolderCreateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** + * This will delete a folder and all its contents permanently. The API returns an empty + * response. + */ + fun delete(params: FolderDeleteParams): CompletableFuture = + delete(params, RequestOptions.none()) + + /** @see delete */ + fun delete( + params: FolderDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** + * This will copy one folder into another. The selected folder, its nested folders, files, and + * their versions (in `includeVersions` is set to true) are copied in this operation. Note: If + * any file at the destination has the same name as the source file, then the source file and + * its versions will be appended to the destination file version history. + */ + fun copy(params: FolderCopyParams): CompletableFuture = + copy(params, RequestOptions.none()) + + /** @see copy */ + fun copy( + params: FolderCopyParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** + * This will move one folder into another. The selected folder, its nested folders, files, and + * their versions are moved in this operation. Note: If any file at the destination has the same + * name as the source file, then the source file and its versions will be appended to the + * destination file version history. + */ + fun move(params: FolderMoveParams): CompletableFuture = + move(params, RequestOptions.none()) + + /** @see move */ + fun move( + params: FolderMoveParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** + * This API allows you to rename an existing folder. The folder and all its nested assets and + * sub-folders will remain unchanged, but their paths will be updated to reflect the new folder + * name. + */ + fun rename(params: FolderRenameParams): CompletableFuture = + rename(params, RequestOptions.none()) + + /** @see rename */ + fun rename( + params: FolderRenameParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** + * A view of [FolderServiceAsync] that provides access to raw HTTP responses for each method. + */ + interface WithRawResponse { + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions( + modifier: Consumer + ): FolderServiceAsync.WithRawResponse + + fun job(): JobServiceAsync.WithRawResponse + + /** + * Returns a raw HTTP response for `post /v1/folder`, but is otherwise the same as + * [FolderServiceAsync.create]. + */ + fun create( + params: FolderCreateParams + ): CompletableFuture> = + create(params, RequestOptions.none()) + + /** @see create */ + fun create( + params: FolderCreateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** + * Returns a raw HTTP response for `delete /v1/folder`, but is otherwise the same as + * [FolderServiceAsync.delete]. + */ + fun delete( + params: FolderDeleteParams + ): CompletableFuture> = + delete(params, RequestOptions.none()) + + /** @see delete */ + fun delete( + params: FolderDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** + * Returns a raw HTTP response for `post /v1/bulkJobs/copyFolder`, but is otherwise the same + * as [FolderServiceAsync.copy]. + */ + fun copy(params: FolderCopyParams): CompletableFuture> = + copy(params, RequestOptions.none()) + + /** @see copy */ + fun copy( + params: FolderCopyParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** + * Returns a raw HTTP response for `post /v1/bulkJobs/moveFolder`, but is otherwise the same + * as [FolderServiceAsync.move]. + */ + fun move(params: FolderMoveParams): CompletableFuture> = + move(params, RequestOptions.none()) + + /** @see move */ + fun move( + params: FolderMoveParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** + * Returns a raw HTTP response for `post /v1/bulkJobs/renameFolder`, but is otherwise the + * same as [FolderServiceAsync.rename]. + */ + fun rename( + params: FolderRenameParams + ): CompletableFuture> = + rename(params, RequestOptions.none()) + + /** @see rename */ + fun rename( + params: FolderRenameParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + } +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/FolderServiceAsyncImpl.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/FolderServiceAsyncImpl.kt new file mode 100644 index 0000000..426fe09 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/FolderServiceAsyncImpl.kt @@ -0,0 +1,258 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.async + +import com.imagekit.api.core.ClientOptions +import com.imagekit.api.core.RequestOptions +import com.imagekit.api.core.handlers.errorBodyHandler +import com.imagekit.api.core.handlers.errorHandler +import com.imagekit.api.core.handlers.jsonHandler +import com.imagekit.api.core.http.HttpMethod +import com.imagekit.api.core.http.HttpRequest +import com.imagekit.api.core.http.HttpResponse +import com.imagekit.api.core.http.HttpResponse.Handler +import com.imagekit.api.core.http.HttpResponseFor +import com.imagekit.api.core.http.json +import com.imagekit.api.core.http.parseable +import com.imagekit.api.core.prepareAsync +import com.imagekit.api.models.folders.FolderCopyParams +import com.imagekit.api.models.folders.FolderCopyResponse +import com.imagekit.api.models.folders.FolderCreateParams +import com.imagekit.api.models.folders.FolderCreateResponse +import com.imagekit.api.models.folders.FolderDeleteParams +import com.imagekit.api.models.folders.FolderDeleteResponse +import com.imagekit.api.models.folders.FolderMoveParams +import com.imagekit.api.models.folders.FolderMoveResponse +import com.imagekit.api.models.folders.FolderRenameParams +import com.imagekit.api.models.folders.FolderRenameResponse +import com.imagekit.api.services.async.folders.JobServiceAsync +import com.imagekit.api.services.async.folders.JobServiceAsyncImpl +import java.util.concurrent.CompletableFuture +import java.util.function.Consumer + +class FolderServiceAsyncImpl internal constructor(private val clientOptions: ClientOptions) : + FolderServiceAsync { + + private val withRawResponse: FolderServiceAsync.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + private val job: JobServiceAsync by lazy { JobServiceAsyncImpl(clientOptions) } + + override fun withRawResponse(): FolderServiceAsync.WithRawResponse = withRawResponse + + override fun withOptions(modifier: Consumer): FolderServiceAsync = + FolderServiceAsyncImpl(clientOptions.toBuilder().apply(modifier::accept).build()) + + override fun job(): JobServiceAsync = job + + override fun create( + params: FolderCreateParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // post /v1/folder + withRawResponse().create(params, requestOptions).thenApply { it.parse() } + + override fun delete( + params: FolderDeleteParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // delete /v1/folder + withRawResponse().delete(params, requestOptions).thenApply { it.parse() } + + override fun copy( + params: FolderCopyParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // post /v1/bulkJobs/copyFolder + withRawResponse().copy(params, requestOptions).thenApply { it.parse() } + + override fun move( + params: FolderMoveParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // post /v1/bulkJobs/moveFolder + withRawResponse().move(params, requestOptions).thenApply { it.parse() } + + override fun rename( + params: FolderRenameParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // post /v1/bulkJobs/renameFolder + withRawResponse().rename(params, requestOptions).thenApply { it.parse() } + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + FolderServiceAsync.WithRawResponse { + + private val errorHandler: Handler = + errorHandler(errorBodyHandler(clientOptions.jsonMapper)) + + private val job: JobServiceAsync.WithRawResponse by lazy { + JobServiceAsyncImpl.WithRawResponseImpl(clientOptions) + } + + override fun withOptions( + modifier: Consumer + ): FolderServiceAsync.WithRawResponse = + FolderServiceAsyncImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + override fun job(): JobServiceAsync.WithRawResponse = job + + private val createHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun create( + params: FolderCreateParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "folder") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { createHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + + private val deleteHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun delete( + params: FolderDeleteParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.DELETE) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "folder") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { deleteHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + + private val copyHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun copy( + params: FolderCopyParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "bulkJobs", "copyFolder") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { copyHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + + private val moveHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun move( + params: FolderMoveParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "bulkJobs", "moveFolder") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { moveHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + + private val renameHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun rename( + params: FolderRenameParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "bulkJobs", "renameFolder") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { renameHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + } +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/WebhookServiceAsync.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/WebhookServiceAsync.kt new file mode 100644 index 0000000..68d1641 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/WebhookServiceAsync.kt @@ -0,0 +1,53 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.async + +import com.imagekit.api.core.ClientOptions +import com.imagekit.api.errors.ImageKitInvalidDataException +import com.imagekit.api.models.webhooks.UnsafeUnwrapWebhookEvent +import com.imagekit.api.models.webhooks.UnwrapWebhookEvent +import java.util.function.Consumer + +interface WebhookServiceAsync { + + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): WebhookServiceAsync + + /** + * Unwraps a webhook event from its JSON representation. + * + * @throws ImageKitInvalidDataException if the body could not be parsed. + */ + fun unsafeUnwrap(body: String): UnsafeUnwrapWebhookEvent + + /** + * Unwraps a webhook event from its JSON representation. + * + * @throws ImageKitInvalidDataException if the body could not be parsed. + */ + fun unwrap(body: String): UnwrapWebhookEvent + + /** + * A view of [WebhookServiceAsync] that provides access to raw HTTP responses for each method. + */ + interface WithRawResponse { + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions( + modifier: Consumer + ): WebhookServiceAsync.WithRawResponse + } +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/WebhookServiceAsyncImpl.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/WebhookServiceAsyncImpl.kt new file mode 100644 index 0000000..b2c9b20 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/WebhookServiceAsyncImpl.kt @@ -0,0 +1,50 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.async + +import com.imagekit.api.core.ClientOptions +import com.imagekit.api.errors.ImageKitInvalidDataException +import com.imagekit.api.models.webhooks.UnsafeUnwrapWebhookEvent +import com.imagekit.api.models.webhooks.UnwrapWebhookEvent +import com.imagekit.api.services.blocking.WebhookServiceImpl +import java.util.function.Consumer + +class WebhookServiceAsyncImpl internal constructor(private val clientOptions: ClientOptions) : + WebhookServiceAsync { + + private val withRawResponse: WebhookServiceAsync.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + override fun withRawResponse(): WebhookServiceAsync.WithRawResponse = withRawResponse + + override fun withOptions(modifier: Consumer): WebhookServiceAsync = + WebhookServiceAsyncImpl(clientOptions.toBuilder().apply(modifier::accept).build()) + + /** + * Unwraps a webhook event from its JSON representation. + * + * @throws ImageKitInvalidDataException if the body could not be parsed. + */ + override fun unsafeUnwrap(body: String): UnsafeUnwrapWebhookEvent = + WebhookServiceImpl(clientOptions).unsafeUnwrap(body) + + /** + * Unwraps a webhook event from its JSON representation. + * + * @throws ImageKitInvalidDataException if the body could not be parsed. + */ + override fun unwrap(body: String): UnwrapWebhookEvent = + WebhookServiceImpl(clientOptions).unwrap(body) + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + WebhookServiceAsync.WithRawResponse { + + override fun withOptions( + modifier: Consumer + ): WebhookServiceAsync.WithRawResponse = + WebhookServiceAsyncImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + } +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/accounts/OriginServiceAsync.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/accounts/OriginServiceAsync.kt new file mode 100644 index 0000000..0852af1 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/accounts/OriginServiceAsync.kt @@ -0,0 +1,306 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.async.accounts + +import com.imagekit.api.core.ClientOptions +import com.imagekit.api.core.RequestOptions +import com.imagekit.api.core.http.HttpResponse +import com.imagekit.api.core.http.HttpResponseFor +import com.imagekit.api.models.accounts.origins.OriginCreateParams +import com.imagekit.api.models.accounts.origins.OriginDeleteParams +import com.imagekit.api.models.accounts.origins.OriginGetParams +import com.imagekit.api.models.accounts.origins.OriginListParams +import com.imagekit.api.models.accounts.origins.OriginResponse +import com.imagekit.api.models.accounts.origins.OriginUpdateParams +import java.util.concurrent.CompletableFuture +import java.util.function.Consumer + +interface OriginServiceAsync { + + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): OriginServiceAsync + + /** + * **Note:** This API is currently in beta. Creates a new origin and returns the origin object. + */ + fun create(params: OriginCreateParams): CompletableFuture = + create(params, RequestOptions.none()) + + /** @see create */ + fun create( + params: OriginCreateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** + * **Note:** This API is currently in beta. Updates the origin identified by `id` and returns + * the updated origin object. + */ + fun update(id: String, params: OriginUpdateParams): CompletableFuture = + update(id, params, RequestOptions.none()) + + /** @see update */ + fun update( + id: String, + params: OriginUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = update(params.toBuilder().id(id).build(), requestOptions) + + /** @see update */ + fun update(params: OriginUpdateParams): CompletableFuture = + update(params, RequestOptions.none()) + + /** @see update */ + fun update( + params: OriginUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** + * **Note:** This API is currently in beta. Returns an array of all configured origins for the + * current account. + */ + fun list(): CompletableFuture> = list(OriginListParams.none()) + + /** @see list */ + fun list( + params: OriginListParams = OriginListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see list */ + fun list( + params: OriginListParams = OriginListParams.none() + ): CompletableFuture> = list(params, RequestOptions.none()) + + /** @see list */ + fun list(requestOptions: RequestOptions): CompletableFuture> = + list(OriginListParams.none(), requestOptions) + + /** + * **Note:** This API is currently in beta. Permanently removes the origin identified by `id`. + * If the origin is in use by any URL‑endpoints, the API will return an error. + */ + fun delete(id: String): CompletableFuture = delete(id, OriginDeleteParams.none()) + + /** @see delete */ + fun delete( + id: String, + params: OriginDeleteParams = OriginDeleteParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = delete(params.toBuilder().id(id).build(), requestOptions) + + /** @see delete */ + fun delete( + id: String, + params: OriginDeleteParams = OriginDeleteParams.none(), + ): CompletableFuture = delete(id, params, RequestOptions.none()) + + /** @see delete */ + fun delete( + params: OriginDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** @see delete */ + fun delete(params: OriginDeleteParams): CompletableFuture = + delete(params, RequestOptions.none()) + + /** @see delete */ + fun delete(id: String, requestOptions: RequestOptions): CompletableFuture = + delete(id, OriginDeleteParams.none(), requestOptions) + + /** **Note:** This API is currently in beta. Retrieves the origin identified by `id`. */ + fun get(id: String): CompletableFuture = get(id, OriginGetParams.none()) + + /** @see get */ + fun get( + id: String, + params: OriginGetParams = OriginGetParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = get(params.toBuilder().id(id).build(), requestOptions) + + /** @see get */ + fun get( + id: String, + params: OriginGetParams = OriginGetParams.none(), + ): CompletableFuture = get(id, params, RequestOptions.none()) + + /** @see get */ + fun get( + params: OriginGetParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** @see get */ + fun get(params: OriginGetParams): CompletableFuture = + get(params, RequestOptions.none()) + + /** @see get */ + fun get(id: String, requestOptions: RequestOptions): CompletableFuture = + get(id, OriginGetParams.none(), requestOptions) + + /** + * A view of [OriginServiceAsync] that provides access to raw HTTP responses for each method. + */ + interface WithRawResponse { + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions( + modifier: Consumer + ): OriginServiceAsync.WithRawResponse + + /** + * Returns a raw HTTP response for `post /v1/accounts/origins`, but is otherwise the same as + * [OriginServiceAsync.create]. + */ + fun create(params: OriginCreateParams): CompletableFuture> = + create(params, RequestOptions.none()) + + /** @see create */ + fun create( + params: OriginCreateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** + * Returns a raw HTTP response for `put /v1/accounts/origins/{id}`, but is otherwise the + * same as [OriginServiceAsync.update]. + */ + fun update( + id: String, + params: OriginUpdateParams, + ): CompletableFuture> = + update(id, params, RequestOptions.none()) + + /** @see update */ + fun update( + id: String, + params: OriginUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> = + update(params.toBuilder().id(id).build(), requestOptions) + + /** @see update */ + fun update(params: OriginUpdateParams): CompletableFuture> = + update(params, RequestOptions.none()) + + /** @see update */ + fun update( + params: OriginUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** + * Returns a raw HTTP response for `get /v1/accounts/origins`, but is otherwise the same as + * [OriginServiceAsync.list]. + */ + fun list(): CompletableFuture>> = + list(OriginListParams.none()) + + /** @see list */ + fun list( + params: OriginListParams = OriginListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture>> + + /** @see list */ + fun list( + params: OriginListParams = OriginListParams.none() + ): CompletableFuture>> = + list(params, RequestOptions.none()) + + /** @see list */ + fun list( + requestOptions: RequestOptions + ): CompletableFuture>> = + list(OriginListParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `delete /v1/accounts/origins/{id}`, but is otherwise the + * same as [OriginServiceAsync.delete]. + */ + fun delete(id: String): CompletableFuture = + delete(id, OriginDeleteParams.none()) + + /** @see delete */ + fun delete( + id: String, + params: OriginDeleteParams = OriginDeleteParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = + delete(params.toBuilder().id(id).build(), requestOptions) + + /** @see delete */ + fun delete( + id: String, + params: OriginDeleteParams = OriginDeleteParams.none(), + ): CompletableFuture = delete(id, params, RequestOptions.none()) + + /** @see delete */ + fun delete( + params: OriginDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** @see delete */ + fun delete(params: OriginDeleteParams): CompletableFuture = + delete(params, RequestOptions.none()) + + /** @see delete */ + fun delete(id: String, requestOptions: RequestOptions): CompletableFuture = + delete(id, OriginDeleteParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `get /v1/accounts/origins/{id}`, but is otherwise the + * same as [OriginServiceAsync.get]. + */ + fun get(id: String): CompletableFuture> = + get(id, OriginGetParams.none()) + + /** @see get */ + fun get( + id: String, + params: OriginGetParams = OriginGetParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> = + get(params.toBuilder().id(id).build(), requestOptions) + + /** @see get */ + fun get( + id: String, + params: OriginGetParams = OriginGetParams.none(), + ): CompletableFuture> = + get(id, params, RequestOptions.none()) + + /** @see get */ + fun get( + params: OriginGetParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see get */ + fun get(params: OriginGetParams): CompletableFuture> = + get(params, RequestOptions.none()) + + /** @see get */ + fun get( + id: String, + requestOptions: RequestOptions, + ): CompletableFuture> = + get(id, OriginGetParams.none(), requestOptions) + } +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/accounts/OriginServiceAsyncImpl.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/accounts/OriginServiceAsyncImpl.kt new file mode 100644 index 0000000..7b9da70 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/accounts/OriginServiceAsyncImpl.kt @@ -0,0 +1,245 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.async.accounts + +import com.imagekit.api.core.ClientOptions +import com.imagekit.api.core.RequestOptions +import com.imagekit.api.core.checkRequired +import com.imagekit.api.core.handlers.emptyHandler +import com.imagekit.api.core.handlers.errorBodyHandler +import com.imagekit.api.core.handlers.errorHandler +import com.imagekit.api.core.handlers.jsonHandler +import com.imagekit.api.core.http.HttpMethod +import com.imagekit.api.core.http.HttpRequest +import com.imagekit.api.core.http.HttpResponse +import com.imagekit.api.core.http.HttpResponse.Handler +import com.imagekit.api.core.http.HttpResponseFor +import com.imagekit.api.core.http.json +import com.imagekit.api.core.http.parseable +import com.imagekit.api.core.prepareAsync +import com.imagekit.api.models.accounts.origins.OriginCreateParams +import com.imagekit.api.models.accounts.origins.OriginDeleteParams +import com.imagekit.api.models.accounts.origins.OriginGetParams +import com.imagekit.api.models.accounts.origins.OriginListParams +import com.imagekit.api.models.accounts.origins.OriginResponse +import com.imagekit.api.models.accounts.origins.OriginUpdateParams +import java.util.concurrent.CompletableFuture +import java.util.function.Consumer +import kotlin.jvm.optionals.getOrNull + +class OriginServiceAsyncImpl internal constructor(private val clientOptions: ClientOptions) : + OriginServiceAsync { + + private val withRawResponse: OriginServiceAsync.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + override fun withRawResponse(): OriginServiceAsync.WithRawResponse = withRawResponse + + override fun withOptions(modifier: Consumer): OriginServiceAsync = + OriginServiceAsyncImpl(clientOptions.toBuilder().apply(modifier::accept).build()) + + override fun create( + params: OriginCreateParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // post /v1/accounts/origins + withRawResponse().create(params, requestOptions).thenApply { it.parse() } + + override fun update( + params: OriginUpdateParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // put /v1/accounts/origins/{id} + withRawResponse().update(params, requestOptions).thenApply { it.parse() } + + override fun list( + params: OriginListParams, + requestOptions: RequestOptions, + ): CompletableFuture> = + // get /v1/accounts/origins + withRawResponse().list(params, requestOptions).thenApply { it.parse() } + + override fun delete( + params: OriginDeleteParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // delete /v1/accounts/origins/{id} + withRawResponse().delete(params, requestOptions).thenAccept {} + + override fun get( + params: OriginGetParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // get /v1/accounts/origins/{id} + withRawResponse().get(params, requestOptions).thenApply { it.parse() } + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + OriginServiceAsync.WithRawResponse { + + private val errorHandler: Handler = + errorHandler(errorBodyHandler(clientOptions.jsonMapper)) + + override fun withOptions( + modifier: Consumer + ): OriginServiceAsync.WithRawResponse = + OriginServiceAsyncImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + private val createHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun create( + params: OriginCreateParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "accounts", "origins") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { createHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + + private val updateHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun update( + params: OriginUpdateParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("id", params.id().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.PUT) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "accounts", "origins", params._pathParam(0)) + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { updateHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + + private val listHandler: Handler> = + jsonHandler>(clientOptions.jsonMapper) + + override fun list( + params: OriginListParams, + requestOptions: RequestOptions, + ): CompletableFuture>> { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "accounts", "origins") + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { listHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.forEach { it.validate() } + } + } + } + } + } + + private val deleteHandler: Handler = emptyHandler() + + override fun delete( + params: OriginDeleteParams, + requestOptions: RequestOptions, + ): CompletableFuture { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("id", params.id().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.DELETE) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "accounts", "origins", params._pathParam(0)) + .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response.use { deleteHandler.handle(it) } + } + } + } + + private val getHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun get( + params: OriginGetParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("id", params.id().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "accounts", "origins", params._pathParam(0)) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { getHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + } +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/accounts/UrlEndpointServiceAsync.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/accounts/UrlEndpointServiceAsync.kt new file mode 100644 index 0000000..334612e --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/accounts/UrlEndpointServiceAsync.kt @@ -0,0 +1,319 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.async.accounts + +import com.imagekit.api.core.ClientOptions +import com.imagekit.api.core.RequestOptions +import com.imagekit.api.core.http.HttpResponse +import com.imagekit.api.core.http.HttpResponseFor +import com.imagekit.api.models.accounts.urlendpoints.UrlEndpointCreateParams +import com.imagekit.api.models.accounts.urlendpoints.UrlEndpointDeleteParams +import com.imagekit.api.models.accounts.urlendpoints.UrlEndpointGetParams +import com.imagekit.api.models.accounts.urlendpoints.UrlEndpointListParams +import com.imagekit.api.models.accounts.urlendpoints.UrlEndpointResponse +import com.imagekit.api.models.accounts.urlendpoints.UrlEndpointUpdateParams +import java.util.concurrent.CompletableFuture +import java.util.function.Consumer + +interface UrlEndpointServiceAsync { + + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): UrlEndpointServiceAsync + + /** + * **Note:** This API is currently in beta. Creates a new URL‑endpoint and returns the resulting + * object. + */ + fun create(params: UrlEndpointCreateParams): CompletableFuture = + create(params, RequestOptions.none()) + + /** @see create */ + fun create( + params: UrlEndpointCreateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** + * **Note:** This API is currently in beta. Updates the URL‑endpoint identified by `id` and + * returns the updated object. + */ + fun update( + id: String, + params: UrlEndpointUpdateParams, + ): CompletableFuture = update(id, params, RequestOptions.none()) + + /** @see update */ + fun update( + id: String, + params: UrlEndpointUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = + update(params.toBuilder().id(id).build(), requestOptions) + + /** @see update */ + fun update(params: UrlEndpointUpdateParams): CompletableFuture = + update(params, RequestOptions.none()) + + /** @see update */ + fun update( + params: UrlEndpointUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** + * **Note:** This API is currently in beta. Returns an array of all URL‑endpoints configured + * including the default URL-endpoint generated by ImageKit during account creation. + */ + fun list(): CompletableFuture> = list(UrlEndpointListParams.none()) + + /** @see list */ + fun list( + params: UrlEndpointListParams = UrlEndpointListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see list */ + fun list( + params: UrlEndpointListParams = UrlEndpointListParams.none() + ): CompletableFuture> = list(params, RequestOptions.none()) + + /** @see list */ + fun list(requestOptions: RequestOptions): CompletableFuture> = + list(UrlEndpointListParams.none(), requestOptions) + + /** + * **Note:** This API is currently in beta. Deletes the URL‑endpoint identified by `id`. You + * cannot delete the default URL‑endpoint created by ImageKit during account creation. + */ + fun delete(id: String): CompletableFuture = delete(id, UrlEndpointDeleteParams.none()) + + /** @see delete */ + fun delete( + id: String, + params: UrlEndpointDeleteParams = UrlEndpointDeleteParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = delete(params.toBuilder().id(id).build(), requestOptions) + + /** @see delete */ + fun delete( + id: String, + params: UrlEndpointDeleteParams = UrlEndpointDeleteParams.none(), + ): CompletableFuture = delete(id, params, RequestOptions.none()) + + /** @see delete */ + fun delete( + params: UrlEndpointDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** @see delete */ + fun delete(params: UrlEndpointDeleteParams): CompletableFuture = + delete(params, RequestOptions.none()) + + /** @see delete */ + fun delete(id: String, requestOptions: RequestOptions): CompletableFuture = + delete(id, UrlEndpointDeleteParams.none(), requestOptions) + + /** **Note:** This API is currently in beta. Retrieves the URL‑endpoint identified by `id`. */ + fun get(id: String): CompletableFuture = + get(id, UrlEndpointGetParams.none()) + + /** @see get */ + fun get( + id: String, + params: UrlEndpointGetParams = UrlEndpointGetParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = + get(params.toBuilder().id(id).build(), requestOptions) + + /** @see get */ + fun get( + id: String, + params: UrlEndpointGetParams = UrlEndpointGetParams.none(), + ): CompletableFuture = get(id, params, RequestOptions.none()) + + /** @see get */ + fun get( + params: UrlEndpointGetParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** @see get */ + fun get(params: UrlEndpointGetParams): CompletableFuture = + get(params, RequestOptions.none()) + + /** @see get */ + fun get(id: String, requestOptions: RequestOptions): CompletableFuture = + get(id, UrlEndpointGetParams.none(), requestOptions) + + /** + * A view of [UrlEndpointServiceAsync] that provides access to raw HTTP responses for each + * method. + */ + interface WithRawResponse { + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions( + modifier: Consumer + ): UrlEndpointServiceAsync.WithRawResponse + + /** + * Returns a raw HTTP response for `post /v1/accounts/url-endpoints`, but is otherwise the + * same as [UrlEndpointServiceAsync.create]. + */ + fun create( + params: UrlEndpointCreateParams + ): CompletableFuture> = + create(params, RequestOptions.none()) + + /** @see create */ + fun create( + params: UrlEndpointCreateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** + * Returns a raw HTTP response for `put /v1/accounts/url-endpoints/{id}`, but is otherwise + * the same as [UrlEndpointServiceAsync.update]. + */ + fun update( + id: String, + params: UrlEndpointUpdateParams, + ): CompletableFuture> = + update(id, params, RequestOptions.none()) + + /** @see update */ + fun update( + id: String, + params: UrlEndpointUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> = + update(params.toBuilder().id(id).build(), requestOptions) + + /** @see update */ + fun update( + params: UrlEndpointUpdateParams + ): CompletableFuture> = + update(params, RequestOptions.none()) + + /** @see update */ + fun update( + params: UrlEndpointUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** + * Returns a raw HTTP response for `get /v1/accounts/url-endpoints`, but is otherwise the + * same as [UrlEndpointServiceAsync.list]. + */ + fun list(): CompletableFuture>> = + list(UrlEndpointListParams.none()) + + /** @see list */ + fun list( + params: UrlEndpointListParams = UrlEndpointListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture>> + + /** @see list */ + fun list( + params: UrlEndpointListParams = UrlEndpointListParams.none() + ): CompletableFuture>> = + list(params, RequestOptions.none()) + + /** @see list */ + fun list( + requestOptions: RequestOptions + ): CompletableFuture>> = + list(UrlEndpointListParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `delete /v1/accounts/url-endpoints/{id}`, but is + * otherwise the same as [UrlEndpointServiceAsync.delete]. + */ + fun delete(id: String): CompletableFuture = + delete(id, UrlEndpointDeleteParams.none()) + + /** @see delete */ + fun delete( + id: String, + params: UrlEndpointDeleteParams = UrlEndpointDeleteParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = + delete(params.toBuilder().id(id).build(), requestOptions) + + /** @see delete */ + fun delete( + id: String, + params: UrlEndpointDeleteParams = UrlEndpointDeleteParams.none(), + ): CompletableFuture = delete(id, params, RequestOptions.none()) + + /** @see delete */ + fun delete( + params: UrlEndpointDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** @see delete */ + fun delete(params: UrlEndpointDeleteParams): CompletableFuture = + delete(params, RequestOptions.none()) + + /** @see delete */ + fun delete(id: String, requestOptions: RequestOptions): CompletableFuture = + delete(id, UrlEndpointDeleteParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `get /v1/accounts/url-endpoints/{id}`, but is otherwise + * the same as [UrlEndpointServiceAsync.get]. + */ + fun get(id: String): CompletableFuture> = + get(id, UrlEndpointGetParams.none()) + + /** @see get */ + fun get( + id: String, + params: UrlEndpointGetParams = UrlEndpointGetParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> = + get(params.toBuilder().id(id).build(), requestOptions) + + /** @see get */ + fun get( + id: String, + params: UrlEndpointGetParams = UrlEndpointGetParams.none(), + ): CompletableFuture> = + get(id, params, RequestOptions.none()) + + /** @see get */ + fun get( + params: UrlEndpointGetParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see get */ + fun get( + params: UrlEndpointGetParams + ): CompletableFuture> = + get(params, RequestOptions.none()) + + /** @see get */ + fun get( + id: String, + requestOptions: RequestOptions, + ): CompletableFuture> = + get(id, UrlEndpointGetParams.none(), requestOptions) + } +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/accounts/UrlEndpointServiceAsyncImpl.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/accounts/UrlEndpointServiceAsyncImpl.kt new file mode 100644 index 0000000..de71666 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/accounts/UrlEndpointServiceAsyncImpl.kt @@ -0,0 +1,245 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.async.accounts + +import com.imagekit.api.core.ClientOptions +import com.imagekit.api.core.RequestOptions +import com.imagekit.api.core.checkRequired +import com.imagekit.api.core.handlers.emptyHandler +import com.imagekit.api.core.handlers.errorBodyHandler +import com.imagekit.api.core.handlers.errorHandler +import com.imagekit.api.core.handlers.jsonHandler +import com.imagekit.api.core.http.HttpMethod +import com.imagekit.api.core.http.HttpRequest +import com.imagekit.api.core.http.HttpResponse +import com.imagekit.api.core.http.HttpResponse.Handler +import com.imagekit.api.core.http.HttpResponseFor +import com.imagekit.api.core.http.json +import com.imagekit.api.core.http.parseable +import com.imagekit.api.core.prepareAsync +import com.imagekit.api.models.accounts.urlendpoints.UrlEndpointCreateParams +import com.imagekit.api.models.accounts.urlendpoints.UrlEndpointDeleteParams +import com.imagekit.api.models.accounts.urlendpoints.UrlEndpointGetParams +import com.imagekit.api.models.accounts.urlendpoints.UrlEndpointListParams +import com.imagekit.api.models.accounts.urlendpoints.UrlEndpointResponse +import com.imagekit.api.models.accounts.urlendpoints.UrlEndpointUpdateParams +import java.util.concurrent.CompletableFuture +import java.util.function.Consumer +import kotlin.jvm.optionals.getOrNull + +class UrlEndpointServiceAsyncImpl internal constructor(private val clientOptions: ClientOptions) : + UrlEndpointServiceAsync { + + private val withRawResponse: UrlEndpointServiceAsync.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + override fun withRawResponse(): UrlEndpointServiceAsync.WithRawResponse = withRawResponse + + override fun withOptions(modifier: Consumer): UrlEndpointServiceAsync = + UrlEndpointServiceAsyncImpl(clientOptions.toBuilder().apply(modifier::accept).build()) + + override fun create( + params: UrlEndpointCreateParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // post /v1/accounts/url-endpoints + withRawResponse().create(params, requestOptions).thenApply { it.parse() } + + override fun update( + params: UrlEndpointUpdateParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // put /v1/accounts/url-endpoints/{id} + withRawResponse().update(params, requestOptions).thenApply { it.parse() } + + override fun list( + params: UrlEndpointListParams, + requestOptions: RequestOptions, + ): CompletableFuture> = + // get /v1/accounts/url-endpoints + withRawResponse().list(params, requestOptions).thenApply { it.parse() } + + override fun delete( + params: UrlEndpointDeleteParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // delete /v1/accounts/url-endpoints/{id} + withRawResponse().delete(params, requestOptions).thenAccept {} + + override fun get( + params: UrlEndpointGetParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // get /v1/accounts/url-endpoints/{id} + withRawResponse().get(params, requestOptions).thenApply { it.parse() } + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + UrlEndpointServiceAsync.WithRawResponse { + + private val errorHandler: Handler = + errorHandler(errorBodyHandler(clientOptions.jsonMapper)) + + override fun withOptions( + modifier: Consumer + ): UrlEndpointServiceAsync.WithRawResponse = + UrlEndpointServiceAsyncImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + private val createHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun create( + params: UrlEndpointCreateParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "accounts", "url-endpoints") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { createHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + + private val updateHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun update( + params: UrlEndpointUpdateParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("id", params.id().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.PUT) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "accounts", "url-endpoints", params._pathParam(0)) + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { updateHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + + private val listHandler: Handler> = + jsonHandler>(clientOptions.jsonMapper) + + override fun list( + params: UrlEndpointListParams, + requestOptions: RequestOptions, + ): CompletableFuture>> { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "accounts", "url-endpoints") + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { listHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.forEach { it.validate() } + } + } + } + } + } + + private val deleteHandler: Handler = emptyHandler() + + override fun delete( + params: UrlEndpointDeleteParams, + requestOptions: RequestOptions, + ): CompletableFuture { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("id", params.id().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.DELETE) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "accounts", "url-endpoints", params._pathParam(0)) + .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response.use { deleteHandler.handle(it) } + } + } + } + + private val getHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun get( + params: UrlEndpointGetParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("id", params.id().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "accounts", "url-endpoints", params._pathParam(0)) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { getHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + } +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/accounts/UsageServiceAsync.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/accounts/UsageServiceAsync.kt new file mode 100644 index 0000000..86d7d14 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/accounts/UsageServiceAsync.kt @@ -0,0 +1,66 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.async.accounts + +import com.imagekit.api.core.ClientOptions +import com.imagekit.api.core.RequestOptions +import com.imagekit.api.core.http.HttpResponseFor +import com.imagekit.api.models.accounts.usage.UsageGetParams +import com.imagekit.api.models.accounts.usage.UsageGetResponse +import java.util.concurrent.CompletableFuture +import java.util.function.Consumer + +interface UsageServiceAsync { + + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): UsageServiceAsync + + /** + * Get the account usage information between two dates. Note that the API response includes data + * from the start date while excluding data from the end date. In other words, the data covers + * the period starting from the specified start date up to, but not including, the end date. + */ + fun get(params: UsageGetParams): CompletableFuture = + get(params, RequestOptions.none()) + + /** @see get */ + fun get( + params: UsageGetParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** A view of [UsageServiceAsync] that provides access to raw HTTP responses for each method. */ + interface WithRawResponse { + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions( + modifier: Consumer + ): UsageServiceAsync.WithRawResponse + + /** + * Returns a raw HTTP response for `get /v1/accounts/usage`, but is otherwise the same as + * [UsageServiceAsync.get]. + */ + fun get(params: UsageGetParams): CompletableFuture> = + get(params, RequestOptions.none()) + + /** @see get */ + fun get( + params: UsageGetParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + } +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/accounts/UsageServiceAsyncImpl.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/accounts/UsageServiceAsyncImpl.kt new file mode 100644 index 0000000..60ebedd --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/accounts/UsageServiceAsyncImpl.kt @@ -0,0 +1,84 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.async.accounts + +import com.imagekit.api.core.ClientOptions +import com.imagekit.api.core.RequestOptions +import com.imagekit.api.core.handlers.errorBodyHandler +import com.imagekit.api.core.handlers.errorHandler +import com.imagekit.api.core.handlers.jsonHandler +import com.imagekit.api.core.http.HttpMethod +import com.imagekit.api.core.http.HttpRequest +import com.imagekit.api.core.http.HttpResponse +import com.imagekit.api.core.http.HttpResponse.Handler +import com.imagekit.api.core.http.HttpResponseFor +import com.imagekit.api.core.http.parseable +import com.imagekit.api.core.prepareAsync +import com.imagekit.api.models.accounts.usage.UsageGetParams +import com.imagekit.api.models.accounts.usage.UsageGetResponse +import java.util.concurrent.CompletableFuture +import java.util.function.Consumer + +class UsageServiceAsyncImpl internal constructor(private val clientOptions: ClientOptions) : + UsageServiceAsync { + + private val withRawResponse: UsageServiceAsync.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + override fun withRawResponse(): UsageServiceAsync.WithRawResponse = withRawResponse + + override fun withOptions(modifier: Consumer): UsageServiceAsync = + UsageServiceAsyncImpl(clientOptions.toBuilder().apply(modifier::accept).build()) + + override fun get( + params: UsageGetParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // get /v1/accounts/usage + withRawResponse().get(params, requestOptions).thenApply { it.parse() } + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + UsageServiceAsync.WithRawResponse { + + private val errorHandler: Handler = + errorHandler(errorBodyHandler(clientOptions.jsonMapper)) + + override fun withOptions( + modifier: Consumer + ): UsageServiceAsync.WithRawResponse = + UsageServiceAsyncImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + private val getHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun get( + params: UsageGetParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "accounts", "usage") + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { getHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + } +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/beta/V2ServiceAsync.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/beta/V2ServiceAsync.kt new file mode 100644 index 0000000..1048ace --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/beta/V2ServiceAsync.kt @@ -0,0 +1,37 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.async.beta + +import com.imagekit.api.core.ClientOptions +import com.imagekit.api.services.async.beta.v2.FileServiceAsync +import java.util.function.Consumer + +interface V2ServiceAsync { + + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): V2ServiceAsync + + fun files(): FileServiceAsync + + /** A view of [V2ServiceAsync] that provides access to raw HTTP responses for each method. */ + interface WithRawResponse { + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): V2ServiceAsync.WithRawResponse + + fun files(): FileServiceAsync.WithRawResponse + } +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/beta/V2ServiceAsyncImpl.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/beta/V2ServiceAsyncImpl.kt new file mode 100644 index 0000000..f07a7a2 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/beta/V2ServiceAsyncImpl.kt @@ -0,0 +1,42 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.async.beta + +import com.imagekit.api.core.ClientOptions +import com.imagekit.api.services.async.beta.v2.FileServiceAsync +import com.imagekit.api.services.async.beta.v2.FileServiceAsyncImpl +import java.util.function.Consumer + +class V2ServiceAsyncImpl internal constructor(private val clientOptions: ClientOptions) : + V2ServiceAsync { + + private val withRawResponse: V2ServiceAsync.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + private val files: FileServiceAsync by lazy { FileServiceAsyncImpl(clientOptions) } + + override fun withRawResponse(): V2ServiceAsync.WithRawResponse = withRawResponse + + override fun withOptions(modifier: Consumer): V2ServiceAsync = + V2ServiceAsyncImpl(clientOptions.toBuilder().apply(modifier::accept).build()) + + override fun files(): FileServiceAsync = files + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + V2ServiceAsync.WithRawResponse { + + private val files: FileServiceAsync.WithRawResponse by lazy { + FileServiceAsyncImpl.WithRawResponseImpl(clientOptions) + } + + override fun withOptions( + modifier: Consumer + ): V2ServiceAsync.WithRawResponse = + V2ServiceAsyncImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + override fun files(): FileServiceAsync.WithRawResponse = files + } +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/beta/v2/FileServiceAsync.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/beta/v2/FileServiceAsync.kt new file mode 100644 index 0000000..d8db93f --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/beta/v2/FileServiceAsync.kt @@ -0,0 +1,83 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.async.beta.v2 + +import com.imagekit.api.core.ClientOptions +import com.imagekit.api.core.RequestOptions +import com.imagekit.api.core.http.HttpResponseFor +import com.imagekit.api.models.beta.v2.files.FileUploadParams +import com.imagekit.api.models.beta.v2.files.FileUploadResponse +import java.util.concurrent.CompletableFuture +import java.util.function.Consumer + +interface FileServiceAsync { + + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): FileServiceAsync + + /** + * The V2 API enhances security by verifying the entire payload using JWT. This API is in beta. + * + * ImageKit.io allows you to upload files directly from both the server and client sides. For + * server-side uploads, private API key authentication is used. For client-side uploads, + * generate a one-time `token` from your secure backend using private API. + * [Learn more](/docs/api-reference/upload-file/upload-file-v2#how-to-implement-secure-client-side-file-upload) + * about how to implement secure client-side file upload. + * + * **File size limit** \ On the free plan, the maximum upload file sizes are 20MB for images, + * audio, and raw files, and 100MB for videos. On the paid plan, these limits increase to 40MB + * for images, audio, and raw files, and 2GB for videos. These limits can be further increased + * with higher-tier plans. + * + * **Version limit** \ A file can have a maximum of 100 versions. + * + * **Demo applications** + * - A full-fledged + * [upload widget using Uppy](https://github.com/imagekit-samples/uppy-uploader), supporting + * file selections from local storage, URL, Dropbox, Google Drive, Instagram, and more. + * - [Quick start guides](/docs/quick-start-guides) for various frameworks and technologies. + */ + fun upload(params: FileUploadParams): CompletableFuture = + upload(params, RequestOptions.none()) + + /** @see upload */ + fun upload( + params: FileUploadParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** A view of [FileServiceAsync] that provides access to raw HTTP responses for each method. */ + interface WithRawResponse { + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): FileServiceAsync.WithRawResponse + + /** + * Returns a raw HTTP response for `post /api/v2/files/upload`, but is otherwise the same as + * [FileServiceAsync.upload]. + */ + fun upload( + params: FileUploadParams + ): CompletableFuture> = + upload(params, RequestOptions.none()) + + /** @see upload */ + fun upload( + params: FileUploadParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + } +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/beta/v2/FileServiceAsyncImpl.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/beta/v2/FileServiceAsyncImpl.kt new file mode 100644 index 0000000..1649f9b --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/beta/v2/FileServiceAsyncImpl.kt @@ -0,0 +1,89 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.async.beta.v2 + +import com.imagekit.api.core.ClientOptions +import com.imagekit.api.core.RequestOptions +import com.imagekit.api.core.handlers.errorBodyHandler +import com.imagekit.api.core.handlers.errorHandler +import com.imagekit.api.core.handlers.jsonHandler +import com.imagekit.api.core.http.HttpMethod +import com.imagekit.api.core.http.HttpRequest +import com.imagekit.api.core.http.HttpResponse +import com.imagekit.api.core.http.HttpResponse.Handler +import com.imagekit.api.core.http.HttpResponseFor +import com.imagekit.api.core.http.multipartFormData +import com.imagekit.api.core.http.parseable +import com.imagekit.api.core.prepareAsync +import com.imagekit.api.models.beta.v2.files.FileUploadParams +import com.imagekit.api.models.beta.v2.files.FileUploadResponse +import java.util.concurrent.CompletableFuture +import java.util.function.Consumer + +class FileServiceAsyncImpl internal constructor(private val clientOptions: ClientOptions) : + FileServiceAsync { + + private val withRawResponse: FileServiceAsync.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + override fun withRawResponse(): FileServiceAsync.WithRawResponse = withRawResponse + + override fun withOptions(modifier: Consumer): FileServiceAsync = + FileServiceAsyncImpl(clientOptions.toBuilder().apply(modifier::accept).build()) + + override fun upload( + params: FileUploadParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // post /api/v2/files/upload + withRawResponse().upload(params, requestOptions).thenApply { it.parse() } + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + FileServiceAsync.WithRawResponse { + + private val errorHandler: Handler = + errorHandler(errorBodyHandler(clientOptions.jsonMapper)) + + override fun withOptions( + modifier: Consumer + ): FileServiceAsync.WithRawResponse = + FileServiceAsyncImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + private val uploadHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun upload( + params: FileUploadParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl( + if (clientOptions.baseUrlOverridden()) clientOptions.baseUrl() + else "https://upload.imagekit.io" + ) + .addPathSegments("api", "v2", "files", "upload") + .body(multipartFormData(clientOptions.jsonMapper, params._body())) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { uploadHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + } +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/cache/InvalidationServiceAsync.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/cache/InvalidationServiceAsync.kt new file mode 100644 index 0000000..49c8861 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/cache/InvalidationServiceAsync.kt @@ -0,0 +1,148 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.async.cache + +import com.imagekit.api.core.ClientOptions +import com.imagekit.api.core.RequestOptions +import com.imagekit.api.core.http.HttpResponseFor +import com.imagekit.api.models.cache.invalidation.InvalidationCreateParams +import com.imagekit.api.models.cache.invalidation.InvalidationCreateResponse +import com.imagekit.api.models.cache.invalidation.InvalidationGetParams +import com.imagekit.api.models.cache.invalidation.InvalidationGetResponse +import java.util.concurrent.CompletableFuture +import java.util.function.Consumer + +interface InvalidationServiceAsync { + + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): InvalidationServiceAsync + + /** + * This API will purge CDN cache and ImageKit.io's internal cache for a file. Note: Purge cache + * is an asynchronous process and it may take some time to reflect the changes. + */ + fun create(params: InvalidationCreateParams): CompletableFuture = + create(params, RequestOptions.none()) + + /** @see create */ + fun create( + params: InvalidationCreateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** This API returns the status of a purge cache request. */ + fun get(requestId: String): CompletableFuture = + get(requestId, InvalidationGetParams.none()) + + /** @see get */ + fun get( + requestId: String, + params: InvalidationGetParams = InvalidationGetParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = + get(params.toBuilder().requestId(requestId).build(), requestOptions) + + /** @see get */ + fun get( + requestId: String, + params: InvalidationGetParams = InvalidationGetParams.none(), + ): CompletableFuture = get(requestId, params, RequestOptions.none()) + + /** @see get */ + fun get( + params: InvalidationGetParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** @see get */ + fun get(params: InvalidationGetParams): CompletableFuture = + get(params, RequestOptions.none()) + + /** @see get */ + fun get( + requestId: String, + requestOptions: RequestOptions, + ): CompletableFuture = + get(requestId, InvalidationGetParams.none(), requestOptions) + + /** + * A view of [InvalidationServiceAsync] that provides access to raw HTTP responses for each + * method. + */ + interface WithRawResponse { + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions( + modifier: Consumer + ): InvalidationServiceAsync.WithRawResponse + + /** + * Returns a raw HTTP response for `post /v1/files/purge`, but is otherwise the same as + * [InvalidationServiceAsync.create]. + */ + fun create( + params: InvalidationCreateParams + ): CompletableFuture> = + create(params, RequestOptions.none()) + + /** @see create */ + fun create( + params: InvalidationCreateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** + * Returns a raw HTTP response for `get /v1/files/purge/{requestId}`, but is otherwise the + * same as [InvalidationServiceAsync.get]. + */ + fun get(requestId: String): CompletableFuture> = + get(requestId, InvalidationGetParams.none()) + + /** @see get */ + fun get( + requestId: String, + params: InvalidationGetParams = InvalidationGetParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> = + get(params.toBuilder().requestId(requestId).build(), requestOptions) + + /** @see get */ + fun get( + requestId: String, + params: InvalidationGetParams = InvalidationGetParams.none(), + ): CompletableFuture> = + get(requestId, params, RequestOptions.none()) + + /** @see get */ + fun get( + params: InvalidationGetParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see get */ + fun get( + params: InvalidationGetParams + ): CompletableFuture> = + get(params, RequestOptions.none()) + + /** @see get */ + fun get( + requestId: String, + requestOptions: RequestOptions, + ): CompletableFuture> = + get(requestId, InvalidationGetParams.none(), requestOptions) + } +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/cache/InvalidationServiceAsyncImpl.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/cache/InvalidationServiceAsyncImpl.kt new file mode 100644 index 0000000..d7e4177 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/cache/InvalidationServiceAsyncImpl.kt @@ -0,0 +1,130 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.async.cache + +import com.imagekit.api.core.ClientOptions +import com.imagekit.api.core.RequestOptions +import com.imagekit.api.core.checkRequired +import com.imagekit.api.core.handlers.errorBodyHandler +import com.imagekit.api.core.handlers.errorHandler +import com.imagekit.api.core.handlers.jsonHandler +import com.imagekit.api.core.http.HttpMethod +import com.imagekit.api.core.http.HttpRequest +import com.imagekit.api.core.http.HttpResponse +import com.imagekit.api.core.http.HttpResponse.Handler +import com.imagekit.api.core.http.HttpResponseFor +import com.imagekit.api.core.http.json +import com.imagekit.api.core.http.parseable +import com.imagekit.api.core.prepareAsync +import com.imagekit.api.models.cache.invalidation.InvalidationCreateParams +import com.imagekit.api.models.cache.invalidation.InvalidationCreateResponse +import com.imagekit.api.models.cache.invalidation.InvalidationGetParams +import com.imagekit.api.models.cache.invalidation.InvalidationGetResponse +import java.util.concurrent.CompletableFuture +import java.util.function.Consumer +import kotlin.jvm.optionals.getOrNull + +class InvalidationServiceAsyncImpl internal constructor(private val clientOptions: ClientOptions) : + InvalidationServiceAsync { + + private val withRawResponse: InvalidationServiceAsync.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + override fun withRawResponse(): InvalidationServiceAsync.WithRawResponse = withRawResponse + + override fun withOptions(modifier: Consumer): InvalidationServiceAsync = + InvalidationServiceAsyncImpl(clientOptions.toBuilder().apply(modifier::accept).build()) + + override fun create( + params: InvalidationCreateParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // post /v1/files/purge + withRawResponse().create(params, requestOptions).thenApply { it.parse() } + + override fun get( + params: InvalidationGetParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // get /v1/files/purge/{requestId} + withRawResponse().get(params, requestOptions).thenApply { it.parse() } + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + InvalidationServiceAsync.WithRawResponse { + + private val errorHandler: Handler = + errorHandler(errorBodyHandler(clientOptions.jsonMapper)) + + override fun withOptions( + modifier: Consumer + ): InvalidationServiceAsync.WithRawResponse = + InvalidationServiceAsyncImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + private val createHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun create( + params: InvalidationCreateParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "files", "purge") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { createHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + + private val getHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun get( + params: InvalidationGetParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("requestId", params.requestId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "files", "purge", params._pathParam(0)) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { getHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + } +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/files/BulkServiceAsync.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/files/BulkServiceAsync.kt new file mode 100644 index 0000000..bab5c67 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/files/BulkServiceAsync.kt @@ -0,0 +1,160 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.async.files + +import com.imagekit.api.core.ClientOptions +import com.imagekit.api.core.RequestOptions +import com.imagekit.api.core.http.HttpResponseFor +import com.imagekit.api.models.files.bulk.BulkAddTagsParams +import com.imagekit.api.models.files.bulk.BulkAddTagsResponse +import com.imagekit.api.models.files.bulk.BulkDeleteParams +import com.imagekit.api.models.files.bulk.BulkDeleteResponse +import com.imagekit.api.models.files.bulk.BulkRemoveAiTagsParams +import com.imagekit.api.models.files.bulk.BulkRemoveAiTagsResponse +import com.imagekit.api.models.files.bulk.BulkRemoveTagsParams +import com.imagekit.api.models.files.bulk.BulkRemoveTagsResponse +import java.util.concurrent.CompletableFuture +import java.util.function.Consumer + +interface BulkServiceAsync { + + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): BulkServiceAsync + + /** + * This API deletes multiple files and all their file versions permanently. + * + * Note: If a file or specific transformation has been requested in the past, then the response + * is cached. Deleting a file does not purge the cache. You can purge the cache using purge + * cache API. + * + * A maximum of 100 files can be deleted at a time. + */ + fun delete(params: BulkDeleteParams): CompletableFuture = + delete(params, RequestOptions.none()) + + /** @see delete */ + fun delete( + params: BulkDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** + * This API adds tags to multiple files in bulk. A maximum of 50 files can be specified at a + * time. + */ + fun addTags(params: BulkAddTagsParams): CompletableFuture = + addTags(params, RequestOptions.none()) + + /** @see addTags */ + fun addTags( + params: BulkAddTagsParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** + * This API removes AITags from multiple files in bulk. A maximum of 50 files can be specified + * at a time. + */ + fun removeAiTags(params: BulkRemoveAiTagsParams): CompletableFuture = + removeAiTags(params, RequestOptions.none()) + + /** @see removeAiTags */ + fun removeAiTags( + params: BulkRemoveAiTagsParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** + * This API removes tags from multiple files in bulk. A maximum of 50 files can be specified at + * a time. + */ + fun removeTags(params: BulkRemoveTagsParams): CompletableFuture = + removeTags(params, RequestOptions.none()) + + /** @see removeTags */ + fun removeTags( + params: BulkRemoveTagsParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** A view of [BulkServiceAsync] that provides access to raw HTTP responses for each method. */ + interface WithRawResponse { + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): BulkServiceAsync.WithRawResponse + + /** + * Returns a raw HTTP response for `post /v1/files/batch/deleteByFileIds`, but is otherwise + * the same as [BulkServiceAsync.delete]. + */ + fun delete( + params: BulkDeleteParams + ): CompletableFuture> = + delete(params, RequestOptions.none()) + + /** @see delete */ + fun delete( + params: BulkDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** + * Returns a raw HTTP response for `post /v1/files/addTags`, but is otherwise the same as + * [BulkServiceAsync.addTags]. + */ + fun addTags( + params: BulkAddTagsParams + ): CompletableFuture> = + addTags(params, RequestOptions.none()) + + /** @see addTags */ + fun addTags( + params: BulkAddTagsParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** + * Returns a raw HTTP response for `post /v1/files/removeAITags`, but is otherwise the same + * as [BulkServiceAsync.removeAiTags]. + */ + fun removeAiTags( + params: BulkRemoveAiTagsParams + ): CompletableFuture> = + removeAiTags(params, RequestOptions.none()) + + /** @see removeAiTags */ + fun removeAiTags( + params: BulkRemoveAiTagsParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** + * Returns a raw HTTP response for `post /v1/files/removeTags`, but is otherwise the same as + * [BulkServiceAsync.removeTags]. + */ + fun removeTags( + params: BulkRemoveTagsParams + ): CompletableFuture> = + removeTags(params, RequestOptions.none()) + + /** @see removeTags */ + fun removeTags( + params: BulkRemoveTagsParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + } +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/files/BulkServiceAsyncImpl.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/files/BulkServiceAsyncImpl.kt new file mode 100644 index 0000000..b4f268d --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/files/BulkServiceAsyncImpl.kt @@ -0,0 +1,206 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.async.files + +import com.imagekit.api.core.ClientOptions +import com.imagekit.api.core.RequestOptions +import com.imagekit.api.core.handlers.errorBodyHandler +import com.imagekit.api.core.handlers.errorHandler +import com.imagekit.api.core.handlers.jsonHandler +import com.imagekit.api.core.http.HttpMethod +import com.imagekit.api.core.http.HttpRequest +import com.imagekit.api.core.http.HttpResponse +import com.imagekit.api.core.http.HttpResponse.Handler +import com.imagekit.api.core.http.HttpResponseFor +import com.imagekit.api.core.http.json +import com.imagekit.api.core.http.parseable +import com.imagekit.api.core.prepareAsync +import com.imagekit.api.models.files.bulk.BulkAddTagsParams +import com.imagekit.api.models.files.bulk.BulkAddTagsResponse +import com.imagekit.api.models.files.bulk.BulkDeleteParams +import com.imagekit.api.models.files.bulk.BulkDeleteResponse +import com.imagekit.api.models.files.bulk.BulkRemoveAiTagsParams +import com.imagekit.api.models.files.bulk.BulkRemoveAiTagsResponse +import com.imagekit.api.models.files.bulk.BulkRemoveTagsParams +import com.imagekit.api.models.files.bulk.BulkRemoveTagsResponse +import java.util.concurrent.CompletableFuture +import java.util.function.Consumer + +class BulkServiceAsyncImpl internal constructor(private val clientOptions: ClientOptions) : + BulkServiceAsync { + + private val withRawResponse: BulkServiceAsync.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + override fun withRawResponse(): BulkServiceAsync.WithRawResponse = withRawResponse + + override fun withOptions(modifier: Consumer): BulkServiceAsync = + BulkServiceAsyncImpl(clientOptions.toBuilder().apply(modifier::accept).build()) + + override fun delete( + params: BulkDeleteParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // post /v1/files/batch/deleteByFileIds + withRawResponse().delete(params, requestOptions).thenApply { it.parse() } + + override fun addTags( + params: BulkAddTagsParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // post /v1/files/addTags + withRawResponse().addTags(params, requestOptions).thenApply { it.parse() } + + override fun removeAiTags( + params: BulkRemoveAiTagsParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // post /v1/files/removeAITags + withRawResponse().removeAiTags(params, requestOptions).thenApply { it.parse() } + + override fun removeTags( + params: BulkRemoveTagsParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // post /v1/files/removeTags + withRawResponse().removeTags(params, requestOptions).thenApply { it.parse() } + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + BulkServiceAsync.WithRawResponse { + + private val errorHandler: Handler = + errorHandler(errorBodyHandler(clientOptions.jsonMapper)) + + override fun withOptions( + modifier: Consumer + ): BulkServiceAsync.WithRawResponse = + BulkServiceAsyncImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + private val deleteHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun delete( + params: BulkDeleteParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "files", "batch", "deleteByFileIds") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { deleteHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + + private val addTagsHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun addTags( + params: BulkAddTagsParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "files", "addTags") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { addTagsHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + + private val removeAiTagsHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun removeAiTags( + params: BulkRemoveAiTagsParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "files", "removeAITags") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { removeAiTagsHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + + private val removeTagsHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun removeTags( + params: BulkRemoveTagsParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "files", "removeTags") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { removeTagsHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + } +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/files/MetadataServiceAsync.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/files/MetadataServiceAsync.kt new file mode 100644 index 0000000..1d7f385 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/files/MetadataServiceAsync.kt @@ -0,0 +1,142 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.async.files + +import com.imagekit.api.core.ClientOptions +import com.imagekit.api.core.RequestOptions +import com.imagekit.api.core.http.HttpResponseFor +import com.imagekit.api.models.files.Metadata +import com.imagekit.api.models.files.metadata.MetadataGetFromUrlParams +import com.imagekit.api.models.files.metadata.MetadataGetParams +import java.util.concurrent.CompletableFuture +import java.util.function.Consumer + +interface MetadataServiceAsync { + + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): MetadataServiceAsync + + /** + * You can programmatically get image EXIF, pHash, and other metadata for uploaded files in the + * ImageKit.io media library using this API. + * + * You can also get the metadata in upload API response by passing `metadata` in + * `responseFields` parameter. + */ + fun get(fileId: String): CompletableFuture = get(fileId, MetadataGetParams.none()) + + /** @see get */ + fun get( + fileId: String, + params: MetadataGetParams = MetadataGetParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = get(params.toBuilder().fileId(fileId).build(), requestOptions) + + /** @see get */ + fun get( + fileId: String, + params: MetadataGetParams = MetadataGetParams.none(), + ): CompletableFuture = get(fileId, params, RequestOptions.none()) + + /** @see get */ + fun get( + params: MetadataGetParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** @see get */ + fun get(params: MetadataGetParams): CompletableFuture = + get(params, RequestOptions.none()) + + /** @see get */ + fun get(fileId: String, requestOptions: RequestOptions): CompletableFuture = + get(fileId, MetadataGetParams.none(), requestOptions) + + /** + * Get image EXIF, pHash, and other metadata from ImageKit.io powered remote URL using this API. + */ + fun getFromUrl(params: MetadataGetFromUrlParams): CompletableFuture = + getFromUrl(params, RequestOptions.none()) + + /** @see getFromUrl */ + fun getFromUrl( + params: MetadataGetFromUrlParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** + * A view of [MetadataServiceAsync] that provides access to raw HTTP responses for each method. + */ + interface WithRawResponse { + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions( + modifier: Consumer + ): MetadataServiceAsync.WithRawResponse + + /** + * Returns a raw HTTP response for `get /v1/files/{fileId}/metadata`, but is otherwise the + * same as [MetadataServiceAsync.get]. + */ + fun get(fileId: String): CompletableFuture> = + get(fileId, MetadataGetParams.none()) + + /** @see get */ + fun get( + fileId: String, + params: MetadataGetParams = MetadataGetParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> = + get(params.toBuilder().fileId(fileId).build(), requestOptions) + + /** @see get */ + fun get( + fileId: String, + params: MetadataGetParams = MetadataGetParams.none(), + ): CompletableFuture> = get(fileId, params, RequestOptions.none()) + + /** @see get */ + fun get( + params: MetadataGetParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see get */ + fun get(params: MetadataGetParams): CompletableFuture> = + get(params, RequestOptions.none()) + + /** @see get */ + fun get( + fileId: String, + requestOptions: RequestOptions, + ): CompletableFuture> = + get(fileId, MetadataGetParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `get /v1/files/metadata`, but is otherwise the same as + * [MetadataServiceAsync.getFromUrl]. + */ + fun getFromUrl( + params: MetadataGetFromUrlParams + ): CompletableFuture> = getFromUrl(params, RequestOptions.none()) + + /** @see getFromUrl */ + fun getFromUrl( + params: MetadataGetFromUrlParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + } +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/files/MetadataServiceAsyncImpl.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/files/MetadataServiceAsyncImpl.kt new file mode 100644 index 0000000..b9a0336 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/files/MetadataServiceAsyncImpl.kt @@ -0,0 +1,126 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.async.files + +import com.imagekit.api.core.ClientOptions +import com.imagekit.api.core.RequestOptions +import com.imagekit.api.core.checkRequired +import com.imagekit.api.core.handlers.errorBodyHandler +import com.imagekit.api.core.handlers.errorHandler +import com.imagekit.api.core.handlers.jsonHandler +import com.imagekit.api.core.http.HttpMethod +import com.imagekit.api.core.http.HttpRequest +import com.imagekit.api.core.http.HttpResponse +import com.imagekit.api.core.http.HttpResponse.Handler +import com.imagekit.api.core.http.HttpResponseFor +import com.imagekit.api.core.http.parseable +import com.imagekit.api.core.prepareAsync +import com.imagekit.api.models.files.Metadata +import com.imagekit.api.models.files.metadata.MetadataGetFromUrlParams +import com.imagekit.api.models.files.metadata.MetadataGetParams +import java.util.concurrent.CompletableFuture +import java.util.function.Consumer +import kotlin.jvm.optionals.getOrNull + +class MetadataServiceAsyncImpl internal constructor(private val clientOptions: ClientOptions) : + MetadataServiceAsync { + + private val withRawResponse: MetadataServiceAsync.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + override fun withRawResponse(): MetadataServiceAsync.WithRawResponse = withRawResponse + + override fun withOptions(modifier: Consumer): MetadataServiceAsync = + MetadataServiceAsyncImpl(clientOptions.toBuilder().apply(modifier::accept).build()) + + override fun get( + params: MetadataGetParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // get /v1/files/{fileId}/metadata + withRawResponse().get(params, requestOptions).thenApply { it.parse() } + + override fun getFromUrl( + params: MetadataGetFromUrlParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // get /v1/files/metadata + withRawResponse().getFromUrl(params, requestOptions).thenApply { it.parse() } + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + MetadataServiceAsync.WithRawResponse { + + private val errorHandler: Handler = + errorHandler(errorBodyHandler(clientOptions.jsonMapper)) + + override fun withOptions( + modifier: Consumer + ): MetadataServiceAsync.WithRawResponse = + MetadataServiceAsyncImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + private val getHandler: Handler = jsonHandler(clientOptions.jsonMapper) + + override fun get( + params: MetadataGetParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("fileId", params.fileId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "files", params._pathParam(0), "metadata") + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { getHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + + private val getFromUrlHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun getFromUrl( + params: MetadataGetFromUrlParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "files", "metadata") + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { getFromUrlHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + } +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/files/VersionServiceAsync.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/files/VersionServiceAsync.kt new file mode 100644 index 0000000..62bdd11 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/files/VersionServiceAsync.kt @@ -0,0 +1,271 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.async.files + +import com.imagekit.api.core.ClientOptions +import com.imagekit.api.core.RequestOptions +import com.imagekit.api.core.http.HttpResponseFor +import com.imagekit.api.models.files.File +import com.imagekit.api.models.files.versions.VersionDeleteParams +import com.imagekit.api.models.files.versions.VersionDeleteResponse +import com.imagekit.api.models.files.versions.VersionGetParams +import com.imagekit.api.models.files.versions.VersionListParams +import com.imagekit.api.models.files.versions.VersionRestoreParams +import java.util.concurrent.CompletableFuture +import java.util.function.Consumer + +interface VersionServiceAsync { + + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): VersionServiceAsync + + /** This API returns details of all versions of a file. */ + fun list(fileId: String): CompletableFuture> = list(fileId, VersionListParams.none()) + + /** @see list */ + fun list( + fileId: String, + params: VersionListParams = VersionListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> = + list(params.toBuilder().fileId(fileId).build(), requestOptions) + + /** @see list */ + fun list( + fileId: String, + params: VersionListParams = VersionListParams.none(), + ): CompletableFuture> = list(fileId, params, RequestOptions.none()) + + /** @see list */ + fun list( + params: VersionListParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see list */ + fun list(params: VersionListParams): CompletableFuture> = + list(params, RequestOptions.none()) + + /** @see list */ + fun list(fileId: String, requestOptions: RequestOptions): CompletableFuture> = + list(fileId, VersionListParams.none(), requestOptions) + + /** + * This API deletes a non-current file version permanently. The API returns an empty response. + * + * Note: If you want to delete all versions of a file, use the delete file API. + */ + fun delete( + versionId: String, + params: VersionDeleteParams, + ): CompletableFuture = delete(versionId, params, RequestOptions.none()) + + /** @see delete */ + fun delete( + versionId: String, + params: VersionDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = + delete(params.toBuilder().versionId(versionId).build(), requestOptions) + + /** @see delete */ + fun delete(params: VersionDeleteParams): CompletableFuture = + delete(params, RequestOptions.none()) + + /** @see delete */ + fun delete( + params: VersionDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** This API returns an object with details or attributes of a file version. */ + fun get(versionId: String, params: VersionGetParams): CompletableFuture = + get(versionId, params, RequestOptions.none()) + + /** @see get */ + fun get( + versionId: String, + params: VersionGetParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = + get(params.toBuilder().versionId(versionId).build(), requestOptions) + + /** @see get */ + fun get(params: VersionGetParams): CompletableFuture = get(params, RequestOptions.none()) + + /** @see get */ + fun get( + params: VersionGetParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** This API restores a file version as the current file version. */ + fun restore(versionId: String, params: VersionRestoreParams): CompletableFuture = + restore(versionId, params, RequestOptions.none()) + + /** @see restore */ + fun restore( + versionId: String, + params: VersionRestoreParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = + restore(params.toBuilder().versionId(versionId).build(), requestOptions) + + /** @see restore */ + fun restore(params: VersionRestoreParams): CompletableFuture = + restore(params, RequestOptions.none()) + + /** @see restore */ + fun restore( + params: VersionRestoreParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** + * A view of [VersionServiceAsync] that provides access to raw HTTP responses for each method. + */ + interface WithRawResponse { + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions( + modifier: Consumer + ): VersionServiceAsync.WithRawResponse + + /** + * Returns a raw HTTP response for `get /v1/files/{fileId}/versions`, but is otherwise the + * same as [VersionServiceAsync.list]. + */ + fun list(fileId: String): CompletableFuture>> = + list(fileId, VersionListParams.none()) + + /** @see list */ + fun list( + fileId: String, + params: VersionListParams = VersionListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture>> = + list(params.toBuilder().fileId(fileId).build(), requestOptions) + + /** @see list */ + fun list( + fileId: String, + params: VersionListParams = VersionListParams.none(), + ): CompletableFuture>> = + list(fileId, params, RequestOptions.none()) + + /** @see list */ + fun list( + params: VersionListParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture>> + + /** @see list */ + fun list(params: VersionListParams): CompletableFuture>> = + list(params, RequestOptions.none()) + + /** @see list */ + fun list( + fileId: String, + requestOptions: RequestOptions, + ): CompletableFuture>> = + list(fileId, VersionListParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `delete /v1/files/{fileId}/versions/{versionId}`, but is + * otherwise the same as [VersionServiceAsync.delete]. + */ + fun delete( + versionId: String, + params: VersionDeleteParams, + ): CompletableFuture> = + delete(versionId, params, RequestOptions.none()) + + /** @see delete */ + fun delete( + versionId: String, + params: VersionDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> = + delete(params.toBuilder().versionId(versionId).build(), requestOptions) + + /** @see delete */ + fun delete( + params: VersionDeleteParams + ): CompletableFuture> = + delete(params, RequestOptions.none()) + + /** @see delete */ + fun delete( + params: VersionDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** + * Returns a raw HTTP response for `get /v1/files/{fileId}/versions/{versionId}`, but is + * otherwise the same as [VersionServiceAsync.get]. + */ + fun get( + versionId: String, + params: VersionGetParams, + ): CompletableFuture> = get(versionId, params, RequestOptions.none()) + + /** @see get */ + fun get( + versionId: String, + params: VersionGetParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> = + get(params.toBuilder().versionId(versionId).build(), requestOptions) + + /** @see get */ + fun get(params: VersionGetParams): CompletableFuture> = + get(params, RequestOptions.none()) + + /** @see get */ + fun get( + params: VersionGetParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** + * Returns a raw HTTP response for `put /v1/files/{fileId}/versions/{versionId}/restore`, + * but is otherwise the same as [VersionServiceAsync.restore]. + */ + fun restore( + versionId: String, + params: VersionRestoreParams, + ): CompletableFuture> = + restore(versionId, params, RequestOptions.none()) + + /** @see restore */ + fun restore( + versionId: String, + params: VersionRestoreParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> = + restore(params.toBuilder().versionId(versionId).build(), requestOptions) + + /** @see restore */ + fun restore(params: VersionRestoreParams): CompletableFuture> = + restore(params, RequestOptions.none()) + + /** @see restore */ + fun restore( + params: VersionRestoreParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + } +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/files/VersionServiceAsyncImpl.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/files/VersionServiceAsyncImpl.kt new file mode 100644 index 0000000..c601ebe --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/files/VersionServiceAsyncImpl.kt @@ -0,0 +1,233 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.async.files + +import com.imagekit.api.core.ClientOptions +import com.imagekit.api.core.RequestOptions +import com.imagekit.api.core.checkRequired +import com.imagekit.api.core.handlers.errorBodyHandler +import com.imagekit.api.core.handlers.errorHandler +import com.imagekit.api.core.handlers.jsonHandler +import com.imagekit.api.core.http.HttpMethod +import com.imagekit.api.core.http.HttpRequest +import com.imagekit.api.core.http.HttpResponse +import com.imagekit.api.core.http.HttpResponse.Handler +import com.imagekit.api.core.http.HttpResponseFor +import com.imagekit.api.core.http.json +import com.imagekit.api.core.http.parseable +import com.imagekit.api.core.prepareAsync +import com.imagekit.api.models.files.File +import com.imagekit.api.models.files.versions.VersionDeleteParams +import com.imagekit.api.models.files.versions.VersionDeleteResponse +import com.imagekit.api.models.files.versions.VersionGetParams +import com.imagekit.api.models.files.versions.VersionListParams +import com.imagekit.api.models.files.versions.VersionRestoreParams +import java.util.concurrent.CompletableFuture +import java.util.function.Consumer +import kotlin.jvm.optionals.getOrNull + +class VersionServiceAsyncImpl internal constructor(private val clientOptions: ClientOptions) : + VersionServiceAsync { + + private val withRawResponse: VersionServiceAsync.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + override fun withRawResponse(): VersionServiceAsync.WithRawResponse = withRawResponse + + override fun withOptions(modifier: Consumer): VersionServiceAsync = + VersionServiceAsyncImpl(clientOptions.toBuilder().apply(modifier::accept).build()) + + override fun list( + params: VersionListParams, + requestOptions: RequestOptions, + ): CompletableFuture> = + // get /v1/files/{fileId}/versions + withRawResponse().list(params, requestOptions).thenApply { it.parse() } + + override fun delete( + params: VersionDeleteParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // delete /v1/files/{fileId}/versions/{versionId} + withRawResponse().delete(params, requestOptions).thenApply { it.parse() } + + override fun get( + params: VersionGetParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // get /v1/files/{fileId}/versions/{versionId} + withRawResponse().get(params, requestOptions).thenApply { it.parse() } + + override fun restore( + params: VersionRestoreParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // put /v1/files/{fileId}/versions/{versionId}/restore + withRawResponse().restore(params, requestOptions).thenApply { it.parse() } + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + VersionServiceAsync.WithRawResponse { + + private val errorHandler: Handler = + errorHandler(errorBodyHandler(clientOptions.jsonMapper)) + + override fun withOptions( + modifier: Consumer + ): VersionServiceAsync.WithRawResponse = + VersionServiceAsyncImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + private val listHandler: Handler> = + jsonHandler>(clientOptions.jsonMapper) + + override fun list( + params: VersionListParams, + requestOptions: RequestOptions, + ): CompletableFuture>> { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("fileId", params.fileId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "files", params._pathParam(0), "versions") + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { listHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.forEach { it.validate() } + } + } + } + } + } + + private val deleteHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun delete( + params: VersionDeleteParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("versionId", params.versionId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.DELETE) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments( + "v1", + "files", + params._pathParam(0), + "versions", + params._pathParam(1), + ) + .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { deleteHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + + private val getHandler: Handler = jsonHandler(clientOptions.jsonMapper) + + override fun get( + params: VersionGetParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("versionId", params.versionId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments( + "v1", + "files", + params._pathParam(0), + "versions", + params._pathParam(1), + ) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { getHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + + private val restoreHandler: Handler = jsonHandler(clientOptions.jsonMapper) + + override fun restore( + params: VersionRestoreParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("versionId", params.versionId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.PUT) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments( + "v1", + "files", + params._pathParam(0), + "versions", + params._pathParam(1), + "restore", + ) + .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { restoreHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + } +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/folders/JobServiceAsync.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/folders/JobServiceAsync.kt new file mode 100644 index 0000000..48bf837 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/folders/JobServiceAsync.kt @@ -0,0 +1,107 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.async.folders + +import com.imagekit.api.core.ClientOptions +import com.imagekit.api.core.RequestOptions +import com.imagekit.api.core.http.HttpResponseFor +import com.imagekit.api.models.folders.job.JobGetParams +import com.imagekit.api.models.folders.job.JobGetResponse +import java.util.concurrent.CompletableFuture +import java.util.function.Consumer + +interface JobServiceAsync { + + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): JobServiceAsync + + /** This API returns the status of a bulk job like copy and move folder operations. */ + fun get(jobId: String): CompletableFuture = get(jobId, JobGetParams.none()) + + /** @see get */ + fun get( + jobId: String, + params: JobGetParams = JobGetParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = + get(params.toBuilder().jobId(jobId).build(), requestOptions) + + /** @see get */ + fun get( + jobId: String, + params: JobGetParams = JobGetParams.none(), + ): CompletableFuture = get(jobId, params, RequestOptions.none()) + + /** @see get */ + fun get( + params: JobGetParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** @see get */ + fun get(params: JobGetParams): CompletableFuture = + get(params, RequestOptions.none()) + + /** @see get */ + fun get(jobId: String, requestOptions: RequestOptions): CompletableFuture = + get(jobId, JobGetParams.none(), requestOptions) + + /** A view of [JobServiceAsync] that provides access to raw HTTP responses for each method. */ + interface WithRawResponse { + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): JobServiceAsync.WithRawResponse + + /** + * Returns a raw HTTP response for `get /v1/bulkJobs/{jobId}`, but is otherwise the same as + * [JobServiceAsync.get]. + */ + fun get(jobId: String): CompletableFuture> = + get(jobId, JobGetParams.none()) + + /** @see get */ + fun get( + jobId: String, + params: JobGetParams = JobGetParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> = + get(params.toBuilder().jobId(jobId).build(), requestOptions) + + /** @see get */ + fun get( + jobId: String, + params: JobGetParams = JobGetParams.none(), + ): CompletableFuture> = + get(jobId, params, RequestOptions.none()) + + /** @see get */ + fun get( + params: JobGetParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see get */ + fun get(params: JobGetParams): CompletableFuture> = + get(params, RequestOptions.none()) + + /** @see get */ + fun get( + jobId: String, + requestOptions: RequestOptions, + ): CompletableFuture> = + get(jobId, JobGetParams.none(), requestOptions) + } +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/folders/JobServiceAsyncImpl.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/folders/JobServiceAsyncImpl.kt new file mode 100644 index 0000000..4f0f7a3 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/async/folders/JobServiceAsyncImpl.kt @@ -0,0 +1,89 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.async.folders + +import com.imagekit.api.core.ClientOptions +import com.imagekit.api.core.RequestOptions +import com.imagekit.api.core.checkRequired +import com.imagekit.api.core.handlers.errorBodyHandler +import com.imagekit.api.core.handlers.errorHandler +import com.imagekit.api.core.handlers.jsonHandler +import com.imagekit.api.core.http.HttpMethod +import com.imagekit.api.core.http.HttpRequest +import com.imagekit.api.core.http.HttpResponse +import com.imagekit.api.core.http.HttpResponse.Handler +import com.imagekit.api.core.http.HttpResponseFor +import com.imagekit.api.core.http.parseable +import com.imagekit.api.core.prepareAsync +import com.imagekit.api.models.folders.job.JobGetParams +import com.imagekit.api.models.folders.job.JobGetResponse +import java.util.concurrent.CompletableFuture +import java.util.function.Consumer +import kotlin.jvm.optionals.getOrNull + +class JobServiceAsyncImpl internal constructor(private val clientOptions: ClientOptions) : + JobServiceAsync { + + private val withRawResponse: JobServiceAsync.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + override fun withRawResponse(): JobServiceAsync.WithRawResponse = withRawResponse + + override fun withOptions(modifier: Consumer): JobServiceAsync = + JobServiceAsyncImpl(clientOptions.toBuilder().apply(modifier::accept).build()) + + override fun get( + params: JobGetParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // get /v1/bulkJobs/{jobId} + withRawResponse().get(params, requestOptions).thenApply { it.parse() } + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + JobServiceAsync.WithRawResponse { + + private val errorHandler: Handler = + errorHandler(errorBodyHandler(clientOptions.jsonMapper)) + + override fun withOptions( + modifier: Consumer + ): JobServiceAsync.WithRawResponse = + JobServiceAsyncImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + private val getHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun get( + params: JobGetParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("jobId", params.jobId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "bulkJobs", params._pathParam(0)) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { getHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + } +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/AccountService.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/AccountService.kt new file mode 100644 index 0000000..40a68cc --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/AccountService.kt @@ -0,0 +1,47 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.blocking + +import com.imagekit.api.core.ClientOptions +import com.imagekit.api.services.blocking.accounts.OriginService +import com.imagekit.api.services.blocking.accounts.UrlEndpointService +import com.imagekit.api.services.blocking.accounts.UsageService +import java.util.function.Consumer + +interface AccountService { + + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): AccountService + + fun usage(): UsageService + + fun origins(): OriginService + + fun urlEndpoints(): UrlEndpointService + + /** A view of [AccountService] that provides access to raw HTTP responses for each method. */ + interface WithRawResponse { + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): AccountService.WithRawResponse + + fun usage(): UsageService.WithRawResponse + + fun origins(): OriginService.WithRawResponse + + fun urlEndpoints(): UrlEndpointService.WithRawResponse + } +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/AccountServiceImpl.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/AccountServiceImpl.kt new file mode 100644 index 0000000..3f7a4a1 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/AccountServiceImpl.kt @@ -0,0 +1,66 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.blocking + +import com.imagekit.api.core.ClientOptions +import com.imagekit.api.services.blocking.accounts.OriginService +import com.imagekit.api.services.blocking.accounts.OriginServiceImpl +import com.imagekit.api.services.blocking.accounts.UrlEndpointService +import com.imagekit.api.services.blocking.accounts.UrlEndpointServiceImpl +import com.imagekit.api.services.blocking.accounts.UsageService +import com.imagekit.api.services.blocking.accounts.UsageServiceImpl +import java.util.function.Consumer + +class AccountServiceImpl internal constructor(private val clientOptions: ClientOptions) : + AccountService { + + private val withRawResponse: AccountService.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + private val usage: UsageService by lazy { UsageServiceImpl(clientOptions) } + + private val origins: OriginService by lazy { OriginServiceImpl(clientOptions) } + + private val urlEndpoints: UrlEndpointService by lazy { UrlEndpointServiceImpl(clientOptions) } + + override fun withRawResponse(): AccountService.WithRawResponse = withRawResponse + + override fun withOptions(modifier: Consumer): AccountService = + AccountServiceImpl(clientOptions.toBuilder().apply(modifier::accept).build()) + + override fun usage(): UsageService = usage + + override fun origins(): OriginService = origins + + override fun urlEndpoints(): UrlEndpointService = urlEndpoints + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + AccountService.WithRawResponse { + + private val usage: UsageService.WithRawResponse by lazy { + UsageServiceImpl.WithRawResponseImpl(clientOptions) + } + + private val origins: OriginService.WithRawResponse by lazy { + OriginServiceImpl.WithRawResponseImpl(clientOptions) + } + + private val urlEndpoints: UrlEndpointService.WithRawResponse by lazy { + UrlEndpointServiceImpl.WithRawResponseImpl(clientOptions) + } + + override fun withOptions( + modifier: Consumer + ): AccountService.WithRawResponse = + AccountServiceImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + override fun usage(): UsageService.WithRawResponse = usage + + override fun origins(): OriginService.WithRawResponse = origins + + override fun urlEndpoints(): UrlEndpointService.WithRawResponse = urlEndpoints + } +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/AssetService.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/AssetService.kt new file mode 100644 index 0000000..0d407ff --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/AssetService.kt @@ -0,0 +1,84 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.blocking + +import com.google.errorprone.annotations.MustBeClosed +import com.imagekit.api.core.ClientOptions +import com.imagekit.api.core.RequestOptions +import com.imagekit.api.core.http.HttpResponseFor +import com.imagekit.api.models.assets.AssetListParams +import com.imagekit.api.models.assets.AssetListResponse +import java.util.function.Consumer + +interface AssetService { + + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): AssetService + + /** + * This API can list all the uploaded files and folders in your ImageKit.io media library. In + * addition, you can fine-tune your query by specifying various filters by generating a query + * string in a Lucene-like syntax and provide this generated string as the value of the + * `searchQuery`. + */ + fun list(): List = list(AssetListParams.none()) + + /** @see list */ + fun list( + params: AssetListParams = AssetListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): List + + /** @see list */ + fun list(params: AssetListParams = AssetListParams.none()): List = + list(params, RequestOptions.none()) + + /** @see list */ + fun list(requestOptions: RequestOptions): List = + list(AssetListParams.none(), requestOptions) + + /** A view of [AssetService] that provides access to raw HTTP responses for each method. */ + interface WithRawResponse { + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): AssetService.WithRawResponse + + /** + * Returns a raw HTTP response for `get /v1/files`, but is otherwise the same as + * [AssetService.list]. + */ + @MustBeClosed + fun list(): HttpResponseFor> = list(AssetListParams.none()) + + /** @see list */ + @MustBeClosed + fun list( + params: AssetListParams = AssetListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor> + + /** @see list */ + @MustBeClosed + fun list( + params: AssetListParams = AssetListParams.none() + ): HttpResponseFor> = list(params, RequestOptions.none()) + + /** @see list */ + @MustBeClosed + fun list(requestOptions: RequestOptions): HttpResponseFor> = + list(AssetListParams.none(), requestOptions) + } +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/AssetServiceImpl.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/AssetServiceImpl.kt new file mode 100644 index 0000000..0297ddb --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/AssetServiceImpl.kt @@ -0,0 +1,80 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.blocking + +import com.imagekit.api.core.ClientOptions +import com.imagekit.api.core.RequestOptions +import com.imagekit.api.core.handlers.errorBodyHandler +import com.imagekit.api.core.handlers.errorHandler +import com.imagekit.api.core.handlers.jsonHandler +import com.imagekit.api.core.http.HttpMethod +import com.imagekit.api.core.http.HttpRequest +import com.imagekit.api.core.http.HttpResponse +import com.imagekit.api.core.http.HttpResponse.Handler +import com.imagekit.api.core.http.HttpResponseFor +import com.imagekit.api.core.http.parseable +import com.imagekit.api.core.prepare +import com.imagekit.api.models.assets.AssetListParams +import com.imagekit.api.models.assets.AssetListResponse +import java.util.function.Consumer + +class AssetServiceImpl internal constructor(private val clientOptions: ClientOptions) : + AssetService { + + private val withRawResponse: AssetService.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + override fun withRawResponse(): AssetService.WithRawResponse = withRawResponse + + override fun withOptions(modifier: Consumer): AssetService = + AssetServiceImpl(clientOptions.toBuilder().apply(modifier::accept).build()) + + override fun list( + params: AssetListParams, + requestOptions: RequestOptions, + ): List = + // get /v1/files + withRawResponse().list(params, requestOptions).parse() + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + AssetService.WithRawResponse { + + private val errorHandler: Handler = + errorHandler(errorBodyHandler(clientOptions.jsonMapper)) + + override fun withOptions( + modifier: Consumer + ): AssetService.WithRawResponse = + AssetServiceImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + private val listHandler: Handler> = + jsonHandler>(clientOptions.jsonMapper) + + override fun list( + params: AssetListParams, + requestOptions: RequestOptions, + ): HttpResponseFor> { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "files") + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { listHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.forEach { it.validate() } + } + } + } + } + } +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/BetaService.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/BetaService.kt new file mode 100644 index 0000000..4b76e4e --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/BetaService.kt @@ -0,0 +1,37 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.blocking + +import com.imagekit.api.core.ClientOptions +import com.imagekit.api.services.blocking.beta.V2Service +import java.util.function.Consumer + +interface BetaService { + + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): BetaService + + fun v2(): V2Service + + /** A view of [BetaService] that provides access to raw HTTP responses for each method. */ + interface WithRawResponse { + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): BetaService.WithRawResponse + + fun v2(): V2Service.WithRawResponse + } +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/BetaServiceImpl.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/BetaServiceImpl.kt new file mode 100644 index 0000000..89cc117 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/BetaServiceImpl.kt @@ -0,0 +1,41 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.blocking + +import com.imagekit.api.core.ClientOptions +import com.imagekit.api.services.blocking.beta.V2Service +import com.imagekit.api.services.blocking.beta.V2ServiceImpl +import java.util.function.Consumer + +class BetaServiceImpl internal constructor(private val clientOptions: ClientOptions) : BetaService { + + private val withRawResponse: BetaService.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + private val v2: V2Service by lazy { V2ServiceImpl(clientOptions) } + + override fun withRawResponse(): BetaService.WithRawResponse = withRawResponse + + override fun withOptions(modifier: Consumer): BetaService = + BetaServiceImpl(clientOptions.toBuilder().apply(modifier::accept).build()) + + override fun v2(): V2Service = v2 + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + BetaService.WithRawResponse { + + private val v2: V2Service.WithRawResponse by lazy { + V2ServiceImpl.WithRawResponseImpl(clientOptions) + } + + override fun withOptions( + modifier: Consumer + ): BetaService.WithRawResponse = + BetaServiceImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + override fun v2(): V2Service.WithRawResponse = v2 + } +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/CacheService.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/CacheService.kt new file mode 100644 index 0000000..f12bf84 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/CacheService.kt @@ -0,0 +1,37 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.blocking + +import com.imagekit.api.core.ClientOptions +import com.imagekit.api.services.blocking.cache.InvalidationService +import java.util.function.Consumer + +interface CacheService { + + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): CacheService + + fun invalidation(): InvalidationService + + /** A view of [CacheService] that provides access to raw HTTP responses for each method. */ + interface WithRawResponse { + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): CacheService.WithRawResponse + + fun invalidation(): InvalidationService.WithRawResponse + } +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/CacheServiceImpl.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/CacheServiceImpl.kt new file mode 100644 index 0000000..32e9296 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/CacheServiceImpl.kt @@ -0,0 +1,42 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.blocking + +import com.imagekit.api.core.ClientOptions +import com.imagekit.api.services.blocking.cache.InvalidationService +import com.imagekit.api.services.blocking.cache.InvalidationServiceImpl +import java.util.function.Consumer + +class CacheServiceImpl internal constructor(private val clientOptions: ClientOptions) : + CacheService { + + private val withRawResponse: CacheService.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + private val invalidation: InvalidationService by lazy { InvalidationServiceImpl(clientOptions) } + + override fun withRawResponse(): CacheService.WithRawResponse = withRawResponse + + override fun withOptions(modifier: Consumer): CacheService = + CacheServiceImpl(clientOptions.toBuilder().apply(modifier::accept).build()) + + override fun invalidation(): InvalidationService = invalidation + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + CacheService.WithRawResponse { + + private val invalidation: InvalidationService.WithRawResponse by lazy { + InvalidationServiceImpl.WithRawResponseImpl(clientOptions) + } + + override fun withOptions( + modifier: Consumer + ): CacheService.WithRawResponse = + CacheServiceImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + override fun invalidation(): InvalidationService.WithRawResponse = invalidation + } +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/CustomMetadataFieldService.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/CustomMetadataFieldService.kt new file mode 100644 index 0000000..bd644ee --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/CustomMetadataFieldService.kt @@ -0,0 +1,279 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.blocking + +import com.google.errorprone.annotations.MustBeClosed +import com.imagekit.api.core.ClientOptions +import com.imagekit.api.core.RequestOptions +import com.imagekit.api.core.http.HttpResponseFor +import com.imagekit.api.models.custommetadatafields.CustomMetadataField +import com.imagekit.api.models.custommetadatafields.CustomMetadataFieldCreateParams +import com.imagekit.api.models.custommetadatafields.CustomMetadataFieldDeleteParams +import com.imagekit.api.models.custommetadatafields.CustomMetadataFieldDeleteResponse +import com.imagekit.api.models.custommetadatafields.CustomMetadataFieldListParams +import com.imagekit.api.models.custommetadatafields.CustomMetadataFieldUpdateParams +import java.util.function.Consumer + +interface CustomMetadataFieldService { + + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): CustomMetadataFieldService + + /** + * This API creates a new custom metadata field. Once a custom metadata field is created either + * through this API or using the dashboard UI, its value can be set on the assets. The value of + * a field for an asset can be set using the media library UI or programmatically through upload + * or update assets API. + */ + fun create(params: CustomMetadataFieldCreateParams): CustomMetadataField = + create(params, RequestOptions.none()) + + /** @see create */ + fun create( + params: CustomMetadataFieldCreateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CustomMetadataField + + /** This API updates the label or schema of an existing custom metadata field. */ + fun update(id: String): CustomMetadataField = update(id, CustomMetadataFieldUpdateParams.none()) + + /** @see update */ + fun update( + id: String, + params: CustomMetadataFieldUpdateParams = CustomMetadataFieldUpdateParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CustomMetadataField = update(params.toBuilder().id(id).build(), requestOptions) + + /** @see update */ + fun update( + id: String, + params: CustomMetadataFieldUpdateParams = CustomMetadataFieldUpdateParams.none(), + ): CustomMetadataField = update(id, params, RequestOptions.none()) + + /** @see update */ + fun update( + params: CustomMetadataFieldUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CustomMetadataField + + /** @see update */ + fun update(params: CustomMetadataFieldUpdateParams): CustomMetadataField = + update(params, RequestOptions.none()) + + /** @see update */ + fun update(id: String, requestOptions: RequestOptions): CustomMetadataField = + update(id, CustomMetadataFieldUpdateParams.none(), requestOptions) + + /** + * This API returns the array of created custom metadata field objects. By default the API + * returns only non deleted field objects, but you can include deleted fields in the API + * response. + */ + fun list(): List = list(CustomMetadataFieldListParams.none()) + + /** @see list */ + fun list( + params: CustomMetadataFieldListParams = CustomMetadataFieldListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): List + + /** @see list */ + fun list( + params: CustomMetadataFieldListParams = CustomMetadataFieldListParams.none() + ): List = list(params, RequestOptions.none()) + + /** @see list */ + fun list(requestOptions: RequestOptions): List = + list(CustomMetadataFieldListParams.none(), requestOptions) + + /** + * This API deletes a custom metadata field. Even after deleting a custom metadata field, you + * cannot create any new custom metadata field with the same name. + */ + fun delete(id: String): CustomMetadataFieldDeleteResponse = + delete(id, CustomMetadataFieldDeleteParams.none()) + + /** @see delete */ + fun delete( + id: String, + params: CustomMetadataFieldDeleteParams = CustomMetadataFieldDeleteParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CustomMetadataFieldDeleteResponse = delete(params.toBuilder().id(id).build(), requestOptions) + + /** @see delete */ + fun delete( + id: String, + params: CustomMetadataFieldDeleteParams = CustomMetadataFieldDeleteParams.none(), + ): CustomMetadataFieldDeleteResponse = delete(id, params, RequestOptions.none()) + + /** @see delete */ + fun delete( + params: CustomMetadataFieldDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CustomMetadataFieldDeleteResponse + + /** @see delete */ + fun delete(params: CustomMetadataFieldDeleteParams): CustomMetadataFieldDeleteResponse = + delete(params, RequestOptions.none()) + + /** @see delete */ + fun delete(id: String, requestOptions: RequestOptions): CustomMetadataFieldDeleteResponse = + delete(id, CustomMetadataFieldDeleteParams.none(), requestOptions) + + /** + * A view of [CustomMetadataFieldService] that provides access to raw HTTP responses for each + * method. + */ + interface WithRawResponse { + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions( + modifier: Consumer + ): CustomMetadataFieldService.WithRawResponse + + /** + * Returns a raw HTTP response for `post /v1/customMetadataFields`, but is otherwise the + * same as [CustomMetadataFieldService.create]. + */ + @MustBeClosed + fun create(params: CustomMetadataFieldCreateParams): HttpResponseFor = + create(params, RequestOptions.none()) + + /** @see create */ + @MustBeClosed + fun create( + params: CustomMetadataFieldCreateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** + * Returns a raw HTTP response for `patch /v1/customMetadataFields/{id}`, but is otherwise + * the same as [CustomMetadataFieldService.update]. + */ + @MustBeClosed + fun update(id: String): HttpResponseFor = + update(id, CustomMetadataFieldUpdateParams.none()) + + /** @see update */ + @MustBeClosed + fun update( + id: String, + params: CustomMetadataFieldUpdateParams = CustomMetadataFieldUpdateParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor = + update(params.toBuilder().id(id).build(), requestOptions) + + /** @see update */ + @MustBeClosed + fun update( + id: String, + params: CustomMetadataFieldUpdateParams = CustomMetadataFieldUpdateParams.none(), + ): HttpResponseFor = update(id, params, RequestOptions.none()) + + /** @see update */ + @MustBeClosed + fun update( + params: CustomMetadataFieldUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see update */ + @MustBeClosed + fun update(params: CustomMetadataFieldUpdateParams): HttpResponseFor = + update(params, RequestOptions.none()) + + /** @see update */ + @MustBeClosed + fun update( + id: String, + requestOptions: RequestOptions, + ): HttpResponseFor = + update(id, CustomMetadataFieldUpdateParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `get /v1/customMetadataFields`, but is otherwise the same + * as [CustomMetadataFieldService.list]. + */ + @MustBeClosed + fun list(): HttpResponseFor> = + list(CustomMetadataFieldListParams.none()) + + /** @see list */ + @MustBeClosed + fun list( + params: CustomMetadataFieldListParams = CustomMetadataFieldListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor> + + /** @see list */ + @MustBeClosed + fun list( + params: CustomMetadataFieldListParams = CustomMetadataFieldListParams.none() + ): HttpResponseFor> = list(params, RequestOptions.none()) + + /** @see list */ + @MustBeClosed + fun list(requestOptions: RequestOptions): HttpResponseFor> = + list(CustomMetadataFieldListParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `delete /v1/customMetadataFields/{id}`, but is otherwise + * the same as [CustomMetadataFieldService.delete]. + */ + @MustBeClosed + fun delete(id: String): HttpResponseFor = + delete(id, CustomMetadataFieldDeleteParams.none()) + + /** @see delete */ + @MustBeClosed + fun delete( + id: String, + params: CustomMetadataFieldDeleteParams = CustomMetadataFieldDeleteParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor = + delete(params.toBuilder().id(id).build(), requestOptions) + + /** @see delete */ + @MustBeClosed + fun delete( + id: String, + params: CustomMetadataFieldDeleteParams = CustomMetadataFieldDeleteParams.none(), + ): HttpResponseFor = + delete(id, params, RequestOptions.none()) + + /** @see delete */ + @MustBeClosed + fun delete( + params: CustomMetadataFieldDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see delete */ + @MustBeClosed + fun delete( + params: CustomMetadataFieldDeleteParams + ): HttpResponseFor = + delete(params, RequestOptions.none()) + + /** @see delete */ + @MustBeClosed + fun delete( + id: String, + requestOptions: RequestOptions, + ): HttpResponseFor = + delete(id, CustomMetadataFieldDeleteParams.none(), requestOptions) + } +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/CustomMetadataFieldServiceImpl.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/CustomMetadataFieldServiceImpl.kt new file mode 100644 index 0000000..ac2e235 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/CustomMetadataFieldServiceImpl.kt @@ -0,0 +1,200 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.blocking + +import com.imagekit.api.core.ClientOptions +import com.imagekit.api.core.RequestOptions +import com.imagekit.api.core.checkRequired +import com.imagekit.api.core.handlers.errorBodyHandler +import com.imagekit.api.core.handlers.errorHandler +import com.imagekit.api.core.handlers.jsonHandler +import com.imagekit.api.core.http.HttpMethod +import com.imagekit.api.core.http.HttpRequest +import com.imagekit.api.core.http.HttpResponse +import com.imagekit.api.core.http.HttpResponse.Handler +import com.imagekit.api.core.http.HttpResponseFor +import com.imagekit.api.core.http.json +import com.imagekit.api.core.http.parseable +import com.imagekit.api.core.prepare +import com.imagekit.api.models.custommetadatafields.CustomMetadataField +import com.imagekit.api.models.custommetadatafields.CustomMetadataFieldCreateParams +import com.imagekit.api.models.custommetadatafields.CustomMetadataFieldDeleteParams +import com.imagekit.api.models.custommetadatafields.CustomMetadataFieldDeleteResponse +import com.imagekit.api.models.custommetadatafields.CustomMetadataFieldListParams +import com.imagekit.api.models.custommetadatafields.CustomMetadataFieldUpdateParams +import java.util.function.Consumer +import kotlin.jvm.optionals.getOrNull + +class CustomMetadataFieldServiceImpl +internal constructor(private val clientOptions: ClientOptions) : CustomMetadataFieldService { + + private val withRawResponse: CustomMetadataFieldService.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + override fun withRawResponse(): CustomMetadataFieldService.WithRawResponse = withRawResponse + + override fun withOptions( + modifier: Consumer + ): CustomMetadataFieldService = + CustomMetadataFieldServiceImpl(clientOptions.toBuilder().apply(modifier::accept).build()) + + override fun create( + params: CustomMetadataFieldCreateParams, + requestOptions: RequestOptions, + ): CustomMetadataField = + // post /v1/customMetadataFields + withRawResponse().create(params, requestOptions).parse() + + override fun update( + params: CustomMetadataFieldUpdateParams, + requestOptions: RequestOptions, + ): CustomMetadataField = + // patch /v1/customMetadataFields/{id} + withRawResponse().update(params, requestOptions).parse() + + override fun list( + params: CustomMetadataFieldListParams, + requestOptions: RequestOptions, + ): List = + // get /v1/customMetadataFields + withRawResponse().list(params, requestOptions).parse() + + override fun delete( + params: CustomMetadataFieldDeleteParams, + requestOptions: RequestOptions, + ): CustomMetadataFieldDeleteResponse = + // delete /v1/customMetadataFields/{id} + withRawResponse().delete(params, requestOptions).parse() + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + CustomMetadataFieldService.WithRawResponse { + + private val errorHandler: Handler = + errorHandler(errorBodyHandler(clientOptions.jsonMapper)) + + override fun withOptions( + modifier: Consumer + ): CustomMetadataFieldService.WithRawResponse = + CustomMetadataFieldServiceImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + private val createHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun create( + params: CustomMetadataFieldCreateParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "customMetadataFields") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { createHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + + private val updateHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun update( + params: CustomMetadataFieldUpdateParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("id", params.id().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.PATCH) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "customMetadataFields", params._pathParam(0)) + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { updateHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + + private val listHandler: Handler> = + jsonHandler>(clientOptions.jsonMapper) + + override fun list( + params: CustomMetadataFieldListParams, + requestOptions: RequestOptions, + ): HttpResponseFor> { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "customMetadataFields") + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { listHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.forEach { it.validate() } + } + } + } + } + + private val deleteHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun delete( + params: CustomMetadataFieldDeleteParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("id", params.id().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.DELETE) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "customMetadataFields", params._pathParam(0)) + .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { deleteHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/FileService.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/FileService.kt new file mode 100644 index 0000000..8f4e8f8 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/FileService.kt @@ -0,0 +1,409 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.blocking + +import com.google.errorprone.annotations.MustBeClosed +import com.imagekit.api.core.ClientOptions +import com.imagekit.api.core.RequestOptions +import com.imagekit.api.core.http.HttpResponse +import com.imagekit.api.core.http.HttpResponseFor +import com.imagekit.api.models.files.File +import com.imagekit.api.models.files.FileCopyParams +import com.imagekit.api.models.files.FileCopyResponse +import com.imagekit.api.models.files.FileDeleteParams +import com.imagekit.api.models.files.FileGetParams +import com.imagekit.api.models.files.FileMoveParams +import com.imagekit.api.models.files.FileMoveResponse +import com.imagekit.api.models.files.FileRenameParams +import com.imagekit.api.models.files.FileRenameResponse +import com.imagekit.api.models.files.FileUpdateParams +import com.imagekit.api.models.files.FileUpdateResponse +import com.imagekit.api.models.files.FileUploadParams +import com.imagekit.api.models.files.FileUploadResponse +import com.imagekit.api.services.blocking.files.BulkService +import com.imagekit.api.services.blocking.files.MetadataService +import com.imagekit.api.services.blocking.files.VersionService +import java.util.function.Consumer + +interface FileService { + + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): FileService + + fun bulk(): BulkService + + fun versions(): VersionService + + fun metadata(): MetadataService + + /** + * This API updates the details or attributes of the current version of the file. You can update + * `tags`, `customCoordinates`, `customMetadata`, publication status, remove existing `AITags` + * and apply extensions using this API. + */ + fun update(fileId: String): FileUpdateResponse = update(fileId, FileUpdateParams.none()) + + /** @see update */ + fun update( + fileId: String, + params: FileUpdateParams = FileUpdateParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): FileUpdateResponse = update(params.toBuilder().fileId(fileId).build(), requestOptions) + + /** @see update */ + fun update( + fileId: String, + params: FileUpdateParams = FileUpdateParams.none(), + ): FileUpdateResponse = update(fileId, params, RequestOptions.none()) + + /** @see update */ + fun update( + params: FileUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): FileUpdateResponse + + /** @see update */ + fun update(params: FileUpdateParams): FileUpdateResponse = update(params, RequestOptions.none()) + + /** @see update */ + fun update(fileId: String, requestOptions: RequestOptions): FileUpdateResponse = + update(fileId, FileUpdateParams.none(), requestOptions) + + /** + * This API deletes the file and all its file versions permanently. + * + * Note: If a file or specific transformation has been requested in the past, then the response + * is cached. Deleting a file does not purge the cache. You can purge the cache using purge + * cache API. + */ + fun delete(fileId: String) = delete(fileId, FileDeleteParams.none()) + + /** @see delete */ + fun delete( + fileId: String, + params: FileDeleteParams = FileDeleteParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ) = delete(params.toBuilder().fileId(fileId).build(), requestOptions) + + /** @see delete */ + fun delete(fileId: String, params: FileDeleteParams = FileDeleteParams.none()) = + delete(fileId, params, RequestOptions.none()) + + /** @see delete */ + fun delete(params: FileDeleteParams, requestOptions: RequestOptions = RequestOptions.none()) + + /** @see delete */ + fun delete(params: FileDeleteParams) = delete(params, RequestOptions.none()) + + /** @see delete */ + fun delete(fileId: String, requestOptions: RequestOptions) = + delete(fileId, FileDeleteParams.none(), requestOptions) + + /** + * This will copy a file from one folder to another. + * + * Note: If any file at the destination has the same name as the source file, then the source + * file and its versions (if `includeFileVersions` is set to true) will be appended to the + * destination file version history. + */ + fun copy(params: FileCopyParams): FileCopyResponse = copy(params, RequestOptions.none()) + + /** @see copy */ + fun copy( + params: FileCopyParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): FileCopyResponse + + /** + * This API returns an object with details or attributes about the current version of the file. + */ + fun get(fileId: String): File = get(fileId, FileGetParams.none()) + + /** @see get */ + fun get( + fileId: String, + params: FileGetParams = FileGetParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): File = get(params.toBuilder().fileId(fileId).build(), requestOptions) + + /** @see get */ + fun get(fileId: String, params: FileGetParams = FileGetParams.none()): File = + get(fileId, params, RequestOptions.none()) + + /** @see get */ + fun get(params: FileGetParams, requestOptions: RequestOptions = RequestOptions.none()): File + + /** @see get */ + fun get(params: FileGetParams): File = get(params, RequestOptions.none()) + + /** @see get */ + fun get(fileId: String, requestOptions: RequestOptions): File = + get(fileId, FileGetParams.none(), requestOptions) + + /** + * This will move a file and all its versions from one folder to another. + * + * Note: If any file at the destination has the same name as the source file, then the source + * file and its versions will be appended to the destination file. + */ + fun move(params: FileMoveParams): FileMoveResponse = move(params, RequestOptions.none()) + + /** @see move */ + fun move( + params: FileMoveParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): FileMoveResponse + + /** + * You can rename an already existing file in the media library using rename file API. This + * operation would rename all file versions of the file. + * + * Note: The old URLs will stop working. The file/file version URLs cached on CDN will continue + * to work unless a purge is requested. + */ + fun rename(params: FileRenameParams): FileRenameResponse = rename(params, RequestOptions.none()) + + /** @see rename */ + fun rename( + params: FileRenameParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): FileRenameResponse + + /** + * ImageKit.io allows you to upload files directly from both the server and client sides. For + * server-side uploads, private API key authentication is used. For client-side uploads, + * generate a one-time `token`, `signature`, and `expire` from your secure backend using private + * API. + * [Learn more](/docs/api-reference/upload-file/upload-file#how-to-implement-client-side-file-upload) + * about how to implement client-side file upload. + * + * The [V2 API](/docs/api-reference/upload-file/upload-file-v2) enhances security by verifying + * the entire payload using JWT. + * + * **File size limit** \ On the free plan, the maximum upload file sizes are 20MB for images, + * audio, and raw files and 100MB for videos. On the paid plan, these limits increase to 40MB + * for images, audio, and raw files and 2GB for videos. These limits can be further increased + * with higher-tier plans. + * + * **Version limit** \ A file can have a maximum of 100 versions. + * + * **Demo applications** + * - A full-fledged + * [upload widget using Uppy](https://github.com/imagekit-samples/uppy-uploader), supporting + * file selections from local storage, URL, Dropbox, Google Drive, Instagram, and more. + * - [Quick start guides](/docs/quick-start-guides) for various frameworks and technologies. + */ + fun upload(params: FileUploadParams): FileUploadResponse = upload(params, RequestOptions.none()) + + /** @see upload */ + fun upload( + params: FileUploadParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): FileUploadResponse + + /** A view of [FileService] that provides access to raw HTTP responses for each method. */ + interface WithRawResponse { + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): FileService.WithRawResponse + + fun bulk(): BulkService.WithRawResponse + + fun versions(): VersionService.WithRawResponse + + fun metadata(): MetadataService.WithRawResponse + + /** + * Returns a raw HTTP response for `patch /v1/files/{fileId}/details`, but is otherwise the + * same as [FileService.update]. + */ + @MustBeClosed + fun update(fileId: String): HttpResponseFor = + update(fileId, FileUpdateParams.none()) + + /** @see update */ + @MustBeClosed + fun update( + fileId: String, + params: FileUpdateParams = FileUpdateParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor = + update(params.toBuilder().fileId(fileId).build(), requestOptions) + + /** @see update */ + @MustBeClosed + fun update( + fileId: String, + params: FileUpdateParams = FileUpdateParams.none(), + ): HttpResponseFor = update(fileId, params, RequestOptions.none()) + + /** @see update */ + @MustBeClosed + fun update( + params: FileUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see update */ + @MustBeClosed + fun update(params: FileUpdateParams): HttpResponseFor = + update(params, RequestOptions.none()) + + /** @see update */ + @MustBeClosed + fun update( + fileId: String, + requestOptions: RequestOptions, + ): HttpResponseFor = + update(fileId, FileUpdateParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `delete /v1/files/{fileId}`, but is otherwise the same as + * [FileService.delete]. + */ + @MustBeClosed + fun delete(fileId: String): HttpResponse = delete(fileId, FileDeleteParams.none()) + + /** @see delete */ + @MustBeClosed + fun delete( + fileId: String, + params: FileDeleteParams = FileDeleteParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponse = delete(params.toBuilder().fileId(fileId).build(), requestOptions) + + /** @see delete */ + @MustBeClosed + fun delete( + fileId: String, + params: FileDeleteParams = FileDeleteParams.none(), + ): HttpResponse = delete(fileId, params, RequestOptions.none()) + + /** @see delete */ + @MustBeClosed + fun delete( + params: FileDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponse + + /** @see delete */ + @MustBeClosed + fun delete(params: FileDeleteParams): HttpResponse = delete(params, RequestOptions.none()) + + /** @see delete */ + @MustBeClosed + fun delete(fileId: String, requestOptions: RequestOptions): HttpResponse = + delete(fileId, FileDeleteParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `post /v1/files/copy`, but is otherwise the same as + * [FileService.copy]. + */ + @MustBeClosed + fun copy(params: FileCopyParams): HttpResponseFor = + copy(params, RequestOptions.none()) + + /** @see copy */ + @MustBeClosed + fun copy( + params: FileCopyParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** + * Returns a raw HTTP response for `get /v1/files/{fileId}/details`, but is otherwise the + * same as [FileService.get]. + */ + @MustBeClosed + fun get(fileId: String): HttpResponseFor = get(fileId, FileGetParams.none()) + + /** @see get */ + @MustBeClosed + fun get( + fileId: String, + params: FileGetParams = FileGetParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor = get(params.toBuilder().fileId(fileId).build(), requestOptions) + + /** @see get */ + @MustBeClosed + fun get( + fileId: String, + params: FileGetParams = FileGetParams.none(), + ): HttpResponseFor = get(fileId, params, RequestOptions.none()) + + /** @see get */ + @MustBeClosed + fun get( + params: FileGetParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see get */ + @MustBeClosed + fun get(params: FileGetParams): HttpResponseFor = get(params, RequestOptions.none()) + + /** @see get */ + @MustBeClosed + fun get(fileId: String, requestOptions: RequestOptions): HttpResponseFor = + get(fileId, FileGetParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `post /v1/files/move`, but is otherwise the same as + * [FileService.move]. + */ + @MustBeClosed + fun move(params: FileMoveParams): HttpResponseFor = + move(params, RequestOptions.none()) + + /** @see move */ + @MustBeClosed + fun move( + params: FileMoveParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** + * Returns a raw HTTP response for `put /v1/files/rename`, but is otherwise the same as + * [FileService.rename]. + */ + @MustBeClosed + fun rename(params: FileRenameParams): HttpResponseFor = + rename(params, RequestOptions.none()) + + /** @see rename */ + @MustBeClosed + fun rename( + params: FileRenameParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** + * Returns a raw HTTP response for `post /api/v1/files/upload`, but is otherwise the same as + * [FileService.upload]. + */ + @MustBeClosed + fun upload(params: FileUploadParams): HttpResponseFor = + upload(params, RequestOptions.none()) + + /** @see upload */ + @MustBeClosed + fun upload( + params: FileUploadParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + } +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/FileServiceImpl.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/FileServiceImpl.kt new file mode 100644 index 0000000..6448f2b --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/FileServiceImpl.kt @@ -0,0 +1,334 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.blocking + +import com.imagekit.api.core.ClientOptions +import com.imagekit.api.core.RequestOptions +import com.imagekit.api.core.checkRequired +import com.imagekit.api.core.handlers.emptyHandler +import com.imagekit.api.core.handlers.errorBodyHandler +import com.imagekit.api.core.handlers.errorHandler +import com.imagekit.api.core.handlers.jsonHandler +import com.imagekit.api.core.http.HttpMethod +import com.imagekit.api.core.http.HttpRequest +import com.imagekit.api.core.http.HttpResponse +import com.imagekit.api.core.http.HttpResponse.Handler +import com.imagekit.api.core.http.HttpResponseFor +import com.imagekit.api.core.http.json +import com.imagekit.api.core.http.multipartFormData +import com.imagekit.api.core.http.parseable +import com.imagekit.api.core.prepare +import com.imagekit.api.models.files.File +import com.imagekit.api.models.files.FileCopyParams +import com.imagekit.api.models.files.FileCopyResponse +import com.imagekit.api.models.files.FileDeleteParams +import com.imagekit.api.models.files.FileGetParams +import com.imagekit.api.models.files.FileMoveParams +import com.imagekit.api.models.files.FileMoveResponse +import com.imagekit.api.models.files.FileRenameParams +import com.imagekit.api.models.files.FileRenameResponse +import com.imagekit.api.models.files.FileUpdateParams +import com.imagekit.api.models.files.FileUpdateResponse +import com.imagekit.api.models.files.FileUploadParams +import com.imagekit.api.models.files.FileUploadResponse +import com.imagekit.api.services.blocking.files.BulkService +import com.imagekit.api.services.blocking.files.BulkServiceImpl +import com.imagekit.api.services.blocking.files.MetadataService +import com.imagekit.api.services.blocking.files.MetadataServiceImpl +import com.imagekit.api.services.blocking.files.VersionService +import com.imagekit.api.services.blocking.files.VersionServiceImpl +import java.util.function.Consumer +import kotlin.jvm.optionals.getOrNull + +class FileServiceImpl internal constructor(private val clientOptions: ClientOptions) : FileService { + + private val withRawResponse: FileService.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + private val bulk: BulkService by lazy { BulkServiceImpl(clientOptions) } + + private val versions: VersionService by lazy { VersionServiceImpl(clientOptions) } + + private val metadata: MetadataService by lazy { MetadataServiceImpl(clientOptions) } + + override fun withRawResponse(): FileService.WithRawResponse = withRawResponse + + override fun withOptions(modifier: Consumer): FileService = + FileServiceImpl(clientOptions.toBuilder().apply(modifier::accept).build()) + + override fun bulk(): BulkService = bulk + + override fun versions(): VersionService = versions + + override fun metadata(): MetadataService = metadata + + override fun update( + params: FileUpdateParams, + requestOptions: RequestOptions, + ): FileUpdateResponse = + // patch /v1/files/{fileId}/details + withRawResponse().update(params, requestOptions).parse() + + override fun delete(params: FileDeleteParams, requestOptions: RequestOptions) { + // delete /v1/files/{fileId} + withRawResponse().delete(params, requestOptions) + } + + override fun copy(params: FileCopyParams, requestOptions: RequestOptions): FileCopyResponse = + // post /v1/files/copy + withRawResponse().copy(params, requestOptions).parse() + + override fun get(params: FileGetParams, requestOptions: RequestOptions): File = + // get /v1/files/{fileId}/details + withRawResponse().get(params, requestOptions).parse() + + override fun move(params: FileMoveParams, requestOptions: RequestOptions): FileMoveResponse = + // post /v1/files/move + withRawResponse().move(params, requestOptions).parse() + + override fun rename( + params: FileRenameParams, + requestOptions: RequestOptions, + ): FileRenameResponse = + // put /v1/files/rename + withRawResponse().rename(params, requestOptions).parse() + + override fun upload( + params: FileUploadParams, + requestOptions: RequestOptions, + ): FileUploadResponse = + // post /api/v1/files/upload + withRawResponse().upload(params, requestOptions).parse() + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + FileService.WithRawResponse { + + private val errorHandler: Handler = + errorHandler(errorBodyHandler(clientOptions.jsonMapper)) + + private val bulk: BulkService.WithRawResponse by lazy { + BulkServiceImpl.WithRawResponseImpl(clientOptions) + } + + private val versions: VersionService.WithRawResponse by lazy { + VersionServiceImpl.WithRawResponseImpl(clientOptions) + } + + private val metadata: MetadataService.WithRawResponse by lazy { + MetadataServiceImpl.WithRawResponseImpl(clientOptions) + } + + override fun withOptions( + modifier: Consumer + ): FileService.WithRawResponse = + FileServiceImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + override fun bulk(): BulkService.WithRawResponse = bulk + + override fun versions(): VersionService.WithRawResponse = versions + + override fun metadata(): MetadataService.WithRawResponse = metadata + + private val updateHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun update( + params: FileUpdateParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("fileId", params.fileId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.PATCH) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "files", params._pathParam(0), "details") + .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { updateHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + + private val deleteHandler: Handler = emptyHandler() + + override fun delete( + params: FileDeleteParams, + requestOptions: RequestOptions, + ): HttpResponse { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("fileId", params.fileId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.DELETE) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "files", params._pathParam(0)) + .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response.use { deleteHandler.handle(it) } + } + } + + private val copyHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun copy( + params: FileCopyParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "files", "copy") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { copyHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + + private val getHandler: Handler = jsonHandler(clientOptions.jsonMapper) + + override fun get( + params: FileGetParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("fileId", params.fileId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "files", params._pathParam(0), "details") + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { getHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + + private val moveHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun move( + params: FileMoveParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "files", "move") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { moveHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + + private val renameHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun rename( + params: FileRenameParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.PUT) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "files", "rename") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { renameHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + + private val uploadHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun upload( + params: FileUploadParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl( + if (clientOptions.baseUrlOverridden()) clientOptions.baseUrl() + else "https://upload.imagekit.io" + ) + .addPathSegments("api", "v1", "files", "upload") + .body(multipartFormData(clientOptions.jsonMapper, params._body())) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { uploadHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/FolderService.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/FolderService.kt new file mode 100644 index 0000000..e38020e --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/FolderService.kt @@ -0,0 +1,193 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.blocking + +import com.google.errorprone.annotations.MustBeClosed +import com.imagekit.api.core.ClientOptions +import com.imagekit.api.core.RequestOptions +import com.imagekit.api.core.http.HttpResponseFor +import com.imagekit.api.models.folders.FolderCopyParams +import com.imagekit.api.models.folders.FolderCopyResponse +import com.imagekit.api.models.folders.FolderCreateParams +import com.imagekit.api.models.folders.FolderCreateResponse +import com.imagekit.api.models.folders.FolderDeleteParams +import com.imagekit.api.models.folders.FolderDeleteResponse +import com.imagekit.api.models.folders.FolderMoveParams +import com.imagekit.api.models.folders.FolderMoveResponse +import com.imagekit.api.models.folders.FolderRenameParams +import com.imagekit.api.models.folders.FolderRenameResponse +import com.imagekit.api.services.blocking.folders.JobService +import java.util.function.Consumer + +interface FolderService { + + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): FolderService + + fun job(): JobService + + /** + * This will create a new folder. You can specify the folder name and location of the parent + * folder where this new folder should be created. + */ + fun create(params: FolderCreateParams): FolderCreateResponse = + create(params, RequestOptions.none()) + + /** @see create */ + fun create( + params: FolderCreateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): FolderCreateResponse + + /** + * This will delete a folder and all its contents permanently. The API returns an empty + * response. + */ + fun delete(params: FolderDeleteParams): FolderDeleteResponse = + delete(params, RequestOptions.none()) + + /** @see delete */ + fun delete( + params: FolderDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): FolderDeleteResponse + + /** + * This will copy one folder into another. The selected folder, its nested folders, files, and + * their versions (in `includeVersions` is set to true) are copied in this operation. Note: If + * any file at the destination has the same name as the source file, then the source file and + * its versions will be appended to the destination file version history. + */ + fun copy(params: FolderCopyParams): FolderCopyResponse = copy(params, RequestOptions.none()) + + /** @see copy */ + fun copy( + params: FolderCopyParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): FolderCopyResponse + + /** + * This will move one folder into another. The selected folder, its nested folders, files, and + * their versions are moved in this operation. Note: If any file at the destination has the same + * name as the source file, then the source file and its versions will be appended to the + * destination file version history. + */ + fun move(params: FolderMoveParams): FolderMoveResponse = move(params, RequestOptions.none()) + + /** @see move */ + fun move( + params: FolderMoveParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): FolderMoveResponse + + /** + * This API allows you to rename an existing folder. The folder and all its nested assets and + * sub-folders will remain unchanged, but their paths will be updated to reflect the new folder + * name. + */ + fun rename(params: FolderRenameParams): FolderRenameResponse = + rename(params, RequestOptions.none()) + + /** @see rename */ + fun rename( + params: FolderRenameParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): FolderRenameResponse + + /** A view of [FolderService] that provides access to raw HTTP responses for each method. */ + interface WithRawResponse { + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): FolderService.WithRawResponse + + fun job(): JobService.WithRawResponse + + /** + * Returns a raw HTTP response for `post /v1/folder`, but is otherwise the same as + * [FolderService.create]. + */ + @MustBeClosed + fun create(params: FolderCreateParams): HttpResponseFor = + create(params, RequestOptions.none()) + + /** @see create */ + @MustBeClosed + fun create( + params: FolderCreateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** + * Returns a raw HTTP response for `delete /v1/folder`, but is otherwise the same as + * [FolderService.delete]. + */ + @MustBeClosed + fun delete(params: FolderDeleteParams): HttpResponseFor = + delete(params, RequestOptions.none()) + + /** @see delete */ + @MustBeClosed + fun delete( + params: FolderDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** + * Returns a raw HTTP response for `post /v1/bulkJobs/copyFolder`, but is otherwise the same + * as [FolderService.copy]. + */ + @MustBeClosed + fun copy(params: FolderCopyParams): HttpResponseFor = + copy(params, RequestOptions.none()) + + /** @see copy */ + @MustBeClosed + fun copy( + params: FolderCopyParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** + * Returns a raw HTTP response for `post /v1/bulkJobs/moveFolder`, but is otherwise the same + * as [FolderService.move]. + */ + @MustBeClosed + fun move(params: FolderMoveParams): HttpResponseFor = + move(params, RequestOptions.none()) + + /** @see move */ + @MustBeClosed + fun move( + params: FolderMoveParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** + * Returns a raw HTTP response for `post /v1/bulkJobs/renameFolder`, but is otherwise the + * same as [FolderService.rename]. + */ + @MustBeClosed + fun rename(params: FolderRenameParams): HttpResponseFor = + rename(params, RequestOptions.none()) + + /** @see rename */ + @MustBeClosed + fun rename( + params: FolderRenameParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + } +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/FolderServiceImpl.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/FolderServiceImpl.kt new file mode 100644 index 0000000..42a20bf --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/FolderServiceImpl.kt @@ -0,0 +1,242 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.blocking + +import com.imagekit.api.core.ClientOptions +import com.imagekit.api.core.RequestOptions +import com.imagekit.api.core.handlers.errorBodyHandler +import com.imagekit.api.core.handlers.errorHandler +import com.imagekit.api.core.handlers.jsonHandler +import com.imagekit.api.core.http.HttpMethod +import com.imagekit.api.core.http.HttpRequest +import com.imagekit.api.core.http.HttpResponse +import com.imagekit.api.core.http.HttpResponse.Handler +import com.imagekit.api.core.http.HttpResponseFor +import com.imagekit.api.core.http.json +import com.imagekit.api.core.http.parseable +import com.imagekit.api.core.prepare +import com.imagekit.api.models.folders.FolderCopyParams +import com.imagekit.api.models.folders.FolderCopyResponse +import com.imagekit.api.models.folders.FolderCreateParams +import com.imagekit.api.models.folders.FolderCreateResponse +import com.imagekit.api.models.folders.FolderDeleteParams +import com.imagekit.api.models.folders.FolderDeleteResponse +import com.imagekit.api.models.folders.FolderMoveParams +import com.imagekit.api.models.folders.FolderMoveResponse +import com.imagekit.api.models.folders.FolderRenameParams +import com.imagekit.api.models.folders.FolderRenameResponse +import com.imagekit.api.services.blocking.folders.JobService +import com.imagekit.api.services.blocking.folders.JobServiceImpl +import java.util.function.Consumer + +class FolderServiceImpl internal constructor(private val clientOptions: ClientOptions) : + FolderService { + + private val withRawResponse: FolderService.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + private val job: JobService by lazy { JobServiceImpl(clientOptions) } + + override fun withRawResponse(): FolderService.WithRawResponse = withRawResponse + + override fun withOptions(modifier: Consumer): FolderService = + FolderServiceImpl(clientOptions.toBuilder().apply(modifier::accept).build()) + + override fun job(): JobService = job + + override fun create( + params: FolderCreateParams, + requestOptions: RequestOptions, + ): FolderCreateResponse = + // post /v1/folder + withRawResponse().create(params, requestOptions).parse() + + override fun delete( + params: FolderDeleteParams, + requestOptions: RequestOptions, + ): FolderDeleteResponse = + // delete /v1/folder + withRawResponse().delete(params, requestOptions).parse() + + override fun copy( + params: FolderCopyParams, + requestOptions: RequestOptions, + ): FolderCopyResponse = + // post /v1/bulkJobs/copyFolder + withRawResponse().copy(params, requestOptions).parse() + + override fun move( + params: FolderMoveParams, + requestOptions: RequestOptions, + ): FolderMoveResponse = + // post /v1/bulkJobs/moveFolder + withRawResponse().move(params, requestOptions).parse() + + override fun rename( + params: FolderRenameParams, + requestOptions: RequestOptions, + ): FolderRenameResponse = + // post /v1/bulkJobs/renameFolder + withRawResponse().rename(params, requestOptions).parse() + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + FolderService.WithRawResponse { + + private val errorHandler: Handler = + errorHandler(errorBodyHandler(clientOptions.jsonMapper)) + + private val job: JobService.WithRawResponse by lazy { + JobServiceImpl.WithRawResponseImpl(clientOptions) + } + + override fun withOptions( + modifier: Consumer + ): FolderService.WithRawResponse = + FolderServiceImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + override fun job(): JobService.WithRawResponse = job + + private val createHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun create( + params: FolderCreateParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "folder") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { createHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + + private val deleteHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun delete( + params: FolderDeleteParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.DELETE) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "folder") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { deleteHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + + private val copyHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun copy( + params: FolderCopyParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "bulkJobs", "copyFolder") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { copyHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + + private val moveHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun move( + params: FolderMoveParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "bulkJobs", "moveFolder") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { moveHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + + private val renameHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun rename( + params: FolderRenameParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "bulkJobs", "renameFolder") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { renameHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/WebhookService.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/WebhookService.kt new file mode 100644 index 0000000..953d9d2 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/WebhookService.kt @@ -0,0 +1,49 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.blocking + +import com.imagekit.api.core.ClientOptions +import com.imagekit.api.errors.ImageKitInvalidDataException +import com.imagekit.api.models.webhooks.UnsafeUnwrapWebhookEvent +import com.imagekit.api.models.webhooks.UnwrapWebhookEvent +import java.util.function.Consumer + +interface WebhookService { + + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): WebhookService + + /** + * Unwraps a webhook event from its JSON representation. + * + * @throws ImageKitInvalidDataException if the body could not be parsed. + */ + fun unsafeUnwrap(body: String): UnsafeUnwrapWebhookEvent + + /** + * Unwraps a webhook event from its JSON representation. + * + * @throws ImageKitInvalidDataException if the body could not be parsed. + */ + fun unwrap(body: String): UnwrapWebhookEvent + + /** A view of [WebhookService] that provides access to raw HTTP responses for each method. */ + interface WithRawResponse { + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): WebhookService.WithRawResponse + } +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/WebhookServiceImpl.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/WebhookServiceImpl.kt new file mode 100644 index 0000000..7e81f40 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/WebhookServiceImpl.kt @@ -0,0 +1,58 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.blocking + +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.imagekit.api.core.ClientOptions +import com.imagekit.api.errors.ImageKitInvalidDataException +import com.imagekit.api.models.webhooks.UnsafeUnwrapWebhookEvent +import com.imagekit.api.models.webhooks.UnwrapWebhookEvent +import java.util.function.Consumer + +class WebhookServiceImpl internal constructor(private val clientOptions: ClientOptions) : + WebhookService { + + private val withRawResponse: WebhookService.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + override fun withRawResponse(): WebhookService.WithRawResponse = withRawResponse + + override fun withOptions(modifier: Consumer): WebhookService = + WebhookServiceImpl(clientOptions.toBuilder().apply(modifier::accept).build()) + + /** + * Unwraps a webhook event from its JSON representation. + * + * @throws ImageKitInvalidDataException if the body could not be parsed. + */ + override fun unsafeUnwrap(body: String): UnsafeUnwrapWebhookEvent = + try { + clientOptions.jsonMapper.readValue(body, jacksonTypeRef()) + } catch (e: Exception) { + throw ImageKitInvalidDataException("Error parsing body", e) + } + + /** + * Unwraps a webhook event from its JSON representation. + * + * @throws ImageKitInvalidDataException if the body could not be parsed. + */ + override fun unwrap(body: String): UnwrapWebhookEvent = + try { + clientOptions.jsonMapper.readValue(body, jacksonTypeRef()) + } catch (e: Exception) { + throw ImageKitInvalidDataException("Error parsing body", e) + } + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + WebhookService.WithRawResponse { + + override fun withOptions( + modifier: Consumer + ): WebhookService.WithRawResponse = + WebhookServiceImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + } +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/accounts/OriginService.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/accounts/OriginService.kt new file mode 100644 index 0000000..5d73533 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/accounts/OriginService.kt @@ -0,0 +1,295 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.blocking.accounts + +import com.google.errorprone.annotations.MustBeClosed +import com.imagekit.api.core.ClientOptions +import com.imagekit.api.core.RequestOptions +import com.imagekit.api.core.http.HttpResponse +import com.imagekit.api.core.http.HttpResponseFor +import com.imagekit.api.models.accounts.origins.OriginCreateParams +import com.imagekit.api.models.accounts.origins.OriginDeleteParams +import com.imagekit.api.models.accounts.origins.OriginGetParams +import com.imagekit.api.models.accounts.origins.OriginListParams +import com.imagekit.api.models.accounts.origins.OriginResponse +import com.imagekit.api.models.accounts.origins.OriginUpdateParams +import java.util.function.Consumer + +interface OriginService { + + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): OriginService + + /** + * **Note:** This API is currently in beta. Creates a new origin and returns the origin object. + */ + fun create(params: OriginCreateParams): OriginResponse = create(params, RequestOptions.none()) + + /** @see create */ + fun create( + params: OriginCreateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): OriginResponse + + /** + * **Note:** This API is currently in beta. Updates the origin identified by `id` and returns + * the updated origin object. + */ + fun update(id: String, params: OriginUpdateParams): OriginResponse = + update(id, params, RequestOptions.none()) + + /** @see update */ + fun update( + id: String, + params: OriginUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): OriginResponse = update(params.toBuilder().id(id).build(), requestOptions) + + /** @see update */ + fun update(params: OriginUpdateParams): OriginResponse = update(params, RequestOptions.none()) + + /** @see update */ + fun update( + params: OriginUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): OriginResponse + + /** + * **Note:** This API is currently in beta. Returns an array of all configured origins for the + * current account. + */ + fun list(): List = list(OriginListParams.none()) + + /** @see list */ + fun list( + params: OriginListParams = OriginListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): List + + /** @see list */ + fun list(params: OriginListParams = OriginListParams.none()): List = + list(params, RequestOptions.none()) + + /** @see list */ + fun list(requestOptions: RequestOptions): List = + list(OriginListParams.none(), requestOptions) + + /** + * **Note:** This API is currently in beta. Permanently removes the origin identified by `id`. + * If the origin is in use by any URL‑endpoints, the API will return an error. + */ + fun delete(id: String) = delete(id, OriginDeleteParams.none()) + + /** @see delete */ + fun delete( + id: String, + params: OriginDeleteParams = OriginDeleteParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ) = delete(params.toBuilder().id(id).build(), requestOptions) + + /** @see delete */ + fun delete(id: String, params: OriginDeleteParams = OriginDeleteParams.none()) = + delete(id, params, RequestOptions.none()) + + /** @see delete */ + fun delete(params: OriginDeleteParams, requestOptions: RequestOptions = RequestOptions.none()) + + /** @see delete */ + fun delete(params: OriginDeleteParams) = delete(params, RequestOptions.none()) + + /** @see delete */ + fun delete(id: String, requestOptions: RequestOptions) = + delete(id, OriginDeleteParams.none(), requestOptions) + + /** **Note:** This API is currently in beta. Retrieves the origin identified by `id`. */ + fun get(id: String): OriginResponse = get(id, OriginGetParams.none()) + + /** @see get */ + fun get( + id: String, + params: OriginGetParams = OriginGetParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): OriginResponse = get(params.toBuilder().id(id).build(), requestOptions) + + /** @see get */ + fun get(id: String, params: OriginGetParams = OriginGetParams.none()): OriginResponse = + get(id, params, RequestOptions.none()) + + /** @see get */ + fun get( + params: OriginGetParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): OriginResponse + + /** @see get */ + fun get(params: OriginGetParams): OriginResponse = get(params, RequestOptions.none()) + + /** @see get */ + fun get(id: String, requestOptions: RequestOptions): OriginResponse = + get(id, OriginGetParams.none(), requestOptions) + + /** A view of [OriginService] that provides access to raw HTTP responses for each method. */ + interface WithRawResponse { + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): OriginService.WithRawResponse + + /** + * Returns a raw HTTP response for `post /v1/accounts/origins`, but is otherwise the same as + * [OriginService.create]. + */ + @MustBeClosed + fun create(params: OriginCreateParams): HttpResponseFor = + create(params, RequestOptions.none()) + + /** @see create */ + @MustBeClosed + fun create( + params: OriginCreateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** + * Returns a raw HTTP response for `put /v1/accounts/origins/{id}`, but is otherwise the + * same as [OriginService.update]. + */ + @MustBeClosed + fun update(id: String, params: OriginUpdateParams): HttpResponseFor = + update(id, params, RequestOptions.none()) + + /** @see update */ + @MustBeClosed + fun update( + id: String, + params: OriginUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor = + update(params.toBuilder().id(id).build(), requestOptions) + + /** @see update */ + @MustBeClosed + fun update(params: OriginUpdateParams): HttpResponseFor = + update(params, RequestOptions.none()) + + /** @see update */ + @MustBeClosed + fun update( + params: OriginUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** + * Returns a raw HTTP response for `get /v1/accounts/origins`, but is otherwise the same as + * [OriginService.list]. + */ + @MustBeClosed + fun list(): HttpResponseFor> = list(OriginListParams.none()) + + /** @see list */ + @MustBeClosed + fun list( + params: OriginListParams = OriginListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor> + + /** @see list */ + @MustBeClosed + fun list( + params: OriginListParams = OriginListParams.none() + ): HttpResponseFor> = list(params, RequestOptions.none()) + + /** @see list */ + @MustBeClosed + fun list(requestOptions: RequestOptions): HttpResponseFor> = + list(OriginListParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `delete /v1/accounts/origins/{id}`, but is otherwise the + * same as [OriginService.delete]. + */ + @MustBeClosed fun delete(id: String): HttpResponse = delete(id, OriginDeleteParams.none()) + + /** @see delete */ + @MustBeClosed + fun delete( + id: String, + params: OriginDeleteParams = OriginDeleteParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponse = delete(params.toBuilder().id(id).build(), requestOptions) + + /** @see delete */ + @MustBeClosed + fun delete( + id: String, + params: OriginDeleteParams = OriginDeleteParams.none(), + ): HttpResponse = delete(id, params, RequestOptions.none()) + + /** @see delete */ + @MustBeClosed + fun delete( + params: OriginDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponse + + /** @see delete */ + @MustBeClosed + fun delete(params: OriginDeleteParams): HttpResponse = delete(params, RequestOptions.none()) + + /** @see delete */ + @MustBeClosed + fun delete(id: String, requestOptions: RequestOptions): HttpResponse = + delete(id, OriginDeleteParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `get /v1/accounts/origins/{id}`, but is otherwise the + * same as [OriginService.get]. + */ + @MustBeClosed + fun get(id: String): HttpResponseFor = get(id, OriginGetParams.none()) + + /** @see get */ + @MustBeClosed + fun get( + id: String, + params: OriginGetParams = OriginGetParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor = get(params.toBuilder().id(id).build(), requestOptions) + + /** @see get */ + @MustBeClosed + fun get( + id: String, + params: OriginGetParams = OriginGetParams.none(), + ): HttpResponseFor = get(id, params, RequestOptions.none()) + + /** @see get */ + @MustBeClosed + fun get( + params: OriginGetParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see get */ + @MustBeClosed + fun get(params: OriginGetParams): HttpResponseFor = + get(params, RequestOptions.none()) + + /** @see get */ + @MustBeClosed + fun get(id: String, requestOptions: RequestOptions): HttpResponseFor = + get(id, OriginGetParams.none(), requestOptions) + } +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/accounts/OriginServiceImpl.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/accounts/OriginServiceImpl.kt new file mode 100644 index 0000000..bbbd635 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/accounts/OriginServiceImpl.kt @@ -0,0 +1,224 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.blocking.accounts + +import com.imagekit.api.core.ClientOptions +import com.imagekit.api.core.RequestOptions +import com.imagekit.api.core.checkRequired +import com.imagekit.api.core.handlers.emptyHandler +import com.imagekit.api.core.handlers.errorBodyHandler +import com.imagekit.api.core.handlers.errorHandler +import com.imagekit.api.core.handlers.jsonHandler +import com.imagekit.api.core.http.HttpMethod +import com.imagekit.api.core.http.HttpRequest +import com.imagekit.api.core.http.HttpResponse +import com.imagekit.api.core.http.HttpResponse.Handler +import com.imagekit.api.core.http.HttpResponseFor +import com.imagekit.api.core.http.json +import com.imagekit.api.core.http.parseable +import com.imagekit.api.core.prepare +import com.imagekit.api.models.accounts.origins.OriginCreateParams +import com.imagekit.api.models.accounts.origins.OriginDeleteParams +import com.imagekit.api.models.accounts.origins.OriginGetParams +import com.imagekit.api.models.accounts.origins.OriginListParams +import com.imagekit.api.models.accounts.origins.OriginResponse +import com.imagekit.api.models.accounts.origins.OriginUpdateParams +import java.util.function.Consumer +import kotlin.jvm.optionals.getOrNull + +class OriginServiceImpl internal constructor(private val clientOptions: ClientOptions) : + OriginService { + + private val withRawResponse: OriginService.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + override fun withRawResponse(): OriginService.WithRawResponse = withRawResponse + + override fun withOptions(modifier: Consumer): OriginService = + OriginServiceImpl(clientOptions.toBuilder().apply(modifier::accept).build()) + + override fun create( + params: OriginCreateParams, + requestOptions: RequestOptions, + ): OriginResponse = + // post /v1/accounts/origins + withRawResponse().create(params, requestOptions).parse() + + override fun update( + params: OriginUpdateParams, + requestOptions: RequestOptions, + ): OriginResponse = + // put /v1/accounts/origins/{id} + withRawResponse().update(params, requestOptions).parse() + + override fun list( + params: OriginListParams, + requestOptions: RequestOptions, + ): List = + // get /v1/accounts/origins + withRawResponse().list(params, requestOptions).parse() + + override fun delete(params: OriginDeleteParams, requestOptions: RequestOptions) { + // delete /v1/accounts/origins/{id} + withRawResponse().delete(params, requestOptions) + } + + override fun get(params: OriginGetParams, requestOptions: RequestOptions): OriginResponse = + // get /v1/accounts/origins/{id} + withRawResponse().get(params, requestOptions).parse() + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + OriginService.WithRawResponse { + + private val errorHandler: Handler = + errorHandler(errorBodyHandler(clientOptions.jsonMapper)) + + override fun withOptions( + modifier: Consumer + ): OriginService.WithRawResponse = + OriginServiceImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + private val createHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun create( + params: OriginCreateParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "accounts", "origins") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { createHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + + private val updateHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun update( + params: OriginUpdateParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("id", params.id().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.PUT) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "accounts", "origins", params._pathParam(0)) + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { updateHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + + private val listHandler: Handler> = + jsonHandler>(clientOptions.jsonMapper) + + override fun list( + params: OriginListParams, + requestOptions: RequestOptions, + ): HttpResponseFor> { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "accounts", "origins") + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { listHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.forEach { it.validate() } + } + } + } + } + + private val deleteHandler: Handler = emptyHandler() + + override fun delete( + params: OriginDeleteParams, + requestOptions: RequestOptions, + ): HttpResponse { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("id", params.id().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.DELETE) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "accounts", "origins", params._pathParam(0)) + .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response.use { deleteHandler.handle(it) } + } + } + + private val getHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun get( + params: OriginGetParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("id", params.id().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "accounts", "origins", params._pathParam(0)) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { getHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/accounts/UrlEndpointService.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/accounts/UrlEndpointService.kt new file mode 100644 index 0000000..bdd10fd --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/accounts/UrlEndpointService.kt @@ -0,0 +1,314 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.blocking.accounts + +import com.google.errorprone.annotations.MustBeClosed +import com.imagekit.api.core.ClientOptions +import com.imagekit.api.core.RequestOptions +import com.imagekit.api.core.http.HttpResponse +import com.imagekit.api.core.http.HttpResponseFor +import com.imagekit.api.models.accounts.urlendpoints.UrlEndpointCreateParams +import com.imagekit.api.models.accounts.urlendpoints.UrlEndpointDeleteParams +import com.imagekit.api.models.accounts.urlendpoints.UrlEndpointGetParams +import com.imagekit.api.models.accounts.urlendpoints.UrlEndpointListParams +import com.imagekit.api.models.accounts.urlendpoints.UrlEndpointResponse +import com.imagekit.api.models.accounts.urlendpoints.UrlEndpointUpdateParams +import java.util.function.Consumer + +interface UrlEndpointService { + + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): UrlEndpointService + + /** + * **Note:** This API is currently in beta. Creates a new URL‑endpoint and returns the resulting + * object. + */ + fun create(params: UrlEndpointCreateParams): UrlEndpointResponse = + create(params, RequestOptions.none()) + + /** @see create */ + fun create( + params: UrlEndpointCreateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): UrlEndpointResponse + + /** + * **Note:** This API is currently in beta. Updates the URL‑endpoint identified by `id` and + * returns the updated object. + */ + fun update(id: String, params: UrlEndpointUpdateParams): UrlEndpointResponse = + update(id, params, RequestOptions.none()) + + /** @see update */ + fun update( + id: String, + params: UrlEndpointUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): UrlEndpointResponse = update(params.toBuilder().id(id).build(), requestOptions) + + /** @see update */ + fun update(params: UrlEndpointUpdateParams): UrlEndpointResponse = + update(params, RequestOptions.none()) + + /** @see update */ + fun update( + params: UrlEndpointUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): UrlEndpointResponse + + /** + * **Note:** This API is currently in beta. Returns an array of all URL‑endpoints configured + * including the default URL-endpoint generated by ImageKit during account creation. + */ + fun list(): List = list(UrlEndpointListParams.none()) + + /** @see list */ + fun list( + params: UrlEndpointListParams = UrlEndpointListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): List + + /** @see list */ + fun list( + params: UrlEndpointListParams = UrlEndpointListParams.none() + ): List = list(params, RequestOptions.none()) + + /** @see list */ + fun list(requestOptions: RequestOptions): List = + list(UrlEndpointListParams.none(), requestOptions) + + /** + * **Note:** This API is currently in beta. Deletes the URL‑endpoint identified by `id`. You + * cannot delete the default URL‑endpoint created by ImageKit during account creation. + */ + fun delete(id: String) = delete(id, UrlEndpointDeleteParams.none()) + + /** @see delete */ + fun delete( + id: String, + params: UrlEndpointDeleteParams = UrlEndpointDeleteParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ) = delete(params.toBuilder().id(id).build(), requestOptions) + + /** @see delete */ + fun delete(id: String, params: UrlEndpointDeleteParams = UrlEndpointDeleteParams.none()) = + delete(id, params, RequestOptions.none()) + + /** @see delete */ + fun delete( + params: UrlEndpointDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ) + + /** @see delete */ + fun delete(params: UrlEndpointDeleteParams) = delete(params, RequestOptions.none()) + + /** @see delete */ + fun delete(id: String, requestOptions: RequestOptions) = + delete(id, UrlEndpointDeleteParams.none(), requestOptions) + + /** **Note:** This API is currently in beta. Retrieves the URL‑endpoint identified by `id`. */ + fun get(id: String): UrlEndpointResponse = get(id, UrlEndpointGetParams.none()) + + /** @see get */ + fun get( + id: String, + params: UrlEndpointGetParams = UrlEndpointGetParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): UrlEndpointResponse = get(params.toBuilder().id(id).build(), requestOptions) + + /** @see get */ + fun get( + id: String, + params: UrlEndpointGetParams = UrlEndpointGetParams.none(), + ): UrlEndpointResponse = get(id, params, RequestOptions.none()) + + /** @see get */ + fun get( + params: UrlEndpointGetParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): UrlEndpointResponse + + /** @see get */ + fun get(params: UrlEndpointGetParams): UrlEndpointResponse = get(params, RequestOptions.none()) + + /** @see get */ + fun get(id: String, requestOptions: RequestOptions): UrlEndpointResponse = + get(id, UrlEndpointGetParams.none(), requestOptions) + + /** + * A view of [UrlEndpointService] that provides access to raw HTTP responses for each method. + */ + interface WithRawResponse { + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions( + modifier: Consumer + ): UrlEndpointService.WithRawResponse + + /** + * Returns a raw HTTP response for `post /v1/accounts/url-endpoints`, but is otherwise the + * same as [UrlEndpointService.create]. + */ + @MustBeClosed + fun create(params: UrlEndpointCreateParams): HttpResponseFor = + create(params, RequestOptions.none()) + + /** @see create */ + @MustBeClosed + fun create( + params: UrlEndpointCreateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** + * Returns a raw HTTP response for `put /v1/accounts/url-endpoints/{id}`, but is otherwise + * the same as [UrlEndpointService.update]. + */ + @MustBeClosed + fun update( + id: String, + params: UrlEndpointUpdateParams, + ): HttpResponseFor = update(id, params, RequestOptions.none()) + + /** @see update */ + @MustBeClosed + fun update( + id: String, + params: UrlEndpointUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor = + update(params.toBuilder().id(id).build(), requestOptions) + + /** @see update */ + @MustBeClosed + fun update(params: UrlEndpointUpdateParams): HttpResponseFor = + update(params, RequestOptions.none()) + + /** @see update */ + @MustBeClosed + fun update( + params: UrlEndpointUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** + * Returns a raw HTTP response for `get /v1/accounts/url-endpoints`, but is otherwise the + * same as [UrlEndpointService.list]. + */ + @MustBeClosed + fun list(): HttpResponseFor> = list(UrlEndpointListParams.none()) + + /** @see list */ + @MustBeClosed + fun list( + params: UrlEndpointListParams = UrlEndpointListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor> + + /** @see list */ + @MustBeClosed + fun list( + params: UrlEndpointListParams = UrlEndpointListParams.none() + ): HttpResponseFor> = list(params, RequestOptions.none()) + + /** @see list */ + @MustBeClosed + fun list(requestOptions: RequestOptions): HttpResponseFor> = + list(UrlEndpointListParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `delete /v1/accounts/url-endpoints/{id}`, but is + * otherwise the same as [UrlEndpointService.delete]. + */ + @MustBeClosed + fun delete(id: String): HttpResponse = delete(id, UrlEndpointDeleteParams.none()) + + /** @see delete */ + @MustBeClosed + fun delete( + id: String, + params: UrlEndpointDeleteParams = UrlEndpointDeleteParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponse = delete(params.toBuilder().id(id).build(), requestOptions) + + /** @see delete */ + @MustBeClosed + fun delete( + id: String, + params: UrlEndpointDeleteParams = UrlEndpointDeleteParams.none(), + ): HttpResponse = delete(id, params, RequestOptions.none()) + + /** @see delete */ + @MustBeClosed + fun delete( + params: UrlEndpointDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponse + + /** @see delete */ + @MustBeClosed + fun delete(params: UrlEndpointDeleteParams): HttpResponse = + delete(params, RequestOptions.none()) + + /** @see delete */ + @MustBeClosed + fun delete(id: String, requestOptions: RequestOptions): HttpResponse = + delete(id, UrlEndpointDeleteParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `get /v1/accounts/url-endpoints/{id}`, but is otherwise + * the same as [UrlEndpointService.get]. + */ + @MustBeClosed + fun get(id: String): HttpResponseFor = + get(id, UrlEndpointGetParams.none()) + + /** @see get */ + @MustBeClosed + fun get( + id: String, + params: UrlEndpointGetParams = UrlEndpointGetParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor = + get(params.toBuilder().id(id).build(), requestOptions) + + /** @see get */ + @MustBeClosed + fun get( + id: String, + params: UrlEndpointGetParams = UrlEndpointGetParams.none(), + ): HttpResponseFor = get(id, params, RequestOptions.none()) + + /** @see get */ + @MustBeClosed + fun get( + params: UrlEndpointGetParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see get */ + @MustBeClosed + fun get(params: UrlEndpointGetParams): HttpResponseFor = + get(params, RequestOptions.none()) + + /** @see get */ + @MustBeClosed + fun get(id: String, requestOptions: RequestOptions): HttpResponseFor = + get(id, UrlEndpointGetParams.none(), requestOptions) + } +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/accounts/UrlEndpointServiceImpl.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/accounts/UrlEndpointServiceImpl.kt new file mode 100644 index 0000000..5d2e17e --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/accounts/UrlEndpointServiceImpl.kt @@ -0,0 +1,227 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.blocking.accounts + +import com.imagekit.api.core.ClientOptions +import com.imagekit.api.core.RequestOptions +import com.imagekit.api.core.checkRequired +import com.imagekit.api.core.handlers.emptyHandler +import com.imagekit.api.core.handlers.errorBodyHandler +import com.imagekit.api.core.handlers.errorHandler +import com.imagekit.api.core.handlers.jsonHandler +import com.imagekit.api.core.http.HttpMethod +import com.imagekit.api.core.http.HttpRequest +import com.imagekit.api.core.http.HttpResponse +import com.imagekit.api.core.http.HttpResponse.Handler +import com.imagekit.api.core.http.HttpResponseFor +import com.imagekit.api.core.http.json +import com.imagekit.api.core.http.parseable +import com.imagekit.api.core.prepare +import com.imagekit.api.models.accounts.urlendpoints.UrlEndpointCreateParams +import com.imagekit.api.models.accounts.urlendpoints.UrlEndpointDeleteParams +import com.imagekit.api.models.accounts.urlendpoints.UrlEndpointGetParams +import com.imagekit.api.models.accounts.urlendpoints.UrlEndpointListParams +import com.imagekit.api.models.accounts.urlendpoints.UrlEndpointResponse +import com.imagekit.api.models.accounts.urlendpoints.UrlEndpointUpdateParams +import java.util.function.Consumer +import kotlin.jvm.optionals.getOrNull + +class UrlEndpointServiceImpl internal constructor(private val clientOptions: ClientOptions) : + UrlEndpointService { + + private val withRawResponse: UrlEndpointService.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + override fun withRawResponse(): UrlEndpointService.WithRawResponse = withRawResponse + + override fun withOptions(modifier: Consumer): UrlEndpointService = + UrlEndpointServiceImpl(clientOptions.toBuilder().apply(modifier::accept).build()) + + override fun create( + params: UrlEndpointCreateParams, + requestOptions: RequestOptions, + ): UrlEndpointResponse = + // post /v1/accounts/url-endpoints + withRawResponse().create(params, requestOptions).parse() + + override fun update( + params: UrlEndpointUpdateParams, + requestOptions: RequestOptions, + ): UrlEndpointResponse = + // put /v1/accounts/url-endpoints/{id} + withRawResponse().update(params, requestOptions).parse() + + override fun list( + params: UrlEndpointListParams, + requestOptions: RequestOptions, + ): List = + // get /v1/accounts/url-endpoints + withRawResponse().list(params, requestOptions).parse() + + override fun delete(params: UrlEndpointDeleteParams, requestOptions: RequestOptions) { + // delete /v1/accounts/url-endpoints/{id} + withRawResponse().delete(params, requestOptions) + } + + override fun get( + params: UrlEndpointGetParams, + requestOptions: RequestOptions, + ): UrlEndpointResponse = + // get /v1/accounts/url-endpoints/{id} + withRawResponse().get(params, requestOptions).parse() + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + UrlEndpointService.WithRawResponse { + + private val errorHandler: Handler = + errorHandler(errorBodyHandler(clientOptions.jsonMapper)) + + override fun withOptions( + modifier: Consumer + ): UrlEndpointService.WithRawResponse = + UrlEndpointServiceImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + private val createHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun create( + params: UrlEndpointCreateParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "accounts", "url-endpoints") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { createHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + + private val updateHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun update( + params: UrlEndpointUpdateParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("id", params.id().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.PUT) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "accounts", "url-endpoints", params._pathParam(0)) + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { updateHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + + private val listHandler: Handler> = + jsonHandler>(clientOptions.jsonMapper) + + override fun list( + params: UrlEndpointListParams, + requestOptions: RequestOptions, + ): HttpResponseFor> { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "accounts", "url-endpoints") + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { listHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.forEach { it.validate() } + } + } + } + } + + private val deleteHandler: Handler = emptyHandler() + + override fun delete( + params: UrlEndpointDeleteParams, + requestOptions: RequestOptions, + ): HttpResponse { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("id", params.id().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.DELETE) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "accounts", "url-endpoints", params._pathParam(0)) + .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response.use { deleteHandler.handle(it) } + } + } + + private val getHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun get( + params: UrlEndpointGetParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("id", params.id().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "accounts", "url-endpoints", params._pathParam(0)) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { getHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/accounts/UsageService.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/accounts/UsageService.kt new file mode 100644 index 0000000..5cdcc94 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/accounts/UsageService.kt @@ -0,0 +1,65 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.blocking.accounts + +import com.google.errorprone.annotations.MustBeClosed +import com.imagekit.api.core.ClientOptions +import com.imagekit.api.core.RequestOptions +import com.imagekit.api.core.http.HttpResponseFor +import com.imagekit.api.models.accounts.usage.UsageGetParams +import com.imagekit.api.models.accounts.usage.UsageGetResponse +import java.util.function.Consumer + +interface UsageService { + + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): UsageService + + /** + * Get the account usage information between two dates. Note that the API response includes data + * from the start date while excluding data from the end date. In other words, the data covers + * the period starting from the specified start date up to, but not including, the end date. + */ + fun get(params: UsageGetParams): UsageGetResponse = get(params, RequestOptions.none()) + + /** @see get */ + fun get( + params: UsageGetParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): UsageGetResponse + + /** A view of [UsageService] that provides access to raw HTTP responses for each method. */ + interface WithRawResponse { + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): UsageService.WithRawResponse + + /** + * Returns a raw HTTP response for `get /v1/accounts/usage`, but is otherwise the same as + * [UsageService.get]. + */ + @MustBeClosed + fun get(params: UsageGetParams): HttpResponseFor = + get(params, RequestOptions.none()) + + /** @see get */ + @MustBeClosed + fun get( + params: UsageGetParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + } +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/accounts/UsageServiceImpl.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/accounts/UsageServiceImpl.kt new file mode 100644 index 0000000..e9884d2 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/accounts/UsageServiceImpl.kt @@ -0,0 +1,77 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.blocking.accounts + +import com.imagekit.api.core.ClientOptions +import com.imagekit.api.core.RequestOptions +import com.imagekit.api.core.handlers.errorBodyHandler +import com.imagekit.api.core.handlers.errorHandler +import com.imagekit.api.core.handlers.jsonHandler +import com.imagekit.api.core.http.HttpMethod +import com.imagekit.api.core.http.HttpRequest +import com.imagekit.api.core.http.HttpResponse +import com.imagekit.api.core.http.HttpResponse.Handler +import com.imagekit.api.core.http.HttpResponseFor +import com.imagekit.api.core.http.parseable +import com.imagekit.api.core.prepare +import com.imagekit.api.models.accounts.usage.UsageGetParams +import com.imagekit.api.models.accounts.usage.UsageGetResponse +import java.util.function.Consumer + +class UsageServiceImpl internal constructor(private val clientOptions: ClientOptions) : + UsageService { + + private val withRawResponse: UsageService.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + override fun withRawResponse(): UsageService.WithRawResponse = withRawResponse + + override fun withOptions(modifier: Consumer): UsageService = + UsageServiceImpl(clientOptions.toBuilder().apply(modifier::accept).build()) + + override fun get(params: UsageGetParams, requestOptions: RequestOptions): UsageGetResponse = + // get /v1/accounts/usage + withRawResponse().get(params, requestOptions).parse() + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + UsageService.WithRawResponse { + + private val errorHandler: Handler = + errorHandler(errorBodyHandler(clientOptions.jsonMapper)) + + override fun withOptions( + modifier: Consumer + ): UsageService.WithRawResponse = + UsageServiceImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + private val getHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun get( + params: UsageGetParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "accounts", "usage") + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { getHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/beta/V2Service.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/beta/V2Service.kt new file mode 100644 index 0000000..9452e84 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/beta/V2Service.kt @@ -0,0 +1,37 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.blocking.beta + +import com.imagekit.api.core.ClientOptions +import com.imagekit.api.services.blocking.beta.v2.FileService +import java.util.function.Consumer + +interface V2Service { + + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): V2Service + + fun files(): FileService + + /** A view of [V2Service] that provides access to raw HTTP responses for each method. */ + interface WithRawResponse { + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): V2Service.WithRawResponse + + fun files(): FileService.WithRawResponse + } +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/beta/V2ServiceImpl.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/beta/V2ServiceImpl.kt new file mode 100644 index 0000000..43beea3 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/beta/V2ServiceImpl.kt @@ -0,0 +1,41 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.blocking.beta + +import com.imagekit.api.core.ClientOptions +import com.imagekit.api.services.blocking.beta.v2.FileService +import com.imagekit.api.services.blocking.beta.v2.FileServiceImpl +import java.util.function.Consumer + +class V2ServiceImpl internal constructor(private val clientOptions: ClientOptions) : V2Service { + + private val withRawResponse: V2Service.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + private val files: FileService by lazy { FileServiceImpl(clientOptions) } + + override fun withRawResponse(): V2Service.WithRawResponse = withRawResponse + + override fun withOptions(modifier: Consumer): V2Service = + V2ServiceImpl(clientOptions.toBuilder().apply(modifier::accept).build()) + + override fun files(): FileService = files + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + V2Service.WithRawResponse { + + private val files: FileService.WithRawResponse by lazy { + FileServiceImpl.WithRawResponseImpl(clientOptions) + } + + override fun withOptions( + modifier: Consumer + ): V2Service.WithRawResponse = + V2ServiceImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + override fun files(): FileService.WithRawResponse = files + } +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/beta/v2/FileService.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/beta/v2/FileService.kt new file mode 100644 index 0000000..70d9c46 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/beta/v2/FileService.kt @@ -0,0 +1,82 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.blocking.beta.v2 + +import com.google.errorprone.annotations.MustBeClosed +import com.imagekit.api.core.ClientOptions +import com.imagekit.api.core.RequestOptions +import com.imagekit.api.core.http.HttpResponseFor +import com.imagekit.api.models.beta.v2.files.FileUploadParams +import com.imagekit.api.models.beta.v2.files.FileUploadResponse +import java.util.function.Consumer + +interface FileService { + + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): FileService + + /** + * The V2 API enhances security by verifying the entire payload using JWT. This API is in beta. + * + * ImageKit.io allows you to upload files directly from both the server and client sides. For + * server-side uploads, private API key authentication is used. For client-side uploads, + * generate a one-time `token` from your secure backend using private API. + * [Learn more](/docs/api-reference/upload-file/upload-file-v2#how-to-implement-secure-client-side-file-upload) + * about how to implement secure client-side file upload. + * + * **File size limit** \ On the free plan, the maximum upload file sizes are 20MB for images, + * audio, and raw files, and 100MB for videos. On the paid plan, these limits increase to 40MB + * for images, audio, and raw files, and 2GB for videos. These limits can be further increased + * with higher-tier plans. + * + * **Version limit** \ A file can have a maximum of 100 versions. + * + * **Demo applications** + * - A full-fledged + * [upload widget using Uppy](https://github.com/imagekit-samples/uppy-uploader), supporting + * file selections from local storage, URL, Dropbox, Google Drive, Instagram, and more. + * - [Quick start guides](/docs/quick-start-guides) for various frameworks and technologies. + */ + fun upload(params: FileUploadParams): FileUploadResponse = upload(params, RequestOptions.none()) + + /** @see upload */ + fun upload( + params: FileUploadParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): FileUploadResponse + + /** A view of [FileService] that provides access to raw HTTP responses for each method. */ + interface WithRawResponse { + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): FileService.WithRawResponse + + /** + * Returns a raw HTTP response for `post /api/v2/files/upload`, but is otherwise the same as + * [FileService.upload]. + */ + @MustBeClosed + fun upload(params: FileUploadParams): HttpResponseFor = + upload(params, RequestOptions.none()) + + /** @see upload */ + @MustBeClosed + fun upload( + params: FileUploadParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + } +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/beta/v2/FileServiceImpl.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/beta/v2/FileServiceImpl.kt new file mode 100644 index 0000000..17203ae --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/beta/v2/FileServiceImpl.kt @@ -0,0 +1,84 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.blocking.beta.v2 + +import com.imagekit.api.core.ClientOptions +import com.imagekit.api.core.RequestOptions +import com.imagekit.api.core.handlers.errorBodyHandler +import com.imagekit.api.core.handlers.errorHandler +import com.imagekit.api.core.handlers.jsonHandler +import com.imagekit.api.core.http.HttpMethod +import com.imagekit.api.core.http.HttpRequest +import com.imagekit.api.core.http.HttpResponse +import com.imagekit.api.core.http.HttpResponse.Handler +import com.imagekit.api.core.http.HttpResponseFor +import com.imagekit.api.core.http.multipartFormData +import com.imagekit.api.core.http.parseable +import com.imagekit.api.core.prepare +import com.imagekit.api.models.beta.v2.files.FileUploadParams +import com.imagekit.api.models.beta.v2.files.FileUploadResponse +import java.util.function.Consumer + +class FileServiceImpl internal constructor(private val clientOptions: ClientOptions) : FileService { + + private val withRawResponse: FileService.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + override fun withRawResponse(): FileService.WithRawResponse = withRawResponse + + override fun withOptions(modifier: Consumer): FileService = + FileServiceImpl(clientOptions.toBuilder().apply(modifier::accept).build()) + + override fun upload( + params: FileUploadParams, + requestOptions: RequestOptions, + ): FileUploadResponse = + // post /api/v2/files/upload + withRawResponse().upload(params, requestOptions).parse() + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + FileService.WithRawResponse { + + private val errorHandler: Handler = + errorHandler(errorBodyHandler(clientOptions.jsonMapper)) + + override fun withOptions( + modifier: Consumer + ): FileService.WithRawResponse = + FileServiceImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + private val uploadHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun upload( + params: FileUploadParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl( + if (clientOptions.baseUrlOverridden()) clientOptions.baseUrl() + else "https://upload.imagekit.io" + ) + .addPathSegments("api", "v2", "files", "upload") + .body(multipartFormData(clientOptions.jsonMapper, params._body())) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { uploadHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/cache/InvalidationService.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/cache/InvalidationService.kt new file mode 100644 index 0000000..4a5bd1e --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/cache/InvalidationService.kt @@ -0,0 +1,147 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.blocking.cache + +import com.google.errorprone.annotations.MustBeClosed +import com.imagekit.api.core.ClientOptions +import com.imagekit.api.core.RequestOptions +import com.imagekit.api.core.http.HttpResponseFor +import com.imagekit.api.models.cache.invalidation.InvalidationCreateParams +import com.imagekit.api.models.cache.invalidation.InvalidationCreateResponse +import com.imagekit.api.models.cache.invalidation.InvalidationGetParams +import com.imagekit.api.models.cache.invalidation.InvalidationGetResponse +import java.util.function.Consumer + +interface InvalidationService { + + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): InvalidationService + + /** + * This API will purge CDN cache and ImageKit.io's internal cache for a file. Note: Purge cache + * is an asynchronous process and it may take some time to reflect the changes. + */ + fun create(params: InvalidationCreateParams): InvalidationCreateResponse = + create(params, RequestOptions.none()) + + /** @see create */ + fun create( + params: InvalidationCreateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): InvalidationCreateResponse + + /** This API returns the status of a purge cache request. */ + fun get(requestId: String): InvalidationGetResponse = + get(requestId, InvalidationGetParams.none()) + + /** @see get */ + fun get( + requestId: String, + params: InvalidationGetParams = InvalidationGetParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): InvalidationGetResponse = + get(params.toBuilder().requestId(requestId).build(), requestOptions) + + /** @see get */ + fun get( + requestId: String, + params: InvalidationGetParams = InvalidationGetParams.none(), + ): InvalidationGetResponse = get(requestId, params, RequestOptions.none()) + + /** @see get */ + fun get( + params: InvalidationGetParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): InvalidationGetResponse + + /** @see get */ + fun get(params: InvalidationGetParams): InvalidationGetResponse = + get(params, RequestOptions.none()) + + /** @see get */ + fun get(requestId: String, requestOptions: RequestOptions): InvalidationGetResponse = + get(requestId, InvalidationGetParams.none(), requestOptions) + + /** + * A view of [InvalidationService] that provides access to raw HTTP responses for each method. + */ + interface WithRawResponse { + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions( + modifier: Consumer + ): InvalidationService.WithRawResponse + + /** + * Returns a raw HTTP response for `post /v1/files/purge`, but is otherwise the same as + * [InvalidationService.create]. + */ + @MustBeClosed + fun create(params: InvalidationCreateParams): HttpResponseFor = + create(params, RequestOptions.none()) + + /** @see create */ + @MustBeClosed + fun create( + params: InvalidationCreateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** + * Returns a raw HTTP response for `get /v1/files/purge/{requestId}`, but is otherwise the + * same as [InvalidationService.get]. + */ + @MustBeClosed + fun get(requestId: String): HttpResponseFor = + get(requestId, InvalidationGetParams.none()) + + /** @see get */ + @MustBeClosed + fun get( + requestId: String, + params: InvalidationGetParams = InvalidationGetParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor = + get(params.toBuilder().requestId(requestId).build(), requestOptions) + + /** @see get */ + @MustBeClosed + fun get( + requestId: String, + params: InvalidationGetParams = InvalidationGetParams.none(), + ): HttpResponseFor = get(requestId, params, RequestOptions.none()) + + /** @see get */ + @MustBeClosed + fun get( + params: InvalidationGetParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see get */ + @MustBeClosed + fun get(params: InvalidationGetParams): HttpResponseFor = + get(params, RequestOptions.none()) + + /** @see get */ + @MustBeClosed + fun get( + requestId: String, + requestOptions: RequestOptions, + ): HttpResponseFor = + get(requestId, InvalidationGetParams.none(), requestOptions) + } +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/cache/InvalidationServiceImpl.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/cache/InvalidationServiceImpl.kt new file mode 100644 index 0000000..72aee8d --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/cache/InvalidationServiceImpl.kt @@ -0,0 +1,123 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.blocking.cache + +import com.imagekit.api.core.ClientOptions +import com.imagekit.api.core.RequestOptions +import com.imagekit.api.core.checkRequired +import com.imagekit.api.core.handlers.errorBodyHandler +import com.imagekit.api.core.handlers.errorHandler +import com.imagekit.api.core.handlers.jsonHandler +import com.imagekit.api.core.http.HttpMethod +import com.imagekit.api.core.http.HttpRequest +import com.imagekit.api.core.http.HttpResponse +import com.imagekit.api.core.http.HttpResponse.Handler +import com.imagekit.api.core.http.HttpResponseFor +import com.imagekit.api.core.http.json +import com.imagekit.api.core.http.parseable +import com.imagekit.api.core.prepare +import com.imagekit.api.models.cache.invalidation.InvalidationCreateParams +import com.imagekit.api.models.cache.invalidation.InvalidationCreateResponse +import com.imagekit.api.models.cache.invalidation.InvalidationGetParams +import com.imagekit.api.models.cache.invalidation.InvalidationGetResponse +import java.util.function.Consumer +import kotlin.jvm.optionals.getOrNull + +class InvalidationServiceImpl internal constructor(private val clientOptions: ClientOptions) : + InvalidationService { + + private val withRawResponse: InvalidationService.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + override fun withRawResponse(): InvalidationService.WithRawResponse = withRawResponse + + override fun withOptions(modifier: Consumer): InvalidationService = + InvalidationServiceImpl(clientOptions.toBuilder().apply(modifier::accept).build()) + + override fun create( + params: InvalidationCreateParams, + requestOptions: RequestOptions, + ): InvalidationCreateResponse = + // post /v1/files/purge + withRawResponse().create(params, requestOptions).parse() + + override fun get( + params: InvalidationGetParams, + requestOptions: RequestOptions, + ): InvalidationGetResponse = + // get /v1/files/purge/{requestId} + withRawResponse().get(params, requestOptions).parse() + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + InvalidationService.WithRawResponse { + + private val errorHandler: Handler = + errorHandler(errorBodyHandler(clientOptions.jsonMapper)) + + override fun withOptions( + modifier: Consumer + ): InvalidationService.WithRawResponse = + InvalidationServiceImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + private val createHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun create( + params: InvalidationCreateParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "files", "purge") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { createHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + + private val getHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun get( + params: InvalidationGetParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("requestId", params.requestId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "files", "purge", params._pathParam(0)) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { getHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/files/BulkService.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/files/BulkService.kt new file mode 100644 index 0000000..dbc0c40 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/files/BulkService.kt @@ -0,0 +1,160 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.blocking.files + +import com.google.errorprone.annotations.MustBeClosed +import com.imagekit.api.core.ClientOptions +import com.imagekit.api.core.RequestOptions +import com.imagekit.api.core.http.HttpResponseFor +import com.imagekit.api.models.files.bulk.BulkAddTagsParams +import com.imagekit.api.models.files.bulk.BulkAddTagsResponse +import com.imagekit.api.models.files.bulk.BulkDeleteParams +import com.imagekit.api.models.files.bulk.BulkDeleteResponse +import com.imagekit.api.models.files.bulk.BulkRemoveAiTagsParams +import com.imagekit.api.models.files.bulk.BulkRemoveAiTagsResponse +import com.imagekit.api.models.files.bulk.BulkRemoveTagsParams +import com.imagekit.api.models.files.bulk.BulkRemoveTagsResponse +import java.util.function.Consumer + +interface BulkService { + + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): BulkService + + /** + * This API deletes multiple files and all their file versions permanently. + * + * Note: If a file or specific transformation has been requested in the past, then the response + * is cached. Deleting a file does not purge the cache. You can purge the cache using purge + * cache API. + * + * A maximum of 100 files can be deleted at a time. + */ + fun delete(params: BulkDeleteParams): BulkDeleteResponse = delete(params, RequestOptions.none()) + + /** @see delete */ + fun delete( + params: BulkDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): BulkDeleteResponse + + /** + * This API adds tags to multiple files in bulk. A maximum of 50 files can be specified at a + * time. + */ + fun addTags(params: BulkAddTagsParams): BulkAddTagsResponse = + addTags(params, RequestOptions.none()) + + /** @see addTags */ + fun addTags( + params: BulkAddTagsParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): BulkAddTagsResponse + + /** + * This API removes AITags from multiple files in bulk. A maximum of 50 files can be specified + * at a time. + */ + fun removeAiTags(params: BulkRemoveAiTagsParams): BulkRemoveAiTagsResponse = + removeAiTags(params, RequestOptions.none()) + + /** @see removeAiTags */ + fun removeAiTags( + params: BulkRemoveAiTagsParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): BulkRemoveAiTagsResponse + + /** + * This API removes tags from multiple files in bulk. A maximum of 50 files can be specified at + * a time. + */ + fun removeTags(params: BulkRemoveTagsParams): BulkRemoveTagsResponse = + removeTags(params, RequestOptions.none()) + + /** @see removeTags */ + fun removeTags( + params: BulkRemoveTagsParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): BulkRemoveTagsResponse + + /** A view of [BulkService] that provides access to raw HTTP responses for each method. */ + interface WithRawResponse { + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): BulkService.WithRawResponse + + /** + * Returns a raw HTTP response for `post /v1/files/batch/deleteByFileIds`, but is otherwise + * the same as [BulkService.delete]. + */ + @MustBeClosed + fun delete(params: BulkDeleteParams): HttpResponseFor = + delete(params, RequestOptions.none()) + + /** @see delete */ + @MustBeClosed + fun delete( + params: BulkDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** + * Returns a raw HTTP response for `post /v1/files/addTags`, but is otherwise the same as + * [BulkService.addTags]. + */ + @MustBeClosed + fun addTags(params: BulkAddTagsParams): HttpResponseFor = + addTags(params, RequestOptions.none()) + + /** @see addTags */ + @MustBeClosed + fun addTags( + params: BulkAddTagsParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** + * Returns a raw HTTP response for `post /v1/files/removeAITags`, but is otherwise the same + * as [BulkService.removeAiTags]. + */ + @MustBeClosed + fun removeAiTags( + params: BulkRemoveAiTagsParams + ): HttpResponseFor = removeAiTags(params, RequestOptions.none()) + + /** @see removeAiTags */ + @MustBeClosed + fun removeAiTags( + params: BulkRemoveAiTagsParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** + * Returns a raw HTTP response for `post /v1/files/removeTags`, but is otherwise the same as + * [BulkService.removeTags]. + */ + @MustBeClosed + fun removeTags(params: BulkRemoveTagsParams): HttpResponseFor = + removeTags(params, RequestOptions.none()) + + /** @see removeTags */ + @MustBeClosed + fun removeTags( + params: BulkRemoveTagsParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + } +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/files/BulkServiceImpl.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/files/BulkServiceImpl.kt new file mode 100644 index 0000000..537b391 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/files/BulkServiceImpl.kt @@ -0,0 +1,192 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.blocking.files + +import com.imagekit.api.core.ClientOptions +import com.imagekit.api.core.RequestOptions +import com.imagekit.api.core.handlers.errorBodyHandler +import com.imagekit.api.core.handlers.errorHandler +import com.imagekit.api.core.handlers.jsonHandler +import com.imagekit.api.core.http.HttpMethod +import com.imagekit.api.core.http.HttpRequest +import com.imagekit.api.core.http.HttpResponse +import com.imagekit.api.core.http.HttpResponse.Handler +import com.imagekit.api.core.http.HttpResponseFor +import com.imagekit.api.core.http.json +import com.imagekit.api.core.http.parseable +import com.imagekit.api.core.prepare +import com.imagekit.api.models.files.bulk.BulkAddTagsParams +import com.imagekit.api.models.files.bulk.BulkAddTagsResponse +import com.imagekit.api.models.files.bulk.BulkDeleteParams +import com.imagekit.api.models.files.bulk.BulkDeleteResponse +import com.imagekit.api.models.files.bulk.BulkRemoveAiTagsParams +import com.imagekit.api.models.files.bulk.BulkRemoveAiTagsResponse +import com.imagekit.api.models.files.bulk.BulkRemoveTagsParams +import com.imagekit.api.models.files.bulk.BulkRemoveTagsResponse +import java.util.function.Consumer + +class BulkServiceImpl internal constructor(private val clientOptions: ClientOptions) : BulkService { + + private val withRawResponse: BulkService.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + override fun withRawResponse(): BulkService.WithRawResponse = withRawResponse + + override fun withOptions(modifier: Consumer): BulkService = + BulkServiceImpl(clientOptions.toBuilder().apply(modifier::accept).build()) + + override fun delete( + params: BulkDeleteParams, + requestOptions: RequestOptions, + ): BulkDeleteResponse = + // post /v1/files/batch/deleteByFileIds + withRawResponse().delete(params, requestOptions).parse() + + override fun addTags( + params: BulkAddTagsParams, + requestOptions: RequestOptions, + ): BulkAddTagsResponse = + // post /v1/files/addTags + withRawResponse().addTags(params, requestOptions).parse() + + override fun removeAiTags( + params: BulkRemoveAiTagsParams, + requestOptions: RequestOptions, + ): BulkRemoveAiTagsResponse = + // post /v1/files/removeAITags + withRawResponse().removeAiTags(params, requestOptions).parse() + + override fun removeTags( + params: BulkRemoveTagsParams, + requestOptions: RequestOptions, + ): BulkRemoveTagsResponse = + // post /v1/files/removeTags + withRawResponse().removeTags(params, requestOptions).parse() + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + BulkService.WithRawResponse { + + private val errorHandler: Handler = + errorHandler(errorBodyHandler(clientOptions.jsonMapper)) + + override fun withOptions( + modifier: Consumer + ): BulkService.WithRawResponse = + BulkServiceImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + private val deleteHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun delete( + params: BulkDeleteParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "files", "batch", "deleteByFileIds") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { deleteHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + + private val addTagsHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun addTags( + params: BulkAddTagsParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "files", "addTags") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { addTagsHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + + private val removeAiTagsHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun removeAiTags( + params: BulkRemoveAiTagsParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "files", "removeAITags") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { removeAiTagsHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + + private val removeTagsHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun removeTags( + params: BulkRemoveTagsParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "files", "removeTags") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { removeTagsHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/files/MetadataService.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/files/MetadataService.kt new file mode 100644 index 0000000..d873401 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/files/MetadataService.kt @@ -0,0 +1,138 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.blocking.files + +import com.google.errorprone.annotations.MustBeClosed +import com.imagekit.api.core.ClientOptions +import com.imagekit.api.core.RequestOptions +import com.imagekit.api.core.http.HttpResponseFor +import com.imagekit.api.models.files.Metadata +import com.imagekit.api.models.files.metadata.MetadataGetFromUrlParams +import com.imagekit.api.models.files.metadata.MetadataGetParams +import java.util.function.Consumer + +interface MetadataService { + + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): MetadataService + + /** + * You can programmatically get image EXIF, pHash, and other metadata for uploaded files in the + * ImageKit.io media library using this API. + * + * You can also get the metadata in upload API response by passing `metadata` in + * `responseFields` parameter. + */ + fun get(fileId: String): Metadata = get(fileId, MetadataGetParams.none()) + + /** @see get */ + fun get( + fileId: String, + params: MetadataGetParams = MetadataGetParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): Metadata = get(params.toBuilder().fileId(fileId).build(), requestOptions) + + /** @see get */ + fun get(fileId: String, params: MetadataGetParams = MetadataGetParams.none()): Metadata = + get(fileId, params, RequestOptions.none()) + + /** @see get */ + fun get( + params: MetadataGetParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): Metadata + + /** @see get */ + fun get(params: MetadataGetParams): Metadata = get(params, RequestOptions.none()) + + /** @see get */ + fun get(fileId: String, requestOptions: RequestOptions): Metadata = + get(fileId, MetadataGetParams.none(), requestOptions) + + /** + * Get image EXIF, pHash, and other metadata from ImageKit.io powered remote URL using this API. + */ + fun getFromUrl(params: MetadataGetFromUrlParams): Metadata = + getFromUrl(params, RequestOptions.none()) + + /** @see getFromUrl */ + fun getFromUrl( + params: MetadataGetFromUrlParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): Metadata + + /** A view of [MetadataService] that provides access to raw HTTP responses for each method. */ + interface WithRawResponse { + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): MetadataService.WithRawResponse + + /** + * Returns a raw HTTP response for `get /v1/files/{fileId}/metadata`, but is otherwise the + * same as [MetadataService.get]. + */ + @MustBeClosed + fun get(fileId: String): HttpResponseFor = get(fileId, MetadataGetParams.none()) + + /** @see get */ + @MustBeClosed + fun get( + fileId: String, + params: MetadataGetParams = MetadataGetParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor = + get(params.toBuilder().fileId(fileId).build(), requestOptions) + + /** @see get */ + @MustBeClosed + fun get( + fileId: String, + params: MetadataGetParams = MetadataGetParams.none(), + ): HttpResponseFor = get(fileId, params, RequestOptions.none()) + + /** @see get */ + @MustBeClosed + fun get( + params: MetadataGetParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see get */ + @MustBeClosed + fun get(params: MetadataGetParams): HttpResponseFor = + get(params, RequestOptions.none()) + + /** @see get */ + @MustBeClosed + fun get(fileId: String, requestOptions: RequestOptions): HttpResponseFor = + get(fileId, MetadataGetParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `get /v1/files/metadata`, but is otherwise the same as + * [MetadataService.getFromUrl]. + */ + @MustBeClosed + fun getFromUrl(params: MetadataGetFromUrlParams): HttpResponseFor = + getFromUrl(params, RequestOptions.none()) + + /** @see getFromUrl */ + @MustBeClosed + fun getFromUrl( + params: MetadataGetFromUrlParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + } +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/files/MetadataServiceImpl.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/files/MetadataServiceImpl.kt new file mode 100644 index 0000000..558676a --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/files/MetadataServiceImpl.kt @@ -0,0 +1,116 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.blocking.files + +import com.imagekit.api.core.ClientOptions +import com.imagekit.api.core.RequestOptions +import com.imagekit.api.core.checkRequired +import com.imagekit.api.core.handlers.errorBodyHandler +import com.imagekit.api.core.handlers.errorHandler +import com.imagekit.api.core.handlers.jsonHandler +import com.imagekit.api.core.http.HttpMethod +import com.imagekit.api.core.http.HttpRequest +import com.imagekit.api.core.http.HttpResponse +import com.imagekit.api.core.http.HttpResponse.Handler +import com.imagekit.api.core.http.HttpResponseFor +import com.imagekit.api.core.http.parseable +import com.imagekit.api.core.prepare +import com.imagekit.api.models.files.Metadata +import com.imagekit.api.models.files.metadata.MetadataGetFromUrlParams +import com.imagekit.api.models.files.metadata.MetadataGetParams +import java.util.function.Consumer +import kotlin.jvm.optionals.getOrNull + +class MetadataServiceImpl internal constructor(private val clientOptions: ClientOptions) : + MetadataService { + + private val withRawResponse: MetadataService.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + override fun withRawResponse(): MetadataService.WithRawResponse = withRawResponse + + override fun withOptions(modifier: Consumer): MetadataService = + MetadataServiceImpl(clientOptions.toBuilder().apply(modifier::accept).build()) + + override fun get(params: MetadataGetParams, requestOptions: RequestOptions): Metadata = + // get /v1/files/{fileId}/metadata + withRawResponse().get(params, requestOptions).parse() + + override fun getFromUrl( + params: MetadataGetFromUrlParams, + requestOptions: RequestOptions, + ): Metadata = + // get /v1/files/metadata + withRawResponse().getFromUrl(params, requestOptions).parse() + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + MetadataService.WithRawResponse { + + private val errorHandler: Handler = + errorHandler(errorBodyHandler(clientOptions.jsonMapper)) + + override fun withOptions( + modifier: Consumer + ): MetadataService.WithRawResponse = + MetadataServiceImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + private val getHandler: Handler = jsonHandler(clientOptions.jsonMapper) + + override fun get( + params: MetadataGetParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("fileId", params.fileId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "files", params._pathParam(0), "metadata") + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { getHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + + private val getFromUrlHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun getFromUrl( + params: MetadataGetFromUrlParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "files", "metadata") + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { getFromUrlHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/files/VersionService.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/files/VersionService.kt new file mode 100644 index 0000000..eb1195e --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/files/VersionService.kt @@ -0,0 +1,261 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.blocking.files + +import com.google.errorprone.annotations.MustBeClosed +import com.imagekit.api.core.ClientOptions +import com.imagekit.api.core.RequestOptions +import com.imagekit.api.core.http.HttpResponseFor +import com.imagekit.api.models.files.File +import com.imagekit.api.models.files.versions.VersionDeleteParams +import com.imagekit.api.models.files.versions.VersionDeleteResponse +import com.imagekit.api.models.files.versions.VersionGetParams +import com.imagekit.api.models.files.versions.VersionListParams +import com.imagekit.api.models.files.versions.VersionRestoreParams +import java.util.function.Consumer + +interface VersionService { + + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): VersionService + + /** This API returns details of all versions of a file. */ + fun list(fileId: String): List = list(fileId, VersionListParams.none()) + + /** @see list */ + fun list( + fileId: String, + params: VersionListParams = VersionListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): List = list(params.toBuilder().fileId(fileId).build(), requestOptions) + + /** @see list */ + fun list(fileId: String, params: VersionListParams = VersionListParams.none()): List = + list(fileId, params, RequestOptions.none()) + + /** @see list */ + fun list( + params: VersionListParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): List + + /** @see list */ + fun list(params: VersionListParams): List = list(params, RequestOptions.none()) + + /** @see list */ + fun list(fileId: String, requestOptions: RequestOptions): List = + list(fileId, VersionListParams.none(), requestOptions) + + /** + * This API deletes a non-current file version permanently. The API returns an empty response. + * + * Note: If you want to delete all versions of a file, use the delete file API. + */ + fun delete(versionId: String, params: VersionDeleteParams): VersionDeleteResponse = + delete(versionId, params, RequestOptions.none()) + + /** @see delete */ + fun delete( + versionId: String, + params: VersionDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): VersionDeleteResponse = + delete(params.toBuilder().versionId(versionId).build(), requestOptions) + + /** @see delete */ + fun delete(params: VersionDeleteParams): VersionDeleteResponse = + delete(params, RequestOptions.none()) + + /** @see delete */ + fun delete( + params: VersionDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): VersionDeleteResponse + + /** This API returns an object with details or attributes of a file version. */ + fun get(versionId: String, params: VersionGetParams): File = + get(versionId, params, RequestOptions.none()) + + /** @see get */ + fun get( + versionId: String, + params: VersionGetParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): File = get(params.toBuilder().versionId(versionId).build(), requestOptions) + + /** @see get */ + fun get(params: VersionGetParams): File = get(params, RequestOptions.none()) + + /** @see get */ + fun get(params: VersionGetParams, requestOptions: RequestOptions = RequestOptions.none()): File + + /** This API restores a file version as the current file version. */ + fun restore(versionId: String, params: VersionRestoreParams): File = + restore(versionId, params, RequestOptions.none()) + + /** @see restore */ + fun restore( + versionId: String, + params: VersionRestoreParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): File = restore(params.toBuilder().versionId(versionId).build(), requestOptions) + + /** @see restore */ + fun restore(params: VersionRestoreParams): File = restore(params, RequestOptions.none()) + + /** @see restore */ + fun restore( + params: VersionRestoreParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): File + + /** A view of [VersionService] that provides access to raw HTTP responses for each method. */ + interface WithRawResponse { + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): VersionService.WithRawResponse + + /** + * Returns a raw HTTP response for `get /v1/files/{fileId}/versions`, but is otherwise the + * same as [VersionService.list]. + */ + @MustBeClosed + fun list(fileId: String): HttpResponseFor> = + list(fileId, VersionListParams.none()) + + /** @see list */ + @MustBeClosed + fun list( + fileId: String, + params: VersionListParams = VersionListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor> = + list(params.toBuilder().fileId(fileId).build(), requestOptions) + + /** @see list */ + @MustBeClosed + fun list( + fileId: String, + params: VersionListParams = VersionListParams.none(), + ): HttpResponseFor> = list(fileId, params, RequestOptions.none()) + + /** @see list */ + @MustBeClosed + fun list( + params: VersionListParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor> + + /** @see list */ + @MustBeClosed + fun list(params: VersionListParams): HttpResponseFor> = + list(params, RequestOptions.none()) + + /** @see list */ + @MustBeClosed + fun list(fileId: String, requestOptions: RequestOptions): HttpResponseFor> = + list(fileId, VersionListParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `delete /v1/files/{fileId}/versions/{versionId}`, but is + * otherwise the same as [VersionService.delete]. + */ + @MustBeClosed + fun delete( + versionId: String, + params: VersionDeleteParams, + ): HttpResponseFor = delete(versionId, params, RequestOptions.none()) + + /** @see delete */ + @MustBeClosed + fun delete( + versionId: String, + params: VersionDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor = + delete(params.toBuilder().versionId(versionId).build(), requestOptions) + + /** @see delete */ + @MustBeClosed + fun delete(params: VersionDeleteParams): HttpResponseFor = + delete(params, RequestOptions.none()) + + /** @see delete */ + @MustBeClosed + fun delete( + params: VersionDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** + * Returns a raw HTTP response for `get /v1/files/{fileId}/versions/{versionId}`, but is + * otherwise the same as [VersionService.get]. + */ + @MustBeClosed + fun get(versionId: String, params: VersionGetParams): HttpResponseFor = + get(versionId, params, RequestOptions.none()) + + /** @see get */ + @MustBeClosed + fun get( + versionId: String, + params: VersionGetParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor = + get(params.toBuilder().versionId(versionId).build(), requestOptions) + + /** @see get */ + @MustBeClosed + fun get(params: VersionGetParams): HttpResponseFor = + get(params, RequestOptions.none()) + + /** @see get */ + @MustBeClosed + fun get( + params: VersionGetParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** + * Returns a raw HTTP response for `put /v1/files/{fileId}/versions/{versionId}/restore`, + * but is otherwise the same as [VersionService.restore]. + */ + @MustBeClosed + fun restore(versionId: String, params: VersionRestoreParams): HttpResponseFor = + restore(versionId, params, RequestOptions.none()) + + /** @see restore */ + @MustBeClosed + fun restore( + versionId: String, + params: VersionRestoreParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor = + restore(params.toBuilder().versionId(versionId).build(), requestOptions) + + /** @see restore */ + @MustBeClosed + fun restore(params: VersionRestoreParams): HttpResponseFor = + restore(params, RequestOptions.none()) + + /** @see restore */ + @MustBeClosed + fun restore( + params: VersionRestoreParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + } +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/files/VersionServiceImpl.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/files/VersionServiceImpl.kt new file mode 100644 index 0000000..2637882 --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/files/VersionServiceImpl.kt @@ -0,0 +1,211 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.blocking.files + +import com.imagekit.api.core.ClientOptions +import com.imagekit.api.core.RequestOptions +import com.imagekit.api.core.checkRequired +import com.imagekit.api.core.handlers.errorBodyHandler +import com.imagekit.api.core.handlers.errorHandler +import com.imagekit.api.core.handlers.jsonHandler +import com.imagekit.api.core.http.HttpMethod +import com.imagekit.api.core.http.HttpRequest +import com.imagekit.api.core.http.HttpResponse +import com.imagekit.api.core.http.HttpResponse.Handler +import com.imagekit.api.core.http.HttpResponseFor +import com.imagekit.api.core.http.json +import com.imagekit.api.core.http.parseable +import com.imagekit.api.core.prepare +import com.imagekit.api.models.files.File +import com.imagekit.api.models.files.versions.VersionDeleteParams +import com.imagekit.api.models.files.versions.VersionDeleteResponse +import com.imagekit.api.models.files.versions.VersionGetParams +import com.imagekit.api.models.files.versions.VersionListParams +import com.imagekit.api.models.files.versions.VersionRestoreParams +import java.util.function.Consumer +import kotlin.jvm.optionals.getOrNull + +class VersionServiceImpl internal constructor(private val clientOptions: ClientOptions) : + VersionService { + + private val withRawResponse: VersionService.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + override fun withRawResponse(): VersionService.WithRawResponse = withRawResponse + + override fun withOptions(modifier: Consumer): VersionService = + VersionServiceImpl(clientOptions.toBuilder().apply(modifier::accept).build()) + + override fun list(params: VersionListParams, requestOptions: RequestOptions): List = + // get /v1/files/{fileId}/versions + withRawResponse().list(params, requestOptions).parse() + + override fun delete( + params: VersionDeleteParams, + requestOptions: RequestOptions, + ): VersionDeleteResponse = + // delete /v1/files/{fileId}/versions/{versionId} + withRawResponse().delete(params, requestOptions).parse() + + override fun get(params: VersionGetParams, requestOptions: RequestOptions): File = + // get /v1/files/{fileId}/versions/{versionId} + withRawResponse().get(params, requestOptions).parse() + + override fun restore(params: VersionRestoreParams, requestOptions: RequestOptions): File = + // put /v1/files/{fileId}/versions/{versionId}/restore + withRawResponse().restore(params, requestOptions).parse() + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + VersionService.WithRawResponse { + + private val errorHandler: Handler = + errorHandler(errorBodyHandler(clientOptions.jsonMapper)) + + override fun withOptions( + modifier: Consumer + ): VersionService.WithRawResponse = + VersionServiceImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + private val listHandler: Handler> = + jsonHandler>(clientOptions.jsonMapper) + + override fun list( + params: VersionListParams, + requestOptions: RequestOptions, + ): HttpResponseFor> { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("fileId", params.fileId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "files", params._pathParam(0), "versions") + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { listHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.forEach { it.validate() } + } + } + } + } + + private val deleteHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun delete( + params: VersionDeleteParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("versionId", params.versionId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.DELETE) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments( + "v1", + "files", + params._pathParam(0), + "versions", + params._pathParam(1), + ) + .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { deleteHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + + private val getHandler: Handler = jsonHandler(clientOptions.jsonMapper) + + override fun get( + params: VersionGetParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("versionId", params.versionId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments( + "v1", + "files", + params._pathParam(0), + "versions", + params._pathParam(1), + ) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { getHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + + private val restoreHandler: Handler = jsonHandler(clientOptions.jsonMapper) + + override fun restore( + params: VersionRestoreParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("versionId", params.versionId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.PUT) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments( + "v1", + "files", + params._pathParam(0), + "versions", + params._pathParam(1), + "restore", + ) + .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { restoreHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/folders/JobService.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/folders/JobService.kt new file mode 100644 index 0000000..e40fbfb --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/folders/JobService.kt @@ -0,0 +1,104 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.blocking.folders + +import com.google.errorprone.annotations.MustBeClosed +import com.imagekit.api.core.ClientOptions +import com.imagekit.api.core.RequestOptions +import com.imagekit.api.core.http.HttpResponseFor +import com.imagekit.api.models.folders.job.JobGetParams +import com.imagekit.api.models.folders.job.JobGetResponse +import java.util.function.Consumer + +interface JobService { + + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): JobService + + /** This API returns the status of a bulk job like copy and move folder operations. */ + fun get(jobId: String): JobGetResponse = get(jobId, JobGetParams.none()) + + /** @see get */ + fun get( + jobId: String, + params: JobGetParams = JobGetParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): JobGetResponse = get(params.toBuilder().jobId(jobId).build(), requestOptions) + + /** @see get */ + fun get(jobId: String, params: JobGetParams = JobGetParams.none()): JobGetResponse = + get(jobId, params, RequestOptions.none()) + + /** @see get */ + fun get( + params: JobGetParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): JobGetResponse + + /** @see get */ + fun get(params: JobGetParams): JobGetResponse = get(params, RequestOptions.none()) + + /** @see get */ + fun get(jobId: String, requestOptions: RequestOptions): JobGetResponse = + get(jobId, JobGetParams.none(), requestOptions) + + /** A view of [JobService] that provides access to raw HTTP responses for each method. */ + interface WithRawResponse { + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): JobService.WithRawResponse + + /** + * Returns a raw HTTP response for `get /v1/bulkJobs/{jobId}`, but is otherwise the same as + * [JobService.get]. + */ + @MustBeClosed + fun get(jobId: String): HttpResponseFor = get(jobId, JobGetParams.none()) + + /** @see get */ + @MustBeClosed + fun get( + jobId: String, + params: JobGetParams = JobGetParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor = + get(params.toBuilder().jobId(jobId).build(), requestOptions) + + /** @see get */ + @MustBeClosed + fun get( + jobId: String, + params: JobGetParams = JobGetParams.none(), + ): HttpResponseFor = get(jobId, params, RequestOptions.none()) + + /** @see get */ + @MustBeClosed + fun get( + params: JobGetParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see get */ + @MustBeClosed + fun get(params: JobGetParams): HttpResponseFor = + get(params, RequestOptions.none()) + + /** @see get */ + @MustBeClosed + fun get(jobId: String, requestOptions: RequestOptions): HttpResponseFor = + get(jobId, JobGetParams.none(), requestOptions) + } +} diff --git a/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/folders/JobServiceImpl.kt b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/folders/JobServiceImpl.kt new file mode 100644 index 0000000..8be9b5a --- /dev/null +++ b/image-kit-java-core/src/main/kotlin/com/imagekit/api/services/blocking/folders/JobServiceImpl.kt @@ -0,0 +1,81 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.blocking.folders + +import com.imagekit.api.core.ClientOptions +import com.imagekit.api.core.RequestOptions +import com.imagekit.api.core.checkRequired +import com.imagekit.api.core.handlers.errorBodyHandler +import com.imagekit.api.core.handlers.errorHandler +import com.imagekit.api.core.handlers.jsonHandler +import com.imagekit.api.core.http.HttpMethod +import com.imagekit.api.core.http.HttpRequest +import com.imagekit.api.core.http.HttpResponse +import com.imagekit.api.core.http.HttpResponse.Handler +import com.imagekit.api.core.http.HttpResponseFor +import com.imagekit.api.core.http.parseable +import com.imagekit.api.core.prepare +import com.imagekit.api.models.folders.job.JobGetParams +import com.imagekit.api.models.folders.job.JobGetResponse +import java.util.function.Consumer +import kotlin.jvm.optionals.getOrNull + +class JobServiceImpl internal constructor(private val clientOptions: ClientOptions) : JobService { + + private val withRawResponse: JobService.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + override fun withRawResponse(): JobService.WithRawResponse = withRawResponse + + override fun withOptions(modifier: Consumer): JobService = + JobServiceImpl(clientOptions.toBuilder().apply(modifier::accept).build()) + + override fun get(params: JobGetParams, requestOptions: RequestOptions): JobGetResponse = + // get /v1/bulkJobs/{jobId} + withRawResponse().get(params, requestOptions).parse() + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + JobService.WithRawResponse { + + private val errorHandler: Handler = + errorHandler(errorBodyHandler(clientOptions.jsonMapper)) + + override fun withOptions( + modifier: Consumer + ): JobService.WithRawResponse = + JobServiceImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + private val getHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun get( + params: JobGetParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("jobId", params.jobId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "bulkJobs", params._pathParam(0)) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { getHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } +} diff --git a/image-kit-java-core/src/main/resources/META-INF/proguard/image-kit-java-core.pro b/image-kit-java-core/src/main/resources/META-INF/proguard/image-kit-java-core.pro new file mode 100644 index 0000000..dedf495 --- /dev/null +++ b/image-kit-java-core/src/main/resources/META-INF/proguard/image-kit-java-core.pro @@ -0,0 +1,32 @@ +# Jackson uses reflection and depends heavily on runtime attributes. +-keepattributes Exceptions,InnerClasses,Signature,Deprecated,*Annotation* + +# Jackson uses Kotlin reflection utilities, which themselves use reflection to access things. +-keep class kotlin.reflect.** { *; } +-keep class kotlin.Metadata { *; } + +# Jackson uses reflection to access enum members (e.g. via `java.lang.Class.getEnumConstants()`). +-keepclassmembers class com.fasterxml.jackson.** extends java.lang.Enum { + ; + public static **[] values(); + public static ** valueOf(java.lang.String); +} + +# Jackson uses reflection to access annotation members. +-keepclassmembers @interface com.fasterxml.jackson.annotation.** { + *; +} + +# Jackson uses reified type information to serialize and deserialize our classes (via `TypeReference`). +-keep class com.fasterxml.jackson.core.type.TypeReference { *; } +-keep class * extends com.fasterxml.jackson.core.type.TypeReference { *; } + +# Jackson uses reflection to access our class serializers and deserializers. +-keep @com.fasterxml.jackson.databind.annotation.JsonSerialize class com.imagekit.api.** { *; } +-keep @com.fasterxml.jackson.databind.annotation.JsonDeserialize class com.imagekit.api.** { *; } + +# Jackson uses reflection to serialize and deserialize our classes based on their constructors and annotated members. +-keepclassmembers class com.imagekit.api.** { + (...); + @com.fasterxml.jackson.annotation.* *; +} \ No newline at end of file diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/TestServerExtension.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/TestServerExtension.kt new file mode 100644 index 0000000..ac78240 --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/TestServerExtension.kt @@ -0,0 +1,62 @@ +package com.imagekit.api + +import java.lang.RuntimeException +import java.net.URL +import org.junit.jupiter.api.extension.BeforeAllCallback +import org.junit.jupiter.api.extension.ConditionEvaluationResult +import org.junit.jupiter.api.extension.ExecutionCondition +import org.junit.jupiter.api.extension.ExtensionContext + +class TestServerExtension : BeforeAllCallback, ExecutionCondition { + + override fun beforeAll(context: ExtensionContext?) { + try { + URL(BASE_URL).openConnection().connect() + } catch (e: Exception) { + throw RuntimeException( + """ + The test suite will not run without a mock Prism server running against your OpenAPI spec. + + You can set the environment variable `SKIP_MOCK_TESTS` to `true` to skip running any tests + that require the mock server. + + To fix: + + 1. Install Prism (requires Node 16+): + + With npm: + $ npm install -g @stoplight/prism-cli + + With yarn: + $ yarn global add @stoplight/prism-cli + + 2. Run the mock server + + To run the server, pass in the path of your OpenAPI spec to the prism command: + $ prism mock path/to/your.openapi.yml + """ + .trimIndent(), + e, + ) + } + } + + override fun evaluateExecutionCondition(context: ExtensionContext): ConditionEvaluationResult { + return if (System.getenv(SKIP_TESTS_ENV).toBoolean()) { + ConditionEvaluationResult.disabled( + "Environment variable $SKIP_TESTS_ENV is set to true" + ) + } else { + ConditionEvaluationResult.enabled( + "Environment variable $SKIP_TESTS_ENV is not set to true" + ) + } + } + + companion object { + + val BASE_URL = System.getenv("TEST_API_BASE_URL") ?: "http://localhost:4010" + + const val SKIP_TESTS_ENV: String = "SKIP_MOCK_TESTS" + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/core/ClientOptionsTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/core/ClientOptionsTest.kt new file mode 100644 index 0000000..4ce82f3 --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/core/ClientOptionsTest.kt @@ -0,0 +1,38 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.core + +import com.imagekit.api.core.http.HttpClient +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith +import org.mockito.junit.jupiter.MockitoExtension +import org.mockito.kotlin.mock +import org.mockito.kotlin.never +import org.mockito.kotlin.verify + +@ExtendWith(MockitoExtension::class) +internal class ClientOptionsTest { + + private val httpClient = mock() + + @Test + fun toBuilder_whenOriginalClientOptionsGarbageCollected_doesNotCloseOriginalClient() { + var clientOptions = + ClientOptions.builder() + .httpClient(httpClient) + .privateApiKey("My Private API Key") + .password("My Password") + .build() + verify(httpClient, never()).close() + + // Overwrite the `clientOptions` variable so that the original `ClientOptions` is GC'd. + clientOptions = clientOptions.toBuilder().build() + System.gc() + Thread.sleep(100) + + verify(httpClient, never()).close() + // This exists so that `clientOptions` is still reachable. + assertThat(clientOptions).isEqualTo(clientOptions) + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/core/ObjectMappersTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/core/ObjectMappersTest.kt new file mode 100644 index 0000000..b340cb7 --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/core/ObjectMappersTest.kt @@ -0,0 +1,102 @@ +package com.imagekit.api.core + +import com.fasterxml.jackson.annotation.JsonProperty +import com.fasterxml.jackson.databind.exc.MismatchedInputException +import com.fasterxml.jackson.module.kotlin.readValue +import java.time.LocalDateTime +import kotlin.reflect.KClass +import org.assertj.core.api.Assertions.assertThat +import org.assertj.core.api.Assertions.catchThrowable +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.assertDoesNotThrow +import org.junit.jupiter.params.ParameterizedTest +import org.junit.jupiter.params.provider.EnumSource +import org.junitpioneer.jupiter.cartesian.CartesianTest + +internal class ObjectMappersTest { + + internal class ClassWithBooleanFieldPrefixedWithIs(private val isActive: JsonField) { + + @JsonProperty("is_active") @ExcludeMissing fun _isActive() = isActive + } + + @Test + fun write_whenFieldPrefixedWithIs_keepsPrefix() { + val value = ClassWithBooleanFieldPrefixedWithIs(JsonField.of(true)) + + val json = jsonMapper().writeValueAsString(value) + + assertThat(json).isEqualTo("{\"is_active\":true}") + } + + internal class Class(@get:JsonProperty("field") @JsonProperty("field") val field: String) + + enum class ShapeTestCase(val value: Any, val kClass: KClass<*>) { + STRING("Hello World!", String::class), + BOOLEAN(true, Boolean::class), + FLOAT(3.14F, Float::class), + DOUBLE(3.14, Double::class), + INTEGER(42, Int::class), + LONG(42L, Long::class), + MAP(mapOf("property" to "value"), Map::class), + CLASS(Class("Hello World!"), Class::class), + LIST(listOf(1, 2, 3), List::class); + + companion object { + val VALID_CONVERSIONS = + listOf( + FLOAT to DOUBLE, + FLOAT to INTEGER, + FLOAT to LONG, + DOUBLE to FLOAT, + DOUBLE to INTEGER, + DOUBLE to LONG, + INTEGER to FLOAT, + INTEGER to DOUBLE, + INTEGER to LONG, + LONG to FLOAT, + LONG to DOUBLE, + LONG to INTEGER, + CLASS to MAP, + // These aren't actually valid, but coercion configs don't work for String until + // v2.14.0: https://github.com/FasterXML/jackson-databind/issues/3240 + // We currently test on v2.13.4. + BOOLEAN to STRING, + FLOAT to STRING, + DOUBLE to STRING, + INTEGER to STRING, + LONG to STRING, + ) + } + } + + @CartesianTest + fun read(@CartesianTest.Enum shape1: ShapeTestCase, @CartesianTest.Enum shape2: ShapeTestCase) { + val jsonMapper = jsonMapper() + val json = jsonMapper.writeValueAsString(shape1.value) + + val e = catchThrowable { jsonMapper.readValue(json, shape2.kClass.java) } + + if (shape1 == shape2 || shape1 to shape2 in ShapeTestCase.VALID_CONVERSIONS) { + assertThat(e).isNull() + } else { + assertThat(e).isInstanceOf(MismatchedInputException::class.java) + } + } + + enum class LenientLocalDateTimeTestCase(val string: String) { + DATE("1998-04-21"), + DATE_TIME("1998-04-21T04:00:00"), + ZONED_DATE_TIME_1("1998-04-21T04:00:00+03:00"), + ZONED_DATE_TIME_2("1998-04-21T04:00:00Z"), + } + + @ParameterizedTest + @EnumSource + fun readLocalDateTime_lenient(testCase: LenientLocalDateTimeTestCase) { + val jsonMapper = jsonMapper() + val json = jsonMapper.writeValueAsString(testCase.string) + + assertDoesNotThrow { jsonMapper().readValue(json) } + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/core/PhantomReachableTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/core/PhantomReachableTest.kt new file mode 100644 index 0000000..8e35e81 --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/core/PhantomReachableTest.kt @@ -0,0 +1,27 @@ +package com.imagekit.api.core + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class PhantomReachableTest { + + @Test + fun closeWhenPhantomReachable_whenObservedIsGarbageCollected_closesCloseable() { + var closed = false + val closeable = AutoCloseable { closed = true } + + closeWhenPhantomReachable( + // Pass an inline object for the object to observe so that it becomes immediately + // unreachable. + Any(), + closeable, + ) + + assertThat(closed).isFalse() + + System.gc() + Thread.sleep(100) + + assertThat(closed).isTrue() + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/core/UtilsTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/core/UtilsTest.kt new file mode 100644 index 0000000..1da50cf --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/core/UtilsTest.kt @@ -0,0 +1,33 @@ +package com.imagekit.api.core + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class UtilsTest { + @Test + fun contentDeepEquals() { + assertThat(42 contentEquals 42).isTrue() + assertThat(42 contentEquals "Hello World!").isFalse() + assertThat(byteArrayOf(1, 2, 3) contentEquals byteArrayOf(1, 2, 3)).isTrue() + assertThat(byteArrayOf(1, 2, 3) contentEquals byteArrayOf(1, 2, 4)).isFalse() + assertThat( + arrayOf(byteArrayOf(1, 2), byteArrayOf(3)) contentEquals + arrayOf(byteArrayOf(1, 2), byteArrayOf(3)) + ) + .isTrue() + assertThat( + arrayOf(byteArrayOf(1, 2), byteArrayOf(3)) contentEquals + arrayOf(byteArrayOf(1), byteArrayOf(2, 3)) + ) + .isFalse() + } + + @Test + fun contentToString() { + assertThat((42).contentToString()).isEqualTo("42") + assertThat("Hello World!".contentToString()).isEqualTo("Hello World!") + assertThat(byteArrayOf(1, 2, 3).contentToString()).isEqualTo("[1, 2, 3]") + assertThat(arrayOf(byteArrayOf(1, 2), byteArrayOf(3)).contentToString()) + .isEqualTo("[[1, 2], [3]]") + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/core/ValuesTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/core/ValuesTest.kt new file mode 100644 index 0000000..e044d52 --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/core/ValuesTest.kt @@ -0,0 +1,144 @@ +package com.imagekit.api.core + +import java.util.Optional +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.params.ParameterizedTest +import org.junit.jupiter.params.provider.EnumSource + +internal class ValuesTest { + companion object { + private val NON_JSON = Any() + } + + enum class TestCase( + val value: JsonField<*>, + val expectedIsMissing: Boolean = false, + val expectedIsNull: Boolean = false, + val expectedAsKnown: Optional<*> = Optional.empty(), + val expectedAsBoolean: Optional = Optional.empty(), + val expectedAsNumber: Optional = Optional.empty(), + val expectedAsString: Optional = Optional.empty(), + val expectedAsArray: Optional> = Optional.empty(), + val expectedAsObject: Optional> = Optional.empty(), + ) { + MISSING(JsonMissing.of(), expectedIsMissing = true), + NULL(JsonNull.of(), expectedIsNull = true), + KNOWN(KnownValue.of(NON_JSON), expectedAsKnown = Optional.of(NON_JSON)), + KNOWN_BOOLEAN( + KnownValue.of(true), + expectedAsKnown = Optional.of(true), + expectedAsBoolean = Optional.of(true), + ), + BOOLEAN(JsonBoolean.of(true), expectedAsBoolean = Optional.of(true)), + KNOWN_NUMBER( + KnownValue.of(42), + expectedAsKnown = Optional.of(42), + expectedAsNumber = Optional.of(42), + ), + NUMBER(JsonNumber.of(42), expectedAsNumber = Optional.of(42)), + KNOWN_STRING( + KnownValue.of("hello"), + expectedAsKnown = Optional.of("hello"), + expectedAsString = Optional.of("hello"), + ), + STRING(JsonString.of("hello"), expectedAsString = Optional.of("hello")), + KNOWN_ARRAY_NOT_ALL_JSON( + KnownValue.of(listOf("a", "b", NON_JSON)), + expectedAsKnown = Optional.of(listOf("a", "b", NON_JSON)), + ), + KNOWN_ARRAY( + KnownValue.of(listOf("a", "b", "c")), + expectedAsKnown = Optional.of(listOf("a", "b", "c")), + expectedAsArray = + Optional.of(listOf(JsonString.of("a"), JsonString.of("b"), JsonString.of("c"))), + ), + ARRAY( + JsonArray.of(listOf(JsonString.of("a"), JsonString.of("b"), JsonString.of("c"))), + expectedAsArray = + Optional.of(listOf(JsonString.of("a"), JsonString.of("b"), JsonString.of("c"))), + ), + KNOWN_OBJECT_NOT_ALL_STRING_KEYS( + KnownValue.of(mapOf("a" to "b", 42 to "c")), + expectedAsKnown = Optional.of(mapOf("a" to "b", 42 to "c")), + ), + KNOWN_OBJECT_NOT_ALL_JSON( + KnownValue.of(mapOf("a" to "b", "b" to NON_JSON)), + expectedAsKnown = Optional.of(mapOf("a" to "b", "b" to NON_JSON)), + ), + KNOWN_OBJECT( + KnownValue.of(mapOf("a" to "b", "b" to "c")), + expectedAsKnown = Optional.of(mapOf("a" to "b", "b" to "c")), + expectedAsObject = + Optional.of(mapOf("a" to JsonString.of("b"), "b" to JsonString.of("c"))), + ), + OBJECT( + JsonObject.of(mapOf("a" to JsonString.of("b"), "b" to JsonString.of("c"))), + expectedAsObject = + Optional.of(mapOf("a" to JsonString.of("b"), "b" to JsonString.of("c"))), + ), + } + + @ParameterizedTest + @EnumSource + fun isMissing(testCase: TestCase) { + val isMissing = testCase.value.isMissing() + + assertThat(isMissing).isEqualTo(testCase.expectedIsMissing) + } + + @ParameterizedTest + @EnumSource + fun isNull(testCase: TestCase) { + val isNull = testCase.value.isNull() + + assertThat(isNull).isEqualTo(testCase.expectedIsNull) + } + + @ParameterizedTest + @EnumSource + fun asKnown(testCase: TestCase) { + val known = testCase.value.asKnown() + + assertThat(known).isEqualTo(testCase.expectedAsKnown) + } + + @ParameterizedTest + @EnumSource + fun asBoolean(testCase: TestCase) { + val boolean = testCase.value.asBoolean() + + assertThat(boolean).isEqualTo(testCase.expectedAsBoolean) + } + + @ParameterizedTest + @EnumSource + fun asNumber(testCase: TestCase) { + val number = testCase.value.asNumber() + + assertThat(number).isEqualTo(testCase.expectedAsNumber) + } + + @ParameterizedTest + @EnumSource + fun asString(testCase: TestCase) { + val string = testCase.value.asString() + + assertThat(string).isEqualTo(testCase.expectedAsString) + } + + @ParameterizedTest + @EnumSource + fun asArray(testCase: TestCase) { + val array = testCase.value.asArray() + + assertThat(array).isEqualTo(testCase.expectedAsArray) + } + + @ParameterizedTest + @EnumSource + fun asObject(testCase: TestCase) { + val obj = testCase.value.asObject() + + assertThat(obj).isEqualTo(testCase.expectedAsObject) + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/core/http/AsyncStreamResponseTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/core/http/AsyncStreamResponseTest.kt new file mode 100644 index 0000000..bb36e9b --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/core/http/AsyncStreamResponseTest.kt @@ -0,0 +1,268 @@ +package com.imagekit.api.core.http + +import java.util.* +import java.util.concurrent.CompletableFuture +import java.util.concurrent.Executor +import java.util.stream.Stream +import kotlin.streams.asStream +import org.assertj.core.api.Assertions.assertThat +import org.assertj.core.api.Assertions.catchThrowable +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.assertDoesNotThrow +import org.junit.jupiter.api.extension.ExtendWith +import org.mockito.junit.jupiter.MockitoExtension +import org.mockito.kotlin.* + +@ExtendWith(MockitoExtension::class) +internal class AsyncStreamResponseTest { + + companion object { + private val ERROR = RuntimeException("ERROR!") + } + + private val streamResponse = + spy> { + doReturn(Stream.of("chunk1", "chunk2", "chunk3")).whenever(it).stream() + } + private val erroringStreamResponse = + spy> { + doReturn( + sequence { + yield("chunk1") + yield("chunk2") + throw ERROR + } + .asStream() + ) + .whenever(it) + .stream() + } + private val executor = + spy { + doAnswer { invocation -> invocation.getArgument(0).run() } + .whenever(it) + .execute(any()) + } + private val handler = mock>() + + @Test + fun subscribe_whenAlreadySubscribed_throws() { + val asyncStreamResponse = CompletableFuture>().toAsync(executor) + asyncStreamResponse.subscribe {} + + val throwable = catchThrowable { asyncStreamResponse.subscribe {} } + + assertThat(throwable).isInstanceOf(IllegalStateException::class.java) + assertThat(throwable).hasMessage("Cannot subscribe more than once") + verify(executor, never()).execute(any()) + } + + @Test + fun subscribe_whenClosed_throws() { + val asyncStreamResponse = CompletableFuture>().toAsync(executor) + asyncStreamResponse.close() + + val throwable = catchThrowable { asyncStreamResponse.subscribe {} } + + assertThat(throwable).isInstanceOf(IllegalStateException::class.java) + assertThat(throwable).hasMessage("Cannot subscribe after the response is closed") + verify(executor, never()).execute(any()) + } + + @Test + fun subscribe_whenFutureCompletesAfterClose_doesNothing() { + val future = CompletableFuture>() + val asyncStreamResponse = future.toAsync(executor) + asyncStreamResponse.subscribe(handler) + asyncStreamResponse.close() + + future.complete(streamResponse) + + verify(handler, never()).onNext(any()) + verify(handler, never()).onComplete(any()) + verify(executor, times(1)).execute(any()) + } + + @Test + fun subscribe_whenFutureErrors_callsOnComplete() { + val future = CompletableFuture>() + val asyncStreamResponse = future.toAsync(executor) + asyncStreamResponse.subscribe(handler) + + future.completeExceptionally(ERROR) + + verify(handler, never()).onNext(any()) + verify(handler, times(1)).onComplete(Optional.of(ERROR)) + verify(executor, times(1)).execute(any()) + } + + @Test + fun subscribe_whenFutureCompletes_runsHandler() { + val future = CompletableFuture>() + val asyncStreamResponse = future.toAsync(executor) + asyncStreamResponse.subscribe(handler) + + future.complete(streamResponse) + + inOrder(handler, streamResponse) { + verify(handler, times(1)).onNext("chunk1") + verify(handler, times(1)).onNext("chunk2") + verify(handler, times(1)).onNext("chunk3") + verify(handler, times(1)).onComplete(Optional.empty()) + verify(streamResponse, times(1)).close() + } + verify(executor, times(1)).execute(any()) + } + + @Test + fun subscribe_whenStreamErrors_callsOnCompleteEarly() { + val future = CompletableFuture>() + val asyncStreamResponse = future.toAsync(executor) + asyncStreamResponse.subscribe(handler) + + future.complete(erroringStreamResponse) + + inOrder(handler, erroringStreamResponse) { + verify(handler, times(1)).onNext("chunk1") + verify(handler, times(1)).onNext("chunk2") + verify(handler, times(1)).onComplete(Optional.of(ERROR)) + verify(erroringStreamResponse, times(1)).close() + } + verify(executor, times(1)).execute(any()) + } + + @Test + fun onCompleteFuture_whenStreamResponseFutureNotCompleted_onCompleteFutureNotCompleted() { + val future = CompletableFuture>() + val asyncStreamResponse = future.toAsync(executor) + + val onCompletableFuture = asyncStreamResponse.onCompleteFuture() + + assertThat(onCompletableFuture).isNotCompleted + } + + @Test + fun onCompleteFuture_whenStreamResponseFutureErrors_onCompleteFutureCompletedExceptionally() { + val future = CompletableFuture>() + val asyncStreamResponse = future.toAsync(executor) + future.completeExceptionally(ERROR) + + val onCompletableFuture = asyncStreamResponse.onCompleteFuture() + + assertThat(onCompletableFuture).isCompletedExceptionally + } + + @Test + fun onCompleteFuture_whenStreamResponseFutureCompletedButStillStreaming_onCompleteFutureNotCompleted() { + val future = CompletableFuture>() + val asyncStreamResponse = future.toAsync(executor) + future.complete(streamResponse) + + val onCompletableFuture = asyncStreamResponse.onCompleteFuture() + + assertThat(onCompletableFuture).isNotCompleted + } + + @Test + fun onCompleteFuture_whenStreamResponseFutureCompletedAndStreamErrors_onCompleteFutureCompletedExceptionally() { + val future = CompletableFuture>() + val asyncStreamResponse = future.toAsync(executor) + asyncStreamResponse.subscribe(handler) + future.complete(erroringStreamResponse) + + val onCompletableFuture = asyncStreamResponse.onCompleteFuture() + + assertThat(onCompletableFuture).isCompletedExceptionally + } + + @Test + fun onCompleteFuture_whenStreamResponseFutureCompletedAndStreamCompleted_onCompleteFutureCompleted() { + val future = CompletableFuture>() + val asyncStreamResponse = future.toAsync(executor) + asyncStreamResponse.subscribe(handler) + future.complete(streamResponse) + + val onCompletableFuture = asyncStreamResponse.onCompleteFuture() + + assertThat(onCompletableFuture).isCompleted + } + + @Test + fun onCompleteFuture_whenHandlerOnCompleteWithoutThrowableThrows_onCompleteFutureCompleted() { + val future = CompletableFuture>() + val asyncStreamResponse = future.toAsync(executor) + asyncStreamResponse.subscribe( + object : AsyncStreamResponse.Handler { + override fun onNext(value: String) {} + + override fun onComplete(error: Optional) = throw ERROR + } + ) + future.complete(streamResponse) + + val onCompletableFuture = asyncStreamResponse.onCompleteFuture() + + assertThat(onCompletableFuture).isCompleted + } + + @Test + fun onCompleteFuture_whenHandlerOnCompleteWithThrowableThrows_onCompleteFutureCompletedExceptionally() { + val future = CompletableFuture>() + val asyncStreamResponse = future.toAsync(executor) + asyncStreamResponse.subscribe( + object : AsyncStreamResponse.Handler { + override fun onNext(value: String) {} + + override fun onComplete(error: Optional) = throw ERROR + } + ) + future.complete(erroringStreamResponse) + + val onCompletableFuture = asyncStreamResponse.onCompleteFuture() + + assertThat(onCompletableFuture).isCompletedExceptionally + } + + @Test + fun onCompleteFuture_whenClosed_onCompleteFutureCompleted() { + val future = CompletableFuture>() + val asyncStreamResponse = future.toAsync(executor) + asyncStreamResponse.close() + + val onCompletableFuture = asyncStreamResponse.onCompleteFuture() + + assertThat(onCompletableFuture).isCompleted + } + + @Test + fun close_whenNotClosed_closesStreamResponse() { + val future = CompletableFuture>() + val asyncStreamResponse = future.toAsync(executor) + + asyncStreamResponse.close() + future.complete(streamResponse) + + verify(streamResponse, times(1)).close() + } + + @Test + fun close_whenAlreadyClosed_doesNothing() { + val future = CompletableFuture>() + val asyncStreamResponse = future.toAsync(executor) + asyncStreamResponse.close() + future.complete(streamResponse) + + asyncStreamResponse.close() + + verify(streamResponse, times(1)).close() + } + + @Test + fun close_whenFutureErrors_doesNothing() { + val future = CompletableFuture>() + val asyncStreamResponse = future.toAsync(executor) + asyncStreamResponse.close() + + assertDoesNotThrow { future.completeExceptionally(ERROR) } + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/core/http/HeadersTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/core/http/HeadersTest.kt new file mode 100644 index 0000000..af17ead --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/core/http/HeadersTest.kt @@ -0,0 +1,242 @@ +package com.imagekit.api.core.http + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.params.ParameterizedTest +import org.junit.jupiter.params.provider.EnumSource + +internal class HeadersTest { + + enum class TestCase( + val headers: Headers, + val expectedMap: Map>, + val expectedSize: Int, + ) { + EMPTY(Headers.builder().build(), expectedMap = mapOf(), expectedSize = 0), + PUT_ONE( + Headers.builder().put("name", "value").build(), + expectedMap = mapOf("name" to listOf("value")), + expectedSize = 1, + ), + PUT_MULTIPLE( + Headers.builder().put("name", listOf("value1", "value2")).build(), + expectedMap = mapOf("name" to listOf("value1", "value2")), + expectedSize = 2, + ), + MULTIPLE_PUT( + Headers.builder().put("name1", "value").put("name2", "value").build(), + expectedMap = mapOf("name1" to listOf("value"), "name2" to listOf("value")), + expectedSize = 2, + ), + MULTIPLE_PUT_SAME_NAME( + Headers.builder().put("name", "value1").put("name", "value2").build(), + expectedMap = mapOf("name" to listOf("value1", "value2")), + expectedSize = 2, + ), + MULTIPLE_PUT_MULTIPLE( + Headers.builder() + .put("name", listOf("value1", "value2")) + .put("name", listOf("value1", "value2")) + .build(), + expectedMap = mapOf("name" to listOf("value1", "value2", "value1", "value2")), + expectedSize = 4, + ), + PUT_CASE_INSENSITIVE( + Headers.builder() + .put("name", "value1") + .put("NAME", "value2") + .put("nAmE", "value3") + .build(), + expectedMap = mapOf("name" to listOf("value1", "value2", "value3")), + expectedSize = 3, + ), + PUT_ALL_MAP( + Headers.builder() + .putAll( + mapOf( + "name1" to listOf("value1", "value2"), + "name2" to listOf("value1", "value2"), + ) + ) + .build(), + expectedMap = + mapOf("name1" to listOf("value1", "value2"), "name2" to listOf("value1", "value2")), + expectedSize = 4, + ), + PUT_ALL_HEADERS( + Headers.builder().putAll(Headers.builder().put("name", "value").build()).build(), + expectedMap = mapOf("name" to listOf("value")), + expectedSize = 1, + ), + PUT_ALL_CASE_INSENSITIVE( + Headers.builder() + .putAll( + mapOf( + "name" to listOf("value1"), + "NAME" to listOf("value2"), + "nAmE" to listOf("value3"), + ) + ) + .build(), + expectedMap = mapOf("name" to listOf("value1", "value2", "value3")), + expectedSize = 3, + ), + REMOVE_ABSENT( + Headers.builder().remove("name").build(), + expectedMap = mapOf(), + expectedSize = 0, + ), + REMOVE_PRESENT_ONE( + Headers.builder().put("name", "value").remove("name").build(), + expectedMap = mapOf(), + expectedSize = 0, + ), + REMOVE_PRESENT_MULTIPLE( + Headers.builder().put("name", listOf("value1", "value2")).remove("name").build(), + expectedMap = mapOf(), + expectedSize = 0, + ), + REMOVE_CASE_INSENSITIVE( + Headers.builder().put("name", listOf("value1", "value2")).remove("NAME").build(), + expectedMap = mapOf(), + expectedSize = 0, + ), + REMOVE_ALL( + Headers.builder() + .put("name1", "value") + .put("name3", "value") + .removeAll(setOf("name1", "name2", "name3")) + .build(), + expectedMap = mapOf(), + expectedSize = 0, + ), + REMOVE_ALL_CASE_INSENSITIVE( + Headers.builder() + .put("name1", "value") + .put("name3", "value") + .removeAll(setOf("NAME1", "nAmE3")) + .build(), + expectedMap = mapOf(), + expectedSize = 0, + ), + CLEAR( + Headers.builder().put("name1", "value").put("name2", "value").clear().build(), + expectedMap = mapOf(), + expectedSize = 0, + ), + REPLACE_ONE_ABSENT( + Headers.builder().replace("name", "value").build(), + expectedMap = mapOf("name" to listOf("value")), + expectedSize = 1, + ), + REPLACE_ONE_PRESENT_ONE( + Headers.builder().put("name", "value1").replace("name", "value2").build(), + expectedMap = mapOf("name" to listOf("value2")), + expectedSize = 1, + ), + REPLACE_ONE_PRESENT_MULTIPLE( + Headers.builder() + .put("name", listOf("value1", "value2")) + .replace("name", "value3") + .build(), + expectedMap = mapOf("name" to listOf("value3")), + expectedSize = 1, + ), + REPLACE_MULTIPLE_ABSENT( + Headers.builder().replace("name", listOf("value1", "value2")).build(), + expectedMap = mapOf("name" to listOf("value1", "value2")), + expectedSize = 2, + ), + REPLACE_MULTIPLE_PRESENT_ONE( + Headers.builder() + .put("name", "value1") + .replace("name", listOf("value2", "value3")) + .build(), + expectedMap = mapOf("name" to listOf("value2", "value3")), + expectedSize = 2, + ), + REPLACE_MULTIPLE_PRESENT_MULTIPLE( + Headers.builder() + .put("name", listOf("value1", "value2")) + .replace("name", listOf("value3", "value4")) + .build(), + expectedMap = mapOf("name" to listOf("value3", "value4")), + expectedSize = 2, + ), + REPLACE_CASE_INSENSITIVE( + Headers.builder() + .put("name", "value1") + .replace("NAME", listOf("value2", "value3")) + .build(), + expectedMap = mapOf("NAME" to listOf("value2", "value3")), + expectedSize = 2, + ), + REPLACE_ALL_MAP( + Headers.builder() + .put("name1", "value1") + .put("name2", "value1") + .put("name3", "value1") + .replaceAll(mapOf("name1" to listOf("value2"), "name3" to listOf("value2"))) + .build(), + expectedMap = + mapOf( + "name1" to listOf("value2"), + "name2" to listOf("value1"), + "name3" to listOf("value2"), + ), + expectedSize = 3, + ), + REPLACE_ALL_HEADERS( + Headers.builder() + .put("name1", "value1") + .put("name2", "value1") + .put("name3", "value1") + .replaceAll(Headers.builder().put("name1", "value2").put("name3", "value2").build()) + .build(), + expectedMap = + mapOf( + "name1" to listOf("value2"), + "name2" to listOf("value1"), + "name3" to listOf("value2"), + ), + expectedSize = 3, + ), + REPLACE_ALL_CASE_INSENSITIVE( + Headers.builder() + .put("name1", "value1") + .put("name2", "value1") + .replaceAll(mapOf("NAME1" to listOf("value2"), "nAmE2" to listOf("value2"))) + .build(), + expectedMap = mapOf("NAME1" to listOf("value2"), "nAmE2" to listOf("value2")), + expectedSize = 2, + ), + } + + @ParameterizedTest + @EnumSource + fun namesAndValues(testCase: TestCase) { + val map = mutableMapOf>() + val headers = testCase.headers + headers.names().forEach { name -> map[name] = headers.values(name) } + + assertThat(map).isEqualTo(testCase.expectedMap) + } + + @ParameterizedTest + @EnumSource + fun caseInsensitiveNames(testCase: TestCase) { + val headers = testCase.headers + + for (name in headers.names()) { + assertThat(headers.values(name)).isEqualTo(headers.values(name.lowercase())) + assertThat(headers.values(name)).isEqualTo(headers.values(name.uppercase())) + } + } + + @ParameterizedTest + @EnumSource + fun size(testCase: TestCase) { + val size = testCase.headers.size + + assertThat(size).isEqualTo(testCase.expectedSize) + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/core/http/QueryParamsTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/core/http/QueryParamsTest.kt new file mode 100644 index 0000000..8774891 --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/core/http/QueryParamsTest.kt @@ -0,0 +1,180 @@ +package com.imagekit.api.core.http + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.params.ParameterizedTest +import org.junit.jupiter.params.provider.EnumSource + +internal class QueryParamsTest { + + enum class TestCase( + val queryParams: QueryParams, + val expectedMap: Map>, + val expectedSize: Int, + ) { + EMPTY(QueryParams.builder().build(), expectedMap = mapOf(), expectedSize = 0), + PUT_ONE( + QueryParams.builder().put("key", "value").build(), + expectedMap = mapOf("key" to listOf("value")), + expectedSize = 1, + ), + PUT_MULTIPLE( + QueryParams.builder().put("key", listOf("value1", "value2")).build(), + expectedMap = mapOf("key" to listOf("value1", "value2")), + expectedSize = 2, + ), + MULTIPLE_PUT( + QueryParams.builder().put("key1", "value").put("key2", "value").build(), + expectedMap = mapOf("key1" to listOf("value"), "key2" to listOf("value")), + expectedSize = 2, + ), + MULTIPLE_PUT_SAME_NAME( + QueryParams.builder().put("key", "value1").put("key", "value2").build(), + expectedMap = mapOf("key" to listOf("value1", "value2")), + expectedSize = 2, + ), + MULTIPLE_PUT_MULTIPLE( + QueryParams.builder() + .put("key", listOf("value1", "value2")) + .put("key", listOf("value1", "value2")) + .build(), + expectedMap = mapOf("key" to listOf("value1", "value2", "value1", "value2")), + expectedSize = 4, + ), + PUT_ALL_MAP( + QueryParams.builder() + .putAll( + mapOf( + "key1" to listOf("value1", "value2"), + "key2" to listOf("value1", "value2"), + ) + ) + .build(), + expectedMap = + mapOf("key1" to listOf("value1", "value2"), "key2" to listOf("value1", "value2")), + expectedSize = 4, + ), + PUT_ALL_HEADERS( + QueryParams.builder().putAll(QueryParams.builder().put("key", "value").build()).build(), + expectedMap = mapOf("key" to listOf("value")), + expectedSize = 1, + ), + REMOVE_ABSENT( + QueryParams.builder().remove("key").build(), + expectedMap = mapOf(), + expectedSize = 0, + ), + REMOVE_PRESENT_ONE( + QueryParams.builder().put("key", "value").remove("key").build(), + expectedMap = mapOf(), + expectedSize = 0, + ), + REMOVE_PRESENT_MULTIPLE( + QueryParams.builder().put("key", listOf("value1", "value2")).remove("key").build(), + expectedMap = mapOf(), + expectedSize = 0, + ), + REMOVE_ALL( + QueryParams.builder() + .put("key1", "value") + .put("key3", "value") + .removeAll(setOf("key1", "key2", "key3")) + .build(), + expectedMap = mapOf(), + expectedSize = 0, + ), + CLEAR( + QueryParams.builder().put("key1", "value").put("key2", "value").clear().build(), + expectedMap = mapOf(), + expectedSize = 0, + ), + REPLACE_ONE_ABSENT( + QueryParams.builder().replace("key", "value").build(), + expectedMap = mapOf("key" to listOf("value")), + expectedSize = 1, + ), + REPLACE_ONE_PRESENT_ONE( + QueryParams.builder().put("key", "value1").replace("key", "value2").build(), + expectedMap = mapOf("key" to listOf("value2")), + expectedSize = 1, + ), + REPLACE_ONE_PRESENT_MULTIPLE( + QueryParams.builder() + .put("key", listOf("value1", "value2")) + .replace("key", "value3") + .build(), + expectedMap = mapOf("key" to listOf("value3")), + expectedSize = 1, + ), + REPLACE_MULTIPLE_ABSENT( + QueryParams.builder().replace("key", listOf("value1", "value2")).build(), + expectedMap = mapOf("key" to listOf("value1", "value2")), + expectedSize = 2, + ), + REPLACE_MULTIPLE_PRESENT_ONE( + QueryParams.builder() + .put("key", "value1") + .replace("key", listOf("value2", "value3")) + .build(), + expectedMap = mapOf("key" to listOf("value2", "value3")), + expectedSize = 2, + ), + REPLACE_MULTIPLE_PRESENT_MULTIPLE( + QueryParams.builder() + .put("key", listOf("value1", "value2")) + .replace("key", listOf("value3", "value4")) + .build(), + expectedMap = mapOf("key" to listOf("value3", "value4")), + expectedSize = 2, + ), + REPLACE_ALL_MAP( + QueryParams.builder() + .put("key1", "value1") + .put("key2", "value1") + .put("key3", "value1") + .replaceAll(mapOf("key1" to listOf("value2"), "key3" to listOf("value2"))) + .build(), + expectedMap = + mapOf( + "key1" to listOf("value2"), + "key2" to listOf("value1"), + "key3" to listOf("value2"), + ), + expectedSize = 3, + ), + REPLACE_ALL_HEADERS( + QueryParams.builder() + .put("key1", "value1") + .put("key2", "value1") + .put("key3", "value1") + .replaceAll( + QueryParams.builder().put("key1", "value2").put("key3", "value2").build() + ) + .build(), + expectedMap = + mapOf( + "key1" to listOf("value2"), + "key2" to listOf("value1"), + "key3" to listOf("value2"), + ), + expectedSize = 3, + ), + } + + @ParameterizedTest + @EnumSource + fun keysAndValues(testCase: TestCase) { + val map = mutableMapOf>() + val queryParams = testCase.queryParams + queryParams.keys().forEach { key -> map[key] = queryParams.values(key) } + + assertThat(map).isEqualTo(testCase.expectedMap) + } + + @ParameterizedTest + @EnumSource + fun size(testCase: TestCase) { + val size = testCase.queryParams.size + + assertThat(size).isEqualTo(testCase.expectedSize) + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/core/http/RetryingHttpClientTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/core/http/RetryingHttpClientTest.kt new file mode 100644 index 0000000..732cc28 --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/core/http/RetryingHttpClientTest.kt @@ -0,0 +1,351 @@ +package com.imagekit.api.core.http + +import com.github.tomakehurst.wiremock.client.WireMock.* +import com.github.tomakehurst.wiremock.junit5.WireMockRuntimeInfo +import com.github.tomakehurst.wiremock.junit5.WireMockTest +import com.github.tomakehurst.wiremock.stubbing.Scenario +import com.imagekit.api.client.okhttp.OkHttpClient +import com.imagekit.api.core.RequestOptions +import com.imagekit.api.errors.ImageKitRetryableException +import java.io.InputStream +import java.time.Duration +import java.util.concurrent.CompletableFuture +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.parallel.ResourceLock +import org.junit.jupiter.params.ParameterizedTest +import org.junit.jupiter.params.provider.ValueSource + +@WireMockTest +@ResourceLock("https://github.com/wiremock/wiremock/issues/169") +internal class RetryingHttpClientTest { + + private var openResponseCount = 0 + private lateinit var baseUrl: String + private lateinit var httpClient: HttpClient + + @BeforeEach + fun beforeEach(wmRuntimeInfo: WireMockRuntimeInfo) { + baseUrl = wmRuntimeInfo.httpBaseUrl + val okHttpClient = OkHttpClient.builder().build() + httpClient = + object : HttpClient { + + override fun execute( + request: HttpRequest, + requestOptions: RequestOptions, + ): HttpResponse = trackClose(okHttpClient.execute(request, requestOptions)) + + override fun executeAsync( + request: HttpRequest, + requestOptions: RequestOptions, + ): CompletableFuture = + okHttpClient.executeAsync(request, requestOptions).thenApply { trackClose(it) } + + override fun close() = okHttpClient.close() + + private fun trackClose(response: HttpResponse): HttpResponse { + openResponseCount++ + return object : HttpResponse { + + private var isClosed = false + + override fun statusCode(): Int = response.statusCode() + + override fun headers(): Headers = response.headers() + + override fun body(): InputStream = response.body() + + override fun close() { + response.close() + if (isClosed) { + return + } + openResponseCount-- + isClosed = true + } + } + } + } + resetAllScenarios() + } + + @ParameterizedTest + @ValueSource(booleans = [false, true]) + fun execute(async: Boolean) { + stubFor(post(urlPathEqualTo("/something")).willReturn(ok())) + val retryingClient = retryingHttpClientBuilder().build() + + val response = + retryingClient.execute( + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(baseUrl) + .addPathSegment("something") + .build(), + async, + ) + + assertThat(response.statusCode()).isEqualTo(200) + verify(1, postRequestedFor(urlPathEqualTo("/something"))) + assertNoResponseLeaks() + } + + @ParameterizedTest + @ValueSource(booleans = [false, true]) + fun execute_withIdempotencyHeader(async: Boolean) { + stubFor( + post(urlPathEqualTo("/something")) + .withHeader("X-Some-Header", matching("stainless-java-retry-.+")) + .willReturn(ok()) + ) + val retryingClient = + retryingHttpClientBuilder().maxRetries(2).idempotencyHeader("X-Some-Header").build() + + val response = + retryingClient.execute( + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(baseUrl) + .addPathSegment("something") + .build(), + async, + ) + + assertThat(response.statusCode()).isEqualTo(200) + verify(1, postRequestedFor(urlPathEqualTo("/something"))) + assertNoResponseLeaks() + } + + @ParameterizedTest + @ValueSource(booleans = [false, true]) + fun execute_withRetryAfterHeader(async: Boolean) { + stubFor( + post(urlPathEqualTo("/something")) + // First we fail with a retry after header given as a date + .inScenario("foo") + .whenScenarioStateIs(Scenario.STARTED) + .willReturn( + serviceUnavailable().withHeader("Retry-After", "Wed, 21 Oct 2015 07:28:00 GMT") + ) + .willSetStateTo("RETRY_AFTER_DATE") + ) + stubFor( + post(urlPathEqualTo("/something")) + // Then we fail with a retry after header given as a delay + .inScenario("foo") + .whenScenarioStateIs("RETRY_AFTER_DATE") + .willReturn(serviceUnavailable().withHeader("Retry-After", "1.234")) + .willSetStateTo("RETRY_AFTER_DELAY") + ) + stubFor( + post(urlPathEqualTo("/something")) + // Then we return a success + .inScenario("foo") + .whenScenarioStateIs("RETRY_AFTER_DELAY") + .willReturn(ok()) + .willSetStateTo("COMPLETED") + ) + val retryingClient = retryingHttpClientBuilder().maxRetries(2).build() + + val response = + retryingClient.execute( + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(baseUrl) + .addPathSegment("something") + .build(), + async, + ) + + assertThat(response.statusCode()).isEqualTo(200) + verify( + 1, + postRequestedFor(urlPathEqualTo("/something")) + .withHeader("x-stainless-retry-count", equalTo("0")), + ) + verify( + 1, + postRequestedFor(urlPathEqualTo("/something")) + .withHeader("x-stainless-retry-count", equalTo("1")), + ) + verify( + 1, + postRequestedFor(urlPathEqualTo("/something")) + .withHeader("x-stainless-retry-count", equalTo("2")), + ) + assertNoResponseLeaks() + } + + @ParameterizedTest + @ValueSource(booleans = [false, true]) + fun execute_withOverwrittenRetryCountHeader(async: Boolean) { + stubFor( + post(urlPathEqualTo("/something")) + .inScenario("foo") // first we fail with a retry after header given as a date + .whenScenarioStateIs(Scenario.STARTED) + .willReturn( + serviceUnavailable().withHeader("Retry-After", "Wed, 21 Oct 2015 07:28:00 GMT") + ) + .willSetStateTo("RETRY_AFTER_DATE") + ) + stubFor( + post(urlPathEqualTo("/something")) + .inScenario("foo") // then we return a success + .whenScenarioStateIs("RETRY_AFTER_DATE") + .willReturn(ok()) + .willSetStateTo("COMPLETED") + ) + val retryingClient = retryingHttpClientBuilder().maxRetries(2).build() + + val response = + retryingClient.execute( + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(baseUrl) + .addPathSegment("something") + .putHeader("x-stainless-retry-count", "42") + .build(), + async, + ) + + assertThat(response.statusCode()).isEqualTo(200) + verify( + 2, + postRequestedFor(urlPathEqualTo("/something")) + .withHeader("x-stainless-retry-count", equalTo("42")), + ) + assertNoResponseLeaks() + } + + @ParameterizedTest + @ValueSource(booleans = [false, true]) + fun execute_withRetryAfterMsHeader(async: Boolean) { + stubFor( + post(urlPathEqualTo("/something")) + .inScenario("foo") + .whenScenarioStateIs(Scenario.STARTED) + .willReturn(serviceUnavailable().withHeader("Retry-After-Ms", "10")) + .willSetStateTo("RETRY_AFTER_DELAY") + ) + stubFor( + post(urlPathEqualTo("/something")) + .inScenario("foo") // then we return a success + .whenScenarioStateIs("RETRY_AFTER_DELAY") + .willReturn(ok()) + .willSetStateTo("COMPLETED") + ) + val retryingClient = retryingHttpClientBuilder().maxRetries(1).build() + + val response = + retryingClient.execute( + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(baseUrl) + .addPathSegment("something") + .build(), + async, + ) + + assertThat(response.statusCode()).isEqualTo(200) + verify(2, postRequestedFor(urlPathEqualTo("/something"))) + assertNoResponseLeaks() + } + + @ParameterizedTest + @ValueSource(booleans = [false, true]) + fun execute_withRetryableException(async: Boolean) { + stubFor(post(urlPathEqualTo("/something")).willReturn(ok())) + + var callCount = 0 + val failingHttpClient = + object : HttpClient { + override fun execute( + request: HttpRequest, + requestOptions: RequestOptions, + ): HttpResponse { + callCount++ + if (callCount == 1) { + throw ImageKitRetryableException("Simulated retryable failure") + } + return httpClient.execute(request, requestOptions) + } + + override fun executeAsync( + request: HttpRequest, + requestOptions: RequestOptions, + ): CompletableFuture { + callCount++ + if (callCount == 1) { + val future = CompletableFuture() + future.completeExceptionally( + ImageKitRetryableException("Simulated retryable failure") + ) + return future + } + return httpClient.executeAsync(request, requestOptions) + } + + override fun close() = httpClient.close() + } + + val retryingClient = + RetryingHttpClient.builder() + .httpClient(failingHttpClient) + .maxRetries(2) + .sleeper( + object : RetryingHttpClient.Sleeper { + + override fun sleep(duration: Duration) {} + + override fun sleepAsync(duration: Duration): CompletableFuture = + CompletableFuture.completedFuture(null) + } + ) + .build() + + val response = + retryingClient.execute( + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(baseUrl) + .addPathSegment("something") + .build(), + async, + ) + + assertThat(response.statusCode()).isEqualTo(200) + verify( + 1, + postRequestedFor(urlPathEqualTo("/something")) + .withHeader("x-stainless-retry-count", equalTo("1")), + ) + verify( + 0, + postRequestedFor(urlPathEqualTo("/something")) + .withHeader("x-stainless-retry-count", equalTo("0")), + ) + assertNoResponseLeaks() + } + + private fun retryingHttpClientBuilder() = + RetryingHttpClient.builder() + .httpClient(httpClient) + // Use a no-op `Sleeper` to make the test fast. + .sleeper( + object : RetryingHttpClient.Sleeper { + + override fun sleep(duration: Duration) {} + + override fun sleepAsync(duration: Duration): CompletableFuture = + CompletableFuture.completedFuture(null) + } + ) + + private fun HttpClient.execute(request: HttpRequest, async: Boolean): HttpResponse = + if (async) executeAsync(request).get() else execute(request) + + // When retrying, all failed responses should be closed. Only the final returned response should + // be open. + private fun assertNoResponseLeaks() = assertThat(openResponseCount).isEqualTo(1) +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/BaseOverlayTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/BaseOverlayTest.kt new file mode 100644 index 0000000..1dab2e0 --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/BaseOverlayTest.kt @@ -0,0 +1,57 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models + +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.imagekit.api.core.jsonMapper +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class BaseOverlayTest { + + @Test + fun create() { + val baseOverlay = + BaseOverlay.builder() + .position( + OverlayPosition.builder() + .focus(OverlayPosition.Focus.CENTER) + .x(0.0) + .y(0.0) + .build() + ) + .timing(OverlayTiming.builder().duration(0.0).end(0.0).start(0.0).build()) + .build() + + assertThat(baseOverlay.position()) + .contains( + OverlayPosition.builder().focus(OverlayPosition.Focus.CENTER).x(0.0).y(0.0).build() + ) + assertThat(baseOverlay.timing()) + .contains(OverlayTiming.builder().duration(0.0).end(0.0).start(0.0).build()) + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val baseOverlay = + BaseOverlay.builder() + .position( + OverlayPosition.builder() + .focus(OverlayPosition.Focus.CENTER) + .x(0.0) + .y(0.0) + .build() + ) + .timing(OverlayTiming.builder().duration(0.0).end(0.0).start(0.0).build()) + .build() + + val roundtrippedBaseOverlay = + jsonMapper.readValue( + jsonMapper.writeValueAsString(baseOverlay), + jacksonTypeRef(), + ) + + assertThat(roundtrippedBaseOverlay).isEqualTo(baseOverlay) + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/ImageOverlayTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/ImageOverlayTest.kt new file mode 100644 index 0000000..934ff3f --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/ImageOverlayTest.kt @@ -0,0 +1,67 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models + +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.imagekit.api.core.jsonMapper +import kotlin.jvm.optionals.getOrNull +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class ImageOverlayTest { + + @Test + fun create() { + val imageOverlay = + ImageOverlay.builder() + .position( + OverlayPosition.builder() + .focus(OverlayPosition.Focus.CENTER) + .x(0.0) + .y(0.0) + .build() + ) + .timing(OverlayTiming.builder().duration(0.0).end(0.0).start(0.0).build()) + .input("input") + .encoding(ImageOverlay.Encoding.AUTO) + .transformation(listOf()) + .build() + + assertThat(imageOverlay.position()) + .contains( + OverlayPosition.builder().focus(OverlayPosition.Focus.CENTER).x(0.0).y(0.0).build() + ) + assertThat(imageOverlay.timing()) + .contains(OverlayTiming.builder().duration(0.0).end(0.0).start(0.0).build()) + assertThat(imageOverlay.input()).isEqualTo("input") + assertThat(imageOverlay.encoding()).contains(ImageOverlay.Encoding.AUTO) + assertThat(imageOverlay.transformation().getOrNull()).containsExactly() + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val imageOverlay = + ImageOverlay.builder() + .position( + OverlayPosition.builder() + .focus(OverlayPosition.Focus.CENTER) + .x(0.0) + .y(0.0) + .build() + ) + .timing(OverlayTiming.builder().duration(0.0).end(0.0).start(0.0).build()) + .input("input") + .encoding(ImageOverlay.Encoding.AUTO) + .transformation(listOf()) + .build() + + val roundtrippedImageOverlay = + jsonMapper.readValue( + jsonMapper.writeValueAsString(imageOverlay), + jacksonTypeRef(), + ) + + assertThat(roundtrippedImageOverlay).isEqualTo(imageOverlay) + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/OverlayPositionTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/OverlayPositionTest.kt new file mode 100644 index 0000000..a39aa65 --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/OverlayPositionTest.kt @@ -0,0 +1,36 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models + +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.imagekit.api.core.jsonMapper +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class OverlayPositionTest { + + @Test + fun create() { + val overlayPosition = + OverlayPosition.builder().focus(OverlayPosition.Focus.CENTER).x(0.0).y(0.0).build() + + assertThat(overlayPosition.focus()).contains(OverlayPosition.Focus.CENTER) + assertThat(overlayPosition.x()).contains(OverlayPosition.X.ofNumber(0.0)) + assertThat(overlayPosition.y()).contains(OverlayPosition.Y.ofNumber(0.0)) + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val overlayPosition = + OverlayPosition.builder().focus(OverlayPosition.Focus.CENTER).x(0.0).y(0.0).build() + + val roundtrippedOverlayPosition = + jsonMapper.readValue( + jsonMapper.writeValueAsString(overlayPosition), + jacksonTypeRef(), + ) + + assertThat(roundtrippedOverlayPosition).isEqualTo(overlayPosition) + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/OverlayTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/OverlayTest.kt new file mode 100644 index 0000000..c55bfc4 --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/OverlayTest.kt @@ -0,0 +1,361 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models + +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.imagekit.api.core.JsonValue +import com.imagekit.api.core.jsonMapper +import com.imagekit.api.errors.ImageKitInvalidDataException +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.assertThrows +import org.junit.jupiter.params.ParameterizedTest +import org.junit.jupiter.params.provider.EnumSource + +internal class OverlayTest { + + @Test + fun ofText() { + val text = + TextOverlay.builder() + .position( + OverlayPosition.builder() + .focus(OverlayPosition.Focus.CENTER) + .x(0.0) + .y(0.0) + .build() + ) + .timing(OverlayTiming.builder().duration(0.0).end(0.0).start(0.0).build()) + .text("text") + .encoding(TextOverlay.Encoding.AUTO) + .addTransformation( + TextOverlayTransformation.builder() + .alpha(1.0) + .background("background") + .flip(TextOverlayTransformation.Flip.H) + .fontColor("fontColor") + .fontFamily("fontFamily") + .fontSize(0.0) + .innerAlignment(TextOverlayTransformation.InnerAlignment.LEFT) + .lineHeight(0.0) + .padding(0.0) + .radius(0.0) + .rotation(0.0) + .typography("typography") + .width(0.0) + .build() + ) + .build() + + val overlay = Overlay.ofText(text) + + assertThat(overlay.text()).contains(text) + assertThat(overlay.image()).isEmpty + assertThat(overlay.video()).isEmpty + assertThat(overlay.subtitle()).isEmpty + assertThat(overlay.solidColor()).isEmpty + } + + @Test + fun ofTextRoundtrip() { + val jsonMapper = jsonMapper() + val overlay = + Overlay.ofText( + TextOverlay.builder() + .position( + OverlayPosition.builder() + .focus(OverlayPosition.Focus.CENTER) + .x(0.0) + .y(0.0) + .build() + ) + .timing(OverlayTiming.builder().duration(0.0).end(0.0).start(0.0).build()) + .text("text") + .encoding(TextOverlay.Encoding.AUTO) + .addTransformation( + TextOverlayTransformation.builder() + .alpha(1.0) + .background("background") + .flip(TextOverlayTransformation.Flip.H) + .fontColor("fontColor") + .fontFamily("fontFamily") + .fontSize(0.0) + .innerAlignment(TextOverlayTransformation.InnerAlignment.LEFT) + .lineHeight(0.0) + .padding(0.0) + .radius(0.0) + .rotation(0.0) + .typography("typography") + .width(0.0) + .build() + ) + .build() + ) + + val roundtrippedOverlay = + jsonMapper.readValue(jsonMapper.writeValueAsString(overlay), jacksonTypeRef()) + + assertThat(roundtrippedOverlay).isEqualTo(overlay) + } + + @Test + fun ofImage() { + val image = + ImageOverlay.builder() + .position( + OverlayPosition.builder() + .focus(OverlayPosition.Focus.CENTER) + .x(0.0) + .y(0.0) + .build() + ) + .timing(OverlayTiming.builder().duration(0.0).end(0.0).start(0.0).build()) + .input("input") + .encoding(ImageOverlay.Encoding.AUTO) + .transformation(listOf()) + .build() + + val overlay = Overlay.ofImage(image) + + assertThat(overlay.text()).isEmpty + assertThat(overlay.image()).contains(image) + assertThat(overlay.video()).isEmpty + assertThat(overlay.subtitle()).isEmpty + assertThat(overlay.solidColor()).isEmpty + } + + @Test + fun ofImageRoundtrip() { + val jsonMapper = jsonMapper() + val overlay = + Overlay.ofImage( + ImageOverlay.builder() + .position( + OverlayPosition.builder() + .focus(OverlayPosition.Focus.CENTER) + .x(0.0) + .y(0.0) + .build() + ) + .timing(OverlayTiming.builder().duration(0.0).end(0.0).start(0.0).build()) + .input("input") + .encoding(ImageOverlay.Encoding.AUTO) + .transformation(listOf()) + .build() + ) + + val roundtrippedOverlay = + jsonMapper.readValue(jsonMapper.writeValueAsString(overlay), jacksonTypeRef()) + + assertThat(roundtrippedOverlay).isEqualTo(overlay) + } + + @Test + fun ofVideo() { + val video = + VideoOverlay.builder() + .position( + OverlayPosition.builder() + .focus(OverlayPosition.Focus.CENTER) + .x(0.0) + .y(0.0) + .build() + ) + .timing(OverlayTiming.builder().duration(0.0).end(0.0).start(0.0).build()) + .input("input") + .encoding(VideoOverlay.Encoding.AUTO) + .transformation(listOf()) + .build() + + val overlay = Overlay.ofVideo(video) + + assertThat(overlay.text()).isEmpty + assertThat(overlay.image()).isEmpty + assertThat(overlay.video()).contains(video) + assertThat(overlay.subtitle()).isEmpty + assertThat(overlay.solidColor()).isEmpty + } + + @Test + fun ofVideoRoundtrip() { + val jsonMapper = jsonMapper() + val overlay = + Overlay.ofVideo( + VideoOverlay.builder() + .position( + OverlayPosition.builder() + .focus(OverlayPosition.Focus.CENTER) + .x(0.0) + .y(0.0) + .build() + ) + .timing(OverlayTiming.builder().duration(0.0).end(0.0).start(0.0).build()) + .input("input") + .encoding(VideoOverlay.Encoding.AUTO) + .transformation(listOf()) + .build() + ) + + val roundtrippedOverlay = + jsonMapper.readValue(jsonMapper.writeValueAsString(overlay), jacksonTypeRef()) + + assertThat(roundtrippedOverlay).isEqualTo(overlay) + } + + @Test + fun ofSubtitle() { + val subtitle = + SubtitleOverlay.builder() + .position( + OverlayPosition.builder() + .focus(OverlayPosition.Focus.CENTER) + .x(0.0) + .y(0.0) + .build() + ) + .timing(OverlayTiming.builder().duration(0.0).end(0.0).start(0.0).build()) + .input("input") + .encoding(SubtitleOverlay.Encoding.AUTO) + .addTransformation( + SubtitleOverlayTransformation.builder() + .background("background") + .color("color") + .fontFamily("fontFamily") + .fontOutline("fontOutline") + .fontShadow("fontShadow") + .fontSize(0.0) + .typography(SubtitleOverlayTransformation.Typography.B) + .build() + ) + .build() + + val overlay = Overlay.ofSubtitle(subtitle) + + assertThat(overlay.text()).isEmpty + assertThat(overlay.image()).isEmpty + assertThat(overlay.video()).isEmpty + assertThat(overlay.subtitle()).contains(subtitle) + assertThat(overlay.solidColor()).isEmpty + } + + @Test + fun ofSubtitleRoundtrip() { + val jsonMapper = jsonMapper() + val overlay = + Overlay.ofSubtitle( + SubtitleOverlay.builder() + .position( + OverlayPosition.builder() + .focus(OverlayPosition.Focus.CENTER) + .x(0.0) + .y(0.0) + .build() + ) + .timing(OverlayTiming.builder().duration(0.0).end(0.0).start(0.0).build()) + .input("input") + .encoding(SubtitleOverlay.Encoding.AUTO) + .addTransformation( + SubtitleOverlayTransformation.builder() + .background("background") + .color("color") + .fontFamily("fontFamily") + .fontOutline("fontOutline") + .fontShadow("fontShadow") + .fontSize(0.0) + .typography(SubtitleOverlayTransformation.Typography.B) + .build() + ) + .build() + ) + + val roundtrippedOverlay = + jsonMapper.readValue(jsonMapper.writeValueAsString(overlay), jacksonTypeRef()) + + assertThat(roundtrippedOverlay).isEqualTo(overlay) + } + + @Test + fun ofSolidColor() { + val solidColor = + SolidColorOverlay.builder() + .position( + OverlayPosition.builder() + .focus(OverlayPosition.Focus.CENTER) + .x(0.0) + .y(0.0) + .build() + ) + .timing(OverlayTiming.builder().duration(0.0).end(0.0).start(0.0).build()) + .color("color") + .addTransformation( + SolidColorOverlayTransformation.builder() + .alpha(1.0) + .background("background") + .gradientTrue() + .height(0.0) + .radius(0.0) + .width(0.0) + .build() + ) + .build() + + val overlay = Overlay.ofSolidColor(solidColor) + + assertThat(overlay.text()).isEmpty + assertThat(overlay.image()).isEmpty + assertThat(overlay.video()).isEmpty + assertThat(overlay.subtitle()).isEmpty + assertThat(overlay.solidColor()).contains(solidColor) + } + + @Test + fun ofSolidColorRoundtrip() { + val jsonMapper = jsonMapper() + val overlay = + Overlay.ofSolidColor( + SolidColorOverlay.builder() + .position( + OverlayPosition.builder() + .focus(OverlayPosition.Focus.CENTER) + .x(0.0) + .y(0.0) + .build() + ) + .timing(OverlayTiming.builder().duration(0.0).end(0.0).start(0.0).build()) + .color("color") + .addTransformation( + SolidColorOverlayTransformation.builder() + .alpha(1.0) + .background("background") + .gradientTrue() + .height(0.0) + .radius(0.0) + .width(0.0) + .build() + ) + .build() + ) + + val roundtrippedOverlay = + jsonMapper.readValue(jsonMapper.writeValueAsString(overlay), jacksonTypeRef()) + + assertThat(roundtrippedOverlay).isEqualTo(overlay) + } + + enum class IncompatibleJsonShapeTestCase(val value: JsonValue) { + BOOLEAN(JsonValue.from(false)), + STRING(JsonValue.from("invalid")), + INTEGER(JsonValue.from(-1)), + FLOAT(JsonValue.from(3.14)), + ARRAY(JsonValue.from(listOf("invalid", "array"))), + } + + @ParameterizedTest + @EnumSource + fun incompatibleJsonShapeDeserializesToUnknown(testCase: IncompatibleJsonShapeTestCase) { + val overlay = jsonMapper().convertValue(testCase.value, jacksonTypeRef()) + + val e = assertThrows { overlay.validate() } + assertThat(e).hasMessageStartingWith("Unknown ") + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/OverlayTimingTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/OverlayTimingTest.kt new file mode 100644 index 0000000..b31c4ea --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/OverlayTimingTest.kt @@ -0,0 +1,34 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models + +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.imagekit.api.core.jsonMapper +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class OverlayTimingTest { + + @Test + fun create() { + val overlayTiming = OverlayTiming.builder().duration(0.0).end(0.0).start(0.0).build() + + assertThat(overlayTiming.duration()).contains(OverlayTiming.Duration.ofNumber(0.0)) + assertThat(overlayTiming.end()).contains(OverlayTiming.End.ofNumber(0.0)) + assertThat(overlayTiming.start()).contains(OverlayTiming.Start.ofNumber(0.0)) + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val overlayTiming = OverlayTiming.builder().duration(0.0).end(0.0).start(0.0).build() + + val roundtrippedOverlayTiming = + jsonMapper.readValue( + jsonMapper.writeValueAsString(overlayTiming), + jacksonTypeRef(), + ) + + assertThat(roundtrippedOverlayTiming).isEqualTo(overlayTiming) + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/SolidColorOverlayTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/SolidColorOverlayTest.kt new file mode 100644 index 0000000..7989cf7 --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/SolidColorOverlayTest.kt @@ -0,0 +1,92 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models + +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.imagekit.api.core.jsonMapper +import kotlin.jvm.optionals.getOrNull +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class SolidColorOverlayTest { + + @Test + fun create() { + val solidColorOverlay = + SolidColorOverlay.builder() + .position( + OverlayPosition.builder() + .focus(OverlayPosition.Focus.CENTER) + .x(0.0) + .y(0.0) + .build() + ) + .timing(OverlayTiming.builder().duration(0.0).end(0.0).start(0.0).build()) + .color("color") + .addTransformation( + SolidColorOverlayTransformation.builder() + .alpha(1.0) + .background("background") + .gradientTrue() + .height(0.0) + .radius(0.0) + .width(0.0) + .build() + ) + .build() + + assertThat(solidColorOverlay.position()) + .contains( + OverlayPosition.builder().focus(OverlayPosition.Focus.CENTER).x(0.0).y(0.0).build() + ) + assertThat(solidColorOverlay.timing()) + .contains(OverlayTiming.builder().duration(0.0).end(0.0).start(0.0).build()) + assertThat(solidColorOverlay.color()).isEqualTo("color") + assertThat(solidColorOverlay.transformation().getOrNull()) + .containsExactly( + SolidColorOverlayTransformation.builder() + .alpha(1.0) + .background("background") + .gradientTrue() + .height(0.0) + .radius(0.0) + .width(0.0) + .build() + ) + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val solidColorOverlay = + SolidColorOverlay.builder() + .position( + OverlayPosition.builder() + .focus(OverlayPosition.Focus.CENTER) + .x(0.0) + .y(0.0) + .build() + ) + .timing(OverlayTiming.builder().duration(0.0).end(0.0).start(0.0).build()) + .color("color") + .addTransformation( + SolidColorOverlayTransformation.builder() + .alpha(1.0) + .background("background") + .gradientTrue() + .height(0.0) + .radius(0.0) + .width(0.0) + .build() + ) + .build() + + val roundtrippedSolidColorOverlay = + jsonMapper.readValue( + jsonMapper.writeValueAsString(solidColorOverlay), + jacksonTypeRef(), + ) + + assertThat(roundtrippedSolidColorOverlay).isEqualTo(solidColorOverlay) + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/SolidColorOverlayTransformationTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/SolidColorOverlayTransformationTest.kt new file mode 100644 index 0000000..d5802c9 --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/SolidColorOverlayTransformationTest.kt @@ -0,0 +1,58 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models + +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.imagekit.api.core.jsonMapper +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class SolidColorOverlayTransformationTest { + + @Test + fun create() { + val solidColorOverlayTransformation = + SolidColorOverlayTransformation.builder() + .alpha(1.0) + .background("background") + .gradientTrue() + .height(0.0) + .radius(0.0) + .width(0.0) + .build() + + assertThat(solidColorOverlayTransformation.alpha()).contains(1.0) + assertThat(solidColorOverlayTransformation.background()).contains("background") + assertThat(solidColorOverlayTransformation.gradient()) + .contains(SolidColorOverlayTransformation.Gradient.ofTrue()) + assertThat(solidColorOverlayTransformation.height()) + .contains(SolidColorOverlayTransformation.Height.ofNumber(0.0)) + assertThat(solidColorOverlayTransformation.radius()) + .contains(SolidColorOverlayTransformation.Radius.ofNumber(0.0)) + assertThat(solidColorOverlayTransformation.width()) + .contains(SolidColorOverlayTransformation.Width.ofNumber(0.0)) + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val solidColorOverlayTransformation = + SolidColorOverlayTransformation.builder() + .alpha(1.0) + .background("background") + .gradientTrue() + .height(0.0) + .radius(0.0) + .width(0.0) + .build() + + val roundtrippedSolidColorOverlayTransformation = + jsonMapper.readValue( + jsonMapper.writeValueAsString(solidColorOverlayTransformation), + jacksonTypeRef(), + ) + + assertThat(roundtrippedSolidColorOverlayTransformation) + .isEqualTo(solidColorOverlayTransformation) + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/SrcOptionsTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/SrcOptionsTest.kt new file mode 100644 index 0000000..a475e8e --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/SrcOptionsTest.kt @@ -0,0 +1,234 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models + +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.imagekit.api.core.JsonValue +import com.imagekit.api.core.jsonMapper +import kotlin.jvm.optionals.getOrNull +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class SrcOptionsTest { + + @Test + fun create() { + val srcOptions = + SrcOptions.builder() + .src("/my-image.jpg") + .urlEndpoint("https://ik.imagekit.io/demo") + .expiresIn(0.0) + .queryParameters( + SrcOptions.QueryParameters.builder() + .putAdditionalProperty("foo", JsonValue.from("string")) + .build() + ) + .signed(true) + .addTransformation( + Transformation.builder() + .aiChangeBackground("aiChangeBackground") + .aiDropShadowTrue() + .aiEdit("aiEdit") + .aiRemoveBackground(Transformation.AiRemoveBackground.TRUE) + .aiRemoveBackgroundExternal(Transformation.AiRemoveBackgroundExternal.TRUE) + .aiRetouch(Transformation.AiRetouch.TRUE) + .aiUpscale(Transformation.AiUpscale.TRUE) + .aiVariation(Transformation.AiVariation.TRUE) + .aspectRatio("4:3") + .audioCodec(Transformation.AudioCodec.AAC) + .background("red") + .blur(10.0) + .border("5_FF0000") + .colorProfile(true) + .contrastStretch(Transformation.ContrastStretch.TRUE) + .crop(Transformation.Crop.FORCE) + .cropMode(Transformation.CropMode.PAD_RESIZE) + .defaultImage("defaultImage") + .dpr(2.0) + .duration(0.0) + .endOffset(0.0) + .flip(Transformation.Flip.H) + .focus("center") + .format(Transformation.Format.AUTO) + .gradientTrue() + .grayscale(Transformation.Grayscale.TRUE) + .height(200.0) + .lossless(true) + .metadata(true) + .named("named") + .opacity(0.0) + .original(true) + .page(0.0) + .progressive(true) + .quality(80.0) + .radius(20.0) + .raw("raw") + .rotation(90.0) + .shadowTrue() + .sharpenTrue() + .startOffset(0.0) + .addStreamingResolution(StreamingResolution._240) + .trimTrue() + .unsharpMaskTrue() + .videoCodec(Transformation.VideoCodec.H264) + .width(300.0) + .x(0.0) + .xCenter(0.0) + .y(0.0) + .yCenter(0.0) + .zoom(0.0) + .build() + ) + .transformationPosition(TransformationPosition.PATH) + .build() + + assertThat(srcOptions.src()).isEqualTo("/my-image.jpg") + assertThat(srcOptions.urlEndpoint()).isEqualTo("https://ik.imagekit.io/demo") + assertThat(srcOptions.expiresIn()).contains(0.0) + assertThat(srcOptions.queryParameters()) + .contains( + SrcOptions.QueryParameters.builder() + .putAdditionalProperty("foo", JsonValue.from("string")) + .build() + ) + assertThat(srcOptions.signed()).contains(true) + assertThat(srcOptions.transformation().getOrNull()) + .containsExactly( + Transformation.builder() + .aiChangeBackground("aiChangeBackground") + .aiDropShadowTrue() + .aiEdit("aiEdit") + .aiRemoveBackground(Transformation.AiRemoveBackground.TRUE) + .aiRemoveBackgroundExternal(Transformation.AiRemoveBackgroundExternal.TRUE) + .aiRetouch(Transformation.AiRetouch.TRUE) + .aiUpscale(Transformation.AiUpscale.TRUE) + .aiVariation(Transformation.AiVariation.TRUE) + .aspectRatio("4:3") + .audioCodec(Transformation.AudioCodec.AAC) + .background("red") + .blur(10.0) + .border("5_FF0000") + .colorProfile(true) + .contrastStretch(Transformation.ContrastStretch.TRUE) + .crop(Transformation.Crop.FORCE) + .cropMode(Transformation.CropMode.PAD_RESIZE) + .defaultImage("defaultImage") + .dpr(2.0) + .duration(0.0) + .endOffset(0.0) + .flip(Transformation.Flip.H) + .focus("center") + .format(Transformation.Format.AUTO) + .gradientTrue() + .grayscale(Transformation.Grayscale.TRUE) + .height(200.0) + .lossless(true) + .metadata(true) + .named("named") + .opacity(0.0) + .original(true) + .page(0.0) + .progressive(true) + .quality(80.0) + .radius(20.0) + .raw("raw") + .rotation(90.0) + .shadowTrue() + .sharpenTrue() + .startOffset(0.0) + .addStreamingResolution(StreamingResolution._240) + .trimTrue() + .unsharpMaskTrue() + .videoCodec(Transformation.VideoCodec.H264) + .width(300.0) + .x(0.0) + .xCenter(0.0) + .y(0.0) + .yCenter(0.0) + .zoom(0.0) + .build() + ) + assertThat(srcOptions.transformationPosition()).contains(TransformationPosition.PATH) + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val srcOptions = + SrcOptions.builder() + .src("/my-image.jpg") + .urlEndpoint("https://ik.imagekit.io/demo") + .expiresIn(0.0) + .queryParameters( + SrcOptions.QueryParameters.builder() + .putAdditionalProperty("foo", JsonValue.from("string")) + .build() + ) + .signed(true) + .addTransformation( + Transformation.builder() + .aiChangeBackground("aiChangeBackground") + .aiDropShadowTrue() + .aiEdit("aiEdit") + .aiRemoveBackground(Transformation.AiRemoveBackground.TRUE) + .aiRemoveBackgroundExternal(Transformation.AiRemoveBackgroundExternal.TRUE) + .aiRetouch(Transformation.AiRetouch.TRUE) + .aiUpscale(Transformation.AiUpscale.TRUE) + .aiVariation(Transformation.AiVariation.TRUE) + .aspectRatio("4:3") + .audioCodec(Transformation.AudioCodec.AAC) + .background("red") + .blur(10.0) + .border("5_FF0000") + .colorProfile(true) + .contrastStretch(Transformation.ContrastStretch.TRUE) + .crop(Transformation.Crop.FORCE) + .cropMode(Transformation.CropMode.PAD_RESIZE) + .defaultImage("defaultImage") + .dpr(2.0) + .duration(0.0) + .endOffset(0.0) + .flip(Transformation.Flip.H) + .focus("center") + .format(Transformation.Format.AUTO) + .gradientTrue() + .grayscale(Transformation.Grayscale.TRUE) + .height(200.0) + .lossless(true) + .metadata(true) + .named("named") + .opacity(0.0) + .original(true) + .page(0.0) + .progressive(true) + .quality(80.0) + .radius(20.0) + .raw("raw") + .rotation(90.0) + .shadowTrue() + .sharpenTrue() + .startOffset(0.0) + .addStreamingResolution(StreamingResolution._240) + .trimTrue() + .unsharpMaskTrue() + .videoCodec(Transformation.VideoCodec.H264) + .width(300.0) + .x(0.0) + .xCenter(0.0) + .y(0.0) + .yCenter(0.0) + .zoom(0.0) + .build() + ) + .transformationPosition(TransformationPosition.PATH) + .build() + + val roundtrippedSrcOptions = + jsonMapper.readValue( + jsonMapper.writeValueAsString(srcOptions), + jacksonTypeRef(), + ) + + assertThat(roundtrippedSrcOptions).isEqualTo(srcOptions) + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/SubtitleOverlayTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/SubtitleOverlayTest.kt new file mode 100644 index 0000000..c0f445a --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/SubtitleOverlayTest.kt @@ -0,0 +1,98 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models + +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.imagekit.api.core.jsonMapper +import kotlin.jvm.optionals.getOrNull +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class SubtitleOverlayTest { + + @Test + fun create() { + val subtitleOverlay = + SubtitleOverlay.builder() + .position( + OverlayPosition.builder() + .focus(OverlayPosition.Focus.CENTER) + .x(0.0) + .y(0.0) + .build() + ) + .timing(OverlayTiming.builder().duration(0.0).end(0.0).start(0.0).build()) + .input("input") + .encoding(SubtitleOverlay.Encoding.AUTO) + .addTransformation( + SubtitleOverlayTransformation.builder() + .background("background") + .color("color") + .fontFamily("fontFamily") + .fontOutline("fontOutline") + .fontShadow("fontShadow") + .fontSize(0.0) + .typography(SubtitleOverlayTransformation.Typography.B) + .build() + ) + .build() + + assertThat(subtitleOverlay.position()) + .contains( + OverlayPosition.builder().focus(OverlayPosition.Focus.CENTER).x(0.0).y(0.0).build() + ) + assertThat(subtitleOverlay.timing()) + .contains(OverlayTiming.builder().duration(0.0).end(0.0).start(0.0).build()) + assertThat(subtitleOverlay.input()).isEqualTo("input") + assertThat(subtitleOverlay.encoding()).contains(SubtitleOverlay.Encoding.AUTO) + assertThat(subtitleOverlay.transformation().getOrNull()) + .containsExactly( + SubtitleOverlayTransformation.builder() + .background("background") + .color("color") + .fontFamily("fontFamily") + .fontOutline("fontOutline") + .fontShadow("fontShadow") + .fontSize(0.0) + .typography(SubtitleOverlayTransformation.Typography.B) + .build() + ) + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val subtitleOverlay = + SubtitleOverlay.builder() + .position( + OverlayPosition.builder() + .focus(OverlayPosition.Focus.CENTER) + .x(0.0) + .y(0.0) + .build() + ) + .timing(OverlayTiming.builder().duration(0.0).end(0.0).start(0.0).build()) + .input("input") + .encoding(SubtitleOverlay.Encoding.AUTO) + .addTransformation( + SubtitleOverlayTransformation.builder() + .background("background") + .color("color") + .fontFamily("fontFamily") + .fontOutline("fontOutline") + .fontShadow("fontShadow") + .fontSize(0.0) + .typography(SubtitleOverlayTransformation.Typography.B) + .build() + ) + .build() + + val roundtrippedSubtitleOverlay = + jsonMapper.readValue( + jsonMapper.writeValueAsString(subtitleOverlay), + jacksonTypeRef(), + ) + + assertThat(roundtrippedSubtitleOverlay).isEqualTo(subtitleOverlay) + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/SubtitleOverlayTransformationTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/SubtitleOverlayTransformationTest.kt new file mode 100644 index 0000000..1fcf8c6 --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/SubtitleOverlayTransformationTest.kt @@ -0,0 +1,58 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models + +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.imagekit.api.core.jsonMapper +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class SubtitleOverlayTransformationTest { + + @Test + fun create() { + val subtitleOverlayTransformation = + SubtitleOverlayTransformation.builder() + .background("background") + .color("color") + .fontFamily("fontFamily") + .fontOutline("fontOutline") + .fontShadow("fontShadow") + .fontSize(0.0) + .typography(SubtitleOverlayTransformation.Typography.B) + .build() + + assertThat(subtitleOverlayTransformation.background()).contains("background") + assertThat(subtitleOverlayTransformation.color()).contains("color") + assertThat(subtitleOverlayTransformation.fontFamily()).contains("fontFamily") + assertThat(subtitleOverlayTransformation.fontOutline()).contains("fontOutline") + assertThat(subtitleOverlayTransformation.fontShadow()).contains("fontShadow") + assertThat(subtitleOverlayTransformation.fontSize()).contains(0.0) + assertThat(subtitleOverlayTransformation.typography()) + .contains(SubtitleOverlayTransformation.Typography.B) + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val subtitleOverlayTransformation = + SubtitleOverlayTransformation.builder() + .background("background") + .color("color") + .fontFamily("fontFamily") + .fontOutline("fontOutline") + .fontShadow("fontShadow") + .fontSize(0.0) + .typography(SubtitleOverlayTransformation.Typography.B) + .build() + + val roundtrippedSubtitleOverlayTransformation = + jsonMapper.readValue( + jsonMapper.writeValueAsString(subtitleOverlayTransformation), + jacksonTypeRef(), + ) + + assertThat(roundtrippedSubtitleOverlayTransformation) + .isEqualTo(subtitleOverlayTransformation) + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/TextOverlayTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/TextOverlayTest.kt new file mode 100644 index 0000000..6b3a27b --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/TextOverlayTest.kt @@ -0,0 +1,116 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models + +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.imagekit.api.core.jsonMapper +import kotlin.jvm.optionals.getOrNull +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class TextOverlayTest { + + @Test + fun create() { + val textOverlay = + TextOverlay.builder() + .position( + OverlayPosition.builder() + .focus(OverlayPosition.Focus.CENTER) + .x(0.0) + .y(0.0) + .build() + ) + .timing(OverlayTiming.builder().duration(0.0).end(0.0).start(0.0).build()) + .text("text") + .encoding(TextOverlay.Encoding.AUTO) + .addTransformation( + TextOverlayTransformation.builder() + .alpha(1.0) + .background("background") + .flip(TextOverlayTransformation.Flip.H) + .fontColor("fontColor") + .fontFamily("fontFamily") + .fontSize(0.0) + .innerAlignment(TextOverlayTransformation.InnerAlignment.LEFT) + .lineHeight(0.0) + .padding(0.0) + .radius(0.0) + .rotation(0.0) + .typography("typography") + .width(0.0) + .build() + ) + .build() + + assertThat(textOverlay.position()) + .contains( + OverlayPosition.builder().focus(OverlayPosition.Focus.CENTER).x(0.0).y(0.0).build() + ) + assertThat(textOverlay.timing()) + .contains(OverlayTiming.builder().duration(0.0).end(0.0).start(0.0).build()) + assertThat(textOverlay.text()).isEqualTo("text") + assertThat(textOverlay.encoding()).contains(TextOverlay.Encoding.AUTO) + assertThat(textOverlay.transformation().getOrNull()) + .containsExactly( + TextOverlayTransformation.builder() + .alpha(1.0) + .background("background") + .flip(TextOverlayTransformation.Flip.H) + .fontColor("fontColor") + .fontFamily("fontFamily") + .fontSize(0.0) + .innerAlignment(TextOverlayTransformation.InnerAlignment.LEFT) + .lineHeight(0.0) + .padding(0.0) + .radius(0.0) + .rotation(0.0) + .typography("typography") + .width(0.0) + .build() + ) + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val textOverlay = + TextOverlay.builder() + .position( + OverlayPosition.builder() + .focus(OverlayPosition.Focus.CENTER) + .x(0.0) + .y(0.0) + .build() + ) + .timing(OverlayTiming.builder().duration(0.0).end(0.0).start(0.0).build()) + .text("text") + .encoding(TextOverlay.Encoding.AUTO) + .addTransformation( + TextOverlayTransformation.builder() + .alpha(1.0) + .background("background") + .flip(TextOverlayTransformation.Flip.H) + .fontColor("fontColor") + .fontFamily("fontFamily") + .fontSize(0.0) + .innerAlignment(TextOverlayTransformation.InnerAlignment.LEFT) + .lineHeight(0.0) + .padding(0.0) + .radius(0.0) + .rotation(0.0) + .typography("typography") + .width(0.0) + .build() + ) + .build() + + val roundtrippedTextOverlay = + jsonMapper.readValue( + jsonMapper.writeValueAsString(textOverlay), + jacksonTypeRef(), + ) + + assertThat(roundtrippedTextOverlay).isEqualTo(textOverlay) + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/TextOverlayTransformationTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/TextOverlayTransformationTest.kt new file mode 100644 index 0000000..f07cd59 --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/TextOverlayTransformationTest.kt @@ -0,0 +1,81 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models + +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.imagekit.api.core.jsonMapper +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class TextOverlayTransformationTest { + + @Test + fun create() { + val textOverlayTransformation = + TextOverlayTransformation.builder() + .alpha(1.0) + .background("background") + .flip(TextOverlayTransformation.Flip.H) + .fontColor("fontColor") + .fontFamily("fontFamily") + .fontSize(0.0) + .innerAlignment(TextOverlayTransformation.InnerAlignment.LEFT) + .lineHeight(0.0) + .padding(0.0) + .radius(0.0) + .rotation(0.0) + .typography("typography") + .width(0.0) + .build() + + assertThat(textOverlayTransformation.alpha()).contains(1.0) + assertThat(textOverlayTransformation.background()).contains("background") + assertThat(textOverlayTransformation.flip()).contains(TextOverlayTransformation.Flip.H) + assertThat(textOverlayTransformation.fontColor()).contains("fontColor") + assertThat(textOverlayTransformation.fontFamily()).contains("fontFamily") + assertThat(textOverlayTransformation.fontSize()) + .contains(TextOverlayTransformation.FontSize.ofNumber(0.0)) + assertThat(textOverlayTransformation.innerAlignment()) + .contains(TextOverlayTransformation.InnerAlignment.LEFT) + assertThat(textOverlayTransformation.lineHeight()) + .contains(TextOverlayTransformation.LineHeight.ofNumber(0.0)) + assertThat(textOverlayTransformation.padding()) + .contains(TextOverlayTransformation.Padding.ofNumber(0.0)) + assertThat(textOverlayTransformation.radius()) + .contains(TextOverlayTransformation.Radius.ofNumber(0.0)) + assertThat(textOverlayTransformation.rotation()) + .contains(TextOverlayTransformation.Rotation.ofNumber(0.0)) + assertThat(textOverlayTransformation.typography()).contains("typography") + assertThat(textOverlayTransformation.width()) + .contains(TextOverlayTransformation.Width.ofNumber(0.0)) + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val textOverlayTransformation = + TextOverlayTransformation.builder() + .alpha(1.0) + .background("background") + .flip(TextOverlayTransformation.Flip.H) + .fontColor("fontColor") + .fontFamily("fontFamily") + .fontSize(0.0) + .innerAlignment(TextOverlayTransformation.InnerAlignment.LEFT) + .lineHeight(0.0) + .padding(0.0) + .radius(0.0) + .rotation(0.0) + .typography("typography") + .width(0.0) + .build() + + val roundtrippedTextOverlayTransformation = + jsonMapper.readValue( + jsonMapper.writeValueAsString(textOverlayTransformation), + jacksonTypeRef(), + ) + + assertThat(roundtrippedTextOverlayTransformation).isEqualTo(textOverlayTransformation) + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/TransformationTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/TransformationTest.kt new file mode 100644 index 0000000..3dee6fd --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/TransformationTest.kt @@ -0,0 +1,193 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models + +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.imagekit.api.core.jsonMapper +import kotlin.jvm.optionals.getOrNull +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class TransformationTest { + + @Test + fun create() { + val transformation = + Transformation.builder() + .aiChangeBackground("aiChangeBackground") + .aiDropShadowTrue() + .aiEdit("aiEdit") + .aiRemoveBackground(Transformation.AiRemoveBackground.TRUE) + .aiRemoveBackgroundExternal(Transformation.AiRemoveBackgroundExternal.TRUE) + .aiRetouch(Transformation.AiRetouch.TRUE) + .aiUpscale(Transformation.AiUpscale.TRUE) + .aiVariation(Transformation.AiVariation.TRUE) + .aspectRatio("4:3") + .audioCodec(Transformation.AudioCodec.AAC) + .background("red") + .blur(10.0) + .border("5_FF0000") + .colorProfile(true) + .contrastStretch(Transformation.ContrastStretch.TRUE) + .crop(Transformation.Crop.FORCE) + .cropMode(Transformation.CropMode.PAD_RESIZE) + .defaultImage("defaultImage") + .dpr(2.0) + .duration(0.0) + .endOffset(0.0) + .flip(Transformation.Flip.H) + .focus("center") + .format(Transformation.Format.AUTO) + .gradientTrue() + .grayscale(Transformation.Grayscale.TRUE) + .height(200.0) + .lossless(true) + .metadata(true) + .named("named") + .opacity(0.0) + .original(true) + .page(0.0) + .progressive(true) + .quality(80.0) + .radius(20.0) + .raw("raw") + .rotation(90.0) + .shadowTrue() + .sharpenTrue() + .startOffset(0.0) + .addStreamingResolution(StreamingResolution._240) + .trimTrue() + .unsharpMaskTrue() + .videoCodec(Transformation.VideoCodec.H264) + .width(300.0) + .x(0.0) + .xCenter(0.0) + .y(0.0) + .yCenter(0.0) + .zoom(0.0) + .build() + + assertThat(transformation.aiChangeBackground()).contains("aiChangeBackground") + assertThat(transformation.aiDropShadow()).contains(Transformation.AiDropShadow.ofTrue()) + assertThat(transformation.aiEdit()).contains("aiEdit") + assertThat(transformation.aiRemoveBackground()) + .contains(Transformation.AiRemoveBackground.TRUE) + assertThat(transformation.aiRemoveBackgroundExternal()) + .contains(Transformation.AiRemoveBackgroundExternal.TRUE) + assertThat(transformation.aiRetouch()).contains(Transformation.AiRetouch.TRUE) + assertThat(transformation.aiUpscale()).contains(Transformation.AiUpscale.TRUE) + assertThat(transformation.aiVariation()).contains(Transformation.AiVariation.TRUE) + assertThat(transformation.aspectRatio()) + .contains(Transformation.AspectRatio.ofString("4:3")) + assertThat(transformation.audioCodec()).contains(Transformation.AudioCodec.AAC) + assertThat(transformation.background()).contains("red") + assertThat(transformation.blur()).contains(10.0) + assertThat(transformation.border()).contains("5_FF0000") + assertThat(transformation.colorProfile()).contains(true) + assertThat(transformation.contrastStretch()).contains(Transformation.ContrastStretch.TRUE) + assertThat(transformation.crop()).contains(Transformation.Crop.FORCE) + assertThat(transformation.cropMode()).contains(Transformation.CropMode.PAD_RESIZE) + assertThat(transformation.defaultImage()).contains("defaultImage") + assertThat(transformation.dpr()).contains(2.0) + assertThat(transformation.duration()).contains(Transformation.Duration.ofNumber(0.0)) + assertThat(transformation.endOffset()).contains(Transformation.EndOffset.ofNumber(0.0)) + assertThat(transformation.flip()).contains(Transformation.Flip.H) + assertThat(transformation.focus()).contains("center") + assertThat(transformation.format()).contains(Transformation.Format.AUTO) + assertThat(transformation.gradient()).contains(Transformation.Gradient.ofTrue()) + assertThat(transformation.grayscale()).contains(Transformation.Grayscale.TRUE) + assertThat(transformation.height()).contains(Transformation.Height.ofNumber(200.0)) + assertThat(transformation.lossless()).contains(true) + assertThat(transformation.metadata()).contains(true) + assertThat(transformation.named()).contains("named") + assertThat(transformation.opacity()).contains(0.0) + assertThat(transformation.original()).contains(true) + assertThat(transformation.page()).contains(Transformation.Page.ofNumber(0.0)) + assertThat(transformation.progressive()).contains(true) + assertThat(transformation.quality()).contains(80.0) + assertThat(transformation.radius()).contains(Transformation.Radius.ofNumber(20.0)) + assertThat(transformation.raw()).contains("raw") + assertThat(transformation.rotation()).contains(Transformation.Rotation.ofNumber(90.0)) + assertThat(transformation.shadow()).contains(Transformation.Shadow.ofTrue()) + assertThat(transformation.sharpen()).contains(Transformation.Sharpen.ofTrue()) + assertThat(transformation.startOffset()).contains(Transformation.StartOffset.ofNumber(0.0)) + assertThat(transformation.streamingResolutions().getOrNull()) + .containsExactly(StreamingResolution._240) + assertThat(transformation.trim()).contains(Transformation.Trim.ofTrue()) + assertThat(transformation.unsharpMask()).contains(Transformation.UnsharpMask.ofTrue()) + assertThat(transformation.videoCodec()).contains(Transformation.VideoCodec.H264) + assertThat(transformation.width()).contains(Transformation.Width.ofNumber(300.0)) + assertThat(transformation.x()).contains(Transformation.X.ofNumber(0.0)) + assertThat(transformation.xCenter()).contains(Transformation.XCenter.ofNumber(0.0)) + assertThat(transformation.y()).contains(Transformation.Y.ofNumber(0.0)) + assertThat(transformation.yCenter()).contains(Transformation.YCenter.ofNumber(0.0)) + assertThat(transformation.zoom()).contains(0.0) + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val transformation = + Transformation.builder() + .aiChangeBackground("aiChangeBackground") + .aiDropShadowTrue() + .aiEdit("aiEdit") + .aiRemoveBackground(Transformation.AiRemoveBackground.TRUE) + .aiRemoveBackgroundExternal(Transformation.AiRemoveBackgroundExternal.TRUE) + .aiRetouch(Transformation.AiRetouch.TRUE) + .aiUpscale(Transformation.AiUpscale.TRUE) + .aiVariation(Transformation.AiVariation.TRUE) + .aspectRatio("4:3") + .audioCodec(Transformation.AudioCodec.AAC) + .background("red") + .blur(10.0) + .border("5_FF0000") + .colorProfile(true) + .contrastStretch(Transformation.ContrastStretch.TRUE) + .crop(Transformation.Crop.FORCE) + .cropMode(Transformation.CropMode.PAD_RESIZE) + .defaultImage("defaultImage") + .dpr(2.0) + .duration(0.0) + .endOffset(0.0) + .flip(Transformation.Flip.H) + .focus("center") + .format(Transformation.Format.AUTO) + .gradientTrue() + .grayscale(Transformation.Grayscale.TRUE) + .height(200.0) + .lossless(true) + .metadata(true) + .named("named") + .opacity(0.0) + .original(true) + .page(0.0) + .progressive(true) + .quality(80.0) + .radius(20.0) + .raw("raw") + .rotation(90.0) + .shadowTrue() + .sharpenTrue() + .startOffset(0.0) + .addStreamingResolution(StreamingResolution._240) + .trimTrue() + .unsharpMaskTrue() + .videoCodec(Transformation.VideoCodec.H264) + .width(300.0) + .x(0.0) + .xCenter(0.0) + .y(0.0) + .yCenter(0.0) + .zoom(0.0) + .build() + + val roundtrippedTransformation = + jsonMapper.readValue( + jsonMapper.writeValueAsString(transformation), + jacksonTypeRef(), + ) + + assertThat(roundtrippedTransformation).isEqualTo(transformation) + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/VideoOverlayTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/VideoOverlayTest.kt new file mode 100644 index 0000000..caca3a9 --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/VideoOverlayTest.kt @@ -0,0 +1,67 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models + +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.imagekit.api.core.jsonMapper +import kotlin.jvm.optionals.getOrNull +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class VideoOverlayTest { + + @Test + fun create() { + val videoOverlay = + VideoOverlay.builder() + .position( + OverlayPosition.builder() + .focus(OverlayPosition.Focus.CENTER) + .x(0.0) + .y(0.0) + .build() + ) + .timing(OverlayTiming.builder().duration(0.0).end(0.0).start(0.0).build()) + .input("input") + .encoding(VideoOverlay.Encoding.AUTO) + .transformation(listOf()) + .build() + + assertThat(videoOverlay.position()) + .contains( + OverlayPosition.builder().focus(OverlayPosition.Focus.CENTER).x(0.0).y(0.0).build() + ) + assertThat(videoOverlay.timing()) + .contains(OverlayTiming.builder().duration(0.0).end(0.0).start(0.0).build()) + assertThat(videoOverlay.input()).isEqualTo("input") + assertThat(videoOverlay.encoding()).contains(VideoOverlay.Encoding.AUTO) + assertThat(videoOverlay.transformation().getOrNull()).containsExactly() + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val videoOverlay = + VideoOverlay.builder() + .position( + OverlayPosition.builder() + .focus(OverlayPosition.Focus.CENTER) + .x(0.0) + .y(0.0) + .build() + ) + .timing(OverlayTiming.builder().duration(0.0).end(0.0).start(0.0).build()) + .input("input") + .encoding(VideoOverlay.Encoding.AUTO) + .transformation(listOf()) + .build() + + val roundtrippedVideoOverlay = + jsonMapper.readValue( + jsonMapper.writeValueAsString(videoOverlay), + jacksonTypeRef(), + ) + + assertThat(roundtrippedVideoOverlay).isEqualTo(videoOverlay) + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/accounts/origins/OriginCreateParamsTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/accounts/origins/OriginCreateParamsTest.kt new file mode 100644 index 0000000..7c03cc6 --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/accounts/origins/OriginCreateParamsTest.kt @@ -0,0 +1,90 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.accounts.origins + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class OriginCreateParamsTest { + + @Test + fun create() { + OriginCreateParams.builder() + .originRequest( + OriginRequest.S3.builder() + .accessKey("AKIATEST123") + .bucket("test-bucket") + .name("My S3 Origin") + .secretKey("secrettest123") + .baseUrlForCanonicalHeader("https://cdn.example.com") + .includeCanonicalHeader(false) + .prefix("images") + .build() + ) + .build() + } + + @Test + fun body() { + val params = + OriginCreateParams.builder() + .originRequest( + OriginRequest.S3.builder() + .accessKey("AKIATEST123") + .bucket("test-bucket") + .name("My S3 Origin") + .secretKey("secrettest123") + .baseUrlForCanonicalHeader("https://cdn.example.com") + .includeCanonicalHeader(false) + .prefix("images") + .build() + ) + .build() + + val body = params._body() + + assertThat(body) + .isEqualTo( + OriginRequest.ofS3( + OriginRequest.S3.builder() + .accessKey("AKIATEST123") + .bucket("test-bucket") + .name("My S3 Origin") + .secretKey("secrettest123") + .baseUrlForCanonicalHeader("https://cdn.example.com") + .includeCanonicalHeader(false) + .prefix("images") + .build() + ) + ) + } + + @Test + fun bodyWithoutOptionalFields() { + val params = + OriginCreateParams.builder() + .originRequest( + OriginRequest.S3.builder() + .accessKey("AKIATEST123") + .bucket("test-bucket") + .name("My S3 Origin") + .secretKey("secrettest123") + .build() + ) + .build() + + val body = params._body() + + assertThat(body) + .isEqualTo( + OriginRequest.ofS3( + OriginRequest.S3.builder() + .accessKey("AKIATEST123") + .bucket("test-bucket") + .name("My S3 Origin") + .secretKey("secrettest123") + .build() + ) + ) + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/accounts/origins/OriginDeleteParamsTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/accounts/origins/OriginDeleteParamsTest.kt new file mode 100644 index 0000000..ef9d5f3 --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/accounts/origins/OriginDeleteParamsTest.kt @@ -0,0 +1,23 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.accounts.origins + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class OriginDeleteParamsTest { + + @Test + fun create() { + OriginDeleteParams.builder().id("id").build() + } + + @Test + fun pathParams() { + val params = OriginDeleteParams.builder().id("id").build() + + assertThat(params._pathParam(0)).isEqualTo("id") + // out-of-bound path param + assertThat(params._pathParam(1)).isEqualTo("") + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/accounts/origins/OriginGetParamsTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/accounts/origins/OriginGetParamsTest.kt new file mode 100644 index 0000000..e029b05 --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/accounts/origins/OriginGetParamsTest.kt @@ -0,0 +1,23 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.accounts.origins + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class OriginGetParamsTest { + + @Test + fun create() { + OriginGetParams.builder().id("id").build() + } + + @Test + fun pathParams() { + val params = OriginGetParams.builder().id("id").build() + + assertThat(params._pathParam(0)).isEqualTo("id") + // out-of-bound path param + assertThat(params._pathParam(1)).isEqualTo("") + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/accounts/origins/OriginListParamsTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/accounts/origins/OriginListParamsTest.kt new file mode 100644 index 0000000..4a9eb55 --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/accounts/origins/OriginListParamsTest.kt @@ -0,0 +1,13 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.accounts.origins + +import org.junit.jupiter.api.Test + +internal class OriginListParamsTest { + + @Test + fun create() { + OriginListParams.builder().build() + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/accounts/origins/OriginRequestTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/accounts/origins/OriginRequestTest.kt new file mode 100644 index 0000000..74f88fc --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/accounts/origins/OriginRequestTest.kt @@ -0,0 +1,428 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.accounts.origins + +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.imagekit.api.core.JsonValue +import com.imagekit.api.core.jsonMapper +import com.imagekit.api.errors.ImageKitInvalidDataException +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.assertThrows +import org.junit.jupiter.params.ParameterizedTest +import org.junit.jupiter.params.provider.EnumSource + +internal class OriginRequestTest { + + @Test + fun ofS3() { + val s3 = + OriginRequest.S3.builder() + .accessKey("AKIAIOSFODNN7EXAMPLE") + .bucket("product-images") + .name("US S3 Storage") + .secretKey("wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY") + .baseUrlForCanonicalHeader("https://cdn.example.com") + .includeCanonicalHeader(false) + .prefix("raw-assets") + .build() + + val originRequest = OriginRequest.ofS3(s3) + + assertThat(originRequest.s3()).contains(s3) + assertThat(originRequest.s3Compatible()).isEmpty + assertThat(originRequest.cloudinaryBackup()).isEmpty + assertThat(originRequest.webFolder()).isEmpty + assertThat(originRequest.webProxy()).isEmpty + assertThat(originRequest.gcs()).isEmpty + assertThat(originRequest.azureBlob()).isEmpty + assertThat(originRequest.akeneoPim()).isEmpty + } + + @Test + fun ofS3Roundtrip() { + val jsonMapper = jsonMapper() + val originRequest = + OriginRequest.ofS3( + OriginRequest.S3.builder() + .accessKey("AKIAIOSFODNN7EXAMPLE") + .bucket("product-images") + .name("US S3 Storage") + .secretKey("wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY") + .baseUrlForCanonicalHeader("https://cdn.example.com") + .includeCanonicalHeader(false) + .prefix("raw-assets") + .build() + ) + + val roundtrippedOriginRequest = + jsonMapper.readValue( + jsonMapper.writeValueAsString(originRequest), + jacksonTypeRef(), + ) + + assertThat(roundtrippedOriginRequest).isEqualTo(originRequest) + } + + @Test + fun ofS3Compatible() { + val s3Compatible = + OriginRequest.S3Compatible.builder() + .accessKey("AKIAIOSFODNN7EXAMPLE") + .bucket("product-images") + .endpoint("https://s3.eu-central-1.wasabisys.com") + .name("US S3 Storage") + .secretKey("wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY") + .baseUrlForCanonicalHeader("https://cdn.example.com") + .includeCanonicalHeader(false) + .prefix("raw-assets") + .s3ForcePathStyle(true) + .build() + + val originRequest = OriginRequest.ofS3Compatible(s3Compatible) + + assertThat(originRequest.s3()).isEmpty + assertThat(originRequest.s3Compatible()).contains(s3Compatible) + assertThat(originRequest.cloudinaryBackup()).isEmpty + assertThat(originRequest.webFolder()).isEmpty + assertThat(originRequest.webProxy()).isEmpty + assertThat(originRequest.gcs()).isEmpty + assertThat(originRequest.azureBlob()).isEmpty + assertThat(originRequest.akeneoPim()).isEmpty + } + + @Test + fun ofS3CompatibleRoundtrip() { + val jsonMapper = jsonMapper() + val originRequest = + OriginRequest.ofS3Compatible( + OriginRequest.S3Compatible.builder() + .accessKey("AKIAIOSFODNN7EXAMPLE") + .bucket("product-images") + .endpoint("https://s3.eu-central-1.wasabisys.com") + .name("US S3 Storage") + .secretKey("wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY") + .baseUrlForCanonicalHeader("https://cdn.example.com") + .includeCanonicalHeader(false) + .prefix("raw-assets") + .s3ForcePathStyle(true) + .build() + ) + + val roundtrippedOriginRequest = + jsonMapper.readValue( + jsonMapper.writeValueAsString(originRequest), + jacksonTypeRef(), + ) + + assertThat(roundtrippedOriginRequest).isEqualTo(originRequest) + } + + @Test + fun ofCloudinaryBackup() { + val cloudinaryBackup = + OriginRequest.CloudinaryBackup.builder() + .accessKey("AKIAIOSFODNN7EXAMPLE") + .bucket("product-images") + .name("US S3 Storage") + .secretKey("wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY") + .baseUrlForCanonicalHeader("https://cdn.example.com") + .includeCanonicalHeader(false) + .prefix("raw-assets") + .build() + + val originRequest = OriginRequest.ofCloudinaryBackup(cloudinaryBackup) + + assertThat(originRequest.s3()).isEmpty + assertThat(originRequest.s3Compatible()).isEmpty + assertThat(originRequest.cloudinaryBackup()).contains(cloudinaryBackup) + assertThat(originRequest.webFolder()).isEmpty + assertThat(originRequest.webProxy()).isEmpty + assertThat(originRequest.gcs()).isEmpty + assertThat(originRequest.azureBlob()).isEmpty + assertThat(originRequest.akeneoPim()).isEmpty + } + + @Test + fun ofCloudinaryBackupRoundtrip() { + val jsonMapper = jsonMapper() + val originRequest = + OriginRequest.ofCloudinaryBackup( + OriginRequest.CloudinaryBackup.builder() + .accessKey("AKIAIOSFODNN7EXAMPLE") + .bucket("product-images") + .name("US S3 Storage") + .secretKey("wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY") + .baseUrlForCanonicalHeader("https://cdn.example.com") + .includeCanonicalHeader(false) + .prefix("raw-assets") + .build() + ) + + val roundtrippedOriginRequest = + jsonMapper.readValue( + jsonMapper.writeValueAsString(originRequest), + jacksonTypeRef(), + ) + + assertThat(roundtrippedOriginRequest).isEqualTo(originRequest) + } + + @Test + fun ofWebFolder() { + val webFolder = + OriginRequest.WebFolder.builder() + .baseUrl("https://images.example.com/assets") + .name("US S3 Storage") + .baseUrlForCanonicalHeader("https://cdn.example.com") + .forwardHostHeaderToOrigin(false) + .includeCanonicalHeader(false) + .build() + + val originRequest = OriginRequest.ofWebFolder(webFolder) + + assertThat(originRequest.s3()).isEmpty + assertThat(originRequest.s3Compatible()).isEmpty + assertThat(originRequest.cloudinaryBackup()).isEmpty + assertThat(originRequest.webFolder()).contains(webFolder) + assertThat(originRequest.webProxy()).isEmpty + assertThat(originRequest.gcs()).isEmpty + assertThat(originRequest.azureBlob()).isEmpty + assertThat(originRequest.akeneoPim()).isEmpty + } + + @Test + fun ofWebFolderRoundtrip() { + val jsonMapper = jsonMapper() + val originRequest = + OriginRequest.ofWebFolder( + OriginRequest.WebFolder.builder() + .baseUrl("https://images.example.com/assets") + .name("US S3 Storage") + .baseUrlForCanonicalHeader("https://cdn.example.com") + .forwardHostHeaderToOrigin(false) + .includeCanonicalHeader(false) + .build() + ) + + val roundtrippedOriginRequest = + jsonMapper.readValue( + jsonMapper.writeValueAsString(originRequest), + jacksonTypeRef(), + ) + + assertThat(roundtrippedOriginRequest).isEqualTo(originRequest) + } + + @Test + fun ofWebProxy() { + val webProxy = + OriginRequest.WebProxy.builder() + .name("US S3 Storage") + .baseUrlForCanonicalHeader("https://cdn.example.com") + .includeCanonicalHeader(false) + .build() + + val originRequest = OriginRequest.ofWebProxy(webProxy) + + assertThat(originRequest.s3()).isEmpty + assertThat(originRequest.s3Compatible()).isEmpty + assertThat(originRequest.cloudinaryBackup()).isEmpty + assertThat(originRequest.webFolder()).isEmpty + assertThat(originRequest.webProxy()).contains(webProxy) + assertThat(originRequest.gcs()).isEmpty + assertThat(originRequest.azureBlob()).isEmpty + assertThat(originRequest.akeneoPim()).isEmpty + } + + @Test + fun ofWebProxyRoundtrip() { + val jsonMapper = jsonMapper() + val originRequest = + OriginRequest.ofWebProxy( + OriginRequest.WebProxy.builder() + .name("US S3 Storage") + .baseUrlForCanonicalHeader("https://cdn.example.com") + .includeCanonicalHeader(false) + .build() + ) + + val roundtrippedOriginRequest = + jsonMapper.readValue( + jsonMapper.writeValueAsString(originRequest), + jacksonTypeRef(), + ) + + assertThat(roundtrippedOriginRequest).isEqualTo(originRequest) + } + + @Test + fun ofGcs() { + val gcs = + OriginRequest.Gcs.builder() + .bucket("gcs-media") + .clientEmail("service-account@project.iam.gserviceaccount.com") + .name("US S3 Storage") + .privateKey("-----BEGIN PRIVATE KEY-----\\nMIIEv...") + .baseUrlForCanonicalHeader("https://cdn.example.com") + .includeCanonicalHeader(false) + .prefix("products") + .build() + + val originRequest = OriginRequest.ofGcs(gcs) + + assertThat(originRequest.s3()).isEmpty + assertThat(originRequest.s3Compatible()).isEmpty + assertThat(originRequest.cloudinaryBackup()).isEmpty + assertThat(originRequest.webFolder()).isEmpty + assertThat(originRequest.webProxy()).isEmpty + assertThat(originRequest.gcs()).contains(gcs) + assertThat(originRequest.azureBlob()).isEmpty + assertThat(originRequest.akeneoPim()).isEmpty + } + + @Test + fun ofGcsRoundtrip() { + val jsonMapper = jsonMapper() + val originRequest = + OriginRequest.ofGcs( + OriginRequest.Gcs.builder() + .bucket("gcs-media") + .clientEmail("service-account@project.iam.gserviceaccount.com") + .name("US S3 Storage") + .privateKey("-----BEGIN PRIVATE KEY-----\\nMIIEv...") + .baseUrlForCanonicalHeader("https://cdn.example.com") + .includeCanonicalHeader(false) + .prefix("products") + .build() + ) + + val roundtrippedOriginRequest = + jsonMapper.readValue( + jsonMapper.writeValueAsString(originRequest), + jacksonTypeRef(), + ) + + assertThat(roundtrippedOriginRequest).isEqualTo(originRequest) + } + + @Test + fun ofAzureBlob() { + val azureBlob = + OriginRequest.AzureBlob.builder() + .accountName("account123") + .container("images") + .name("US S3 Storage") + .sasToken("?sv=2023-01-03&sr=c&sig=abc123") + .baseUrlForCanonicalHeader("https://cdn.example.com") + .includeCanonicalHeader(false) + .prefix("uploads") + .build() + + val originRequest = OriginRequest.ofAzureBlob(azureBlob) + + assertThat(originRequest.s3()).isEmpty + assertThat(originRequest.s3Compatible()).isEmpty + assertThat(originRequest.cloudinaryBackup()).isEmpty + assertThat(originRequest.webFolder()).isEmpty + assertThat(originRequest.webProxy()).isEmpty + assertThat(originRequest.gcs()).isEmpty + assertThat(originRequest.azureBlob()).contains(azureBlob) + assertThat(originRequest.akeneoPim()).isEmpty + } + + @Test + fun ofAzureBlobRoundtrip() { + val jsonMapper = jsonMapper() + val originRequest = + OriginRequest.ofAzureBlob( + OriginRequest.AzureBlob.builder() + .accountName("account123") + .container("images") + .name("US S3 Storage") + .sasToken("?sv=2023-01-03&sr=c&sig=abc123") + .baseUrlForCanonicalHeader("https://cdn.example.com") + .includeCanonicalHeader(false) + .prefix("uploads") + .build() + ) + + val roundtrippedOriginRequest = + jsonMapper.readValue( + jsonMapper.writeValueAsString(originRequest), + jacksonTypeRef(), + ) + + assertThat(roundtrippedOriginRequest).isEqualTo(originRequest) + } + + @Test + fun ofAkeneoPim() { + val akeneoPim = + OriginRequest.AkeneoPim.builder() + .baseUrl("https://akeneo.company.com") + .clientId("akeneo-client-id") + .clientSecret("akeneo-client-secret") + .name("US S3 Storage") + .password("strongpassword123") + .username("integration-user") + .baseUrlForCanonicalHeader("https://cdn.example.com") + .includeCanonicalHeader(false) + .build() + + val originRequest = OriginRequest.ofAkeneoPim(akeneoPim) + + assertThat(originRequest.s3()).isEmpty + assertThat(originRequest.s3Compatible()).isEmpty + assertThat(originRequest.cloudinaryBackup()).isEmpty + assertThat(originRequest.webFolder()).isEmpty + assertThat(originRequest.webProxy()).isEmpty + assertThat(originRequest.gcs()).isEmpty + assertThat(originRequest.azureBlob()).isEmpty + assertThat(originRequest.akeneoPim()).contains(akeneoPim) + } + + @Test + fun ofAkeneoPimRoundtrip() { + val jsonMapper = jsonMapper() + val originRequest = + OriginRequest.ofAkeneoPim( + OriginRequest.AkeneoPim.builder() + .baseUrl("https://akeneo.company.com") + .clientId("akeneo-client-id") + .clientSecret("akeneo-client-secret") + .name("US S3 Storage") + .password("strongpassword123") + .username("integration-user") + .baseUrlForCanonicalHeader("https://cdn.example.com") + .includeCanonicalHeader(false) + .build() + ) + + val roundtrippedOriginRequest = + jsonMapper.readValue( + jsonMapper.writeValueAsString(originRequest), + jacksonTypeRef(), + ) + + assertThat(roundtrippedOriginRequest).isEqualTo(originRequest) + } + + enum class IncompatibleJsonShapeTestCase(val value: JsonValue) { + BOOLEAN(JsonValue.from(false)), + STRING(JsonValue.from("invalid")), + INTEGER(JsonValue.from(-1)), + FLOAT(JsonValue.from(3.14)), + ARRAY(JsonValue.from(listOf("invalid", "array"))), + } + + @ParameterizedTest + @EnumSource + fun incompatibleJsonShapeDeserializesToUnknown(testCase: IncompatibleJsonShapeTestCase) { + val originRequest = + jsonMapper().convertValue(testCase.value, jacksonTypeRef()) + + val e = assertThrows { originRequest.validate() } + assertThat(e).hasMessageStartingWith("Unknown ") + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/accounts/origins/OriginResponseTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/accounts/origins/OriginResponseTest.kt new file mode 100644 index 0000000..da0a393 --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/accounts/origins/OriginResponseTest.kt @@ -0,0 +1,420 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.accounts.origins + +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.imagekit.api.core.JsonValue +import com.imagekit.api.core.jsonMapper +import com.imagekit.api.errors.ImageKitInvalidDataException +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.assertThrows +import org.junit.jupiter.params.ParameterizedTest +import org.junit.jupiter.params.provider.EnumSource + +internal class OriginResponseTest { + + @Test + fun ofS3() { + val s3 = + OriginResponse.S3.builder() + .id("id") + .bucket("product-images") + .includeCanonicalHeader(false) + .name("US S3 Storage") + .prefix("raw-assets") + .baseUrlForCanonicalHeader("https://cdn.example.com") + .build() + + val originResponse = OriginResponse.ofS3(s3) + + assertThat(originResponse.s3()).contains(s3) + assertThat(originResponse.s3Compatible()).isEmpty + assertThat(originResponse.cloudinaryBackup()).isEmpty + assertThat(originResponse.webFolder()).isEmpty + assertThat(originResponse.webProxy()).isEmpty + assertThat(originResponse.gcs()).isEmpty + assertThat(originResponse.azureBlob()).isEmpty + assertThat(originResponse.akeneoPim()).isEmpty + } + + @Test + fun ofS3Roundtrip() { + val jsonMapper = jsonMapper() + val originResponse = + OriginResponse.ofS3( + OriginResponse.S3.builder() + .id("id") + .bucket("product-images") + .includeCanonicalHeader(false) + .name("US S3 Storage") + .prefix("raw-assets") + .baseUrlForCanonicalHeader("https://cdn.example.com") + .build() + ) + + val roundtrippedOriginResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(originResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedOriginResponse).isEqualTo(originResponse) + } + + @Test + fun ofS3Compatible() { + val s3Compatible = + OriginResponse.S3Compatible.builder() + .id("id") + .bucket("product-images") + .endpoint("https://s3.eu-central-1.wasabisys.com") + .includeCanonicalHeader(false) + .name("US S3 Storage") + .prefix("raw-assets") + .s3ForcePathStyle(true) + .baseUrlForCanonicalHeader("https://cdn.example.com") + .build() + + val originResponse = OriginResponse.ofS3Compatible(s3Compatible) + + assertThat(originResponse.s3()).isEmpty + assertThat(originResponse.s3Compatible()).contains(s3Compatible) + assertThat(originResponse.cloudinaryBackup()).isEmpty + assertThat(originResponse.webFolder()).isEmpty + assertThat(originResponse.webProxy()).isEmpty + assertThat(originResponse.gcs()).isEmpty + assertThat(originResponse.azureBlob()).isEmpty + assertThat(originResponse.akeneoPim()).isEmpty + } + + @Test + fun ofS3CompatibleRoundtrip() { + val jsonMapper = jsonMapper() + val originResponse = + OriginResponse.ofS3Compatible( + OriginResponse.S3Compatible.builder() + .id("id") + .bucket("product-images") + .endpoint("https://s3.eu-central-1.wasabisys.com") + .includeCanonicalHeader(false) + .name("US S3 Storage") + .prefix("raw-assets") + .s3ForcePathStyle(true) + .baseUrlForCanonicalHeader("https://cdn.example.com") + .build() + ) + + val roundtrippedOriginResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(originResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedOriginResponse).isEqualTo(originResponse) + } + + @Test + fun ofCloudinaryBackup() { + val cloudinaryBackup = + OriginResponse.CloudinaryBackup.builder() + .id("id") + .bucket("product-images") + .includeCanonicalHeader(false) + .name("US S3 Storage") + .prefix("raw-assets") + .baseUrlForCanonicalHeader("https://cdn.example.com") + .build() + + val originResponse = OriginResponse.ofCloudinaryBackup(cloudinaryBackup) + + assertThat(originResponse.s3()).isEmpty + assertThat(originResponse.s3Compatible()).isEmpty + assertThat(originResponse.cloudinaryBackup()).contains(cloudinaryBackup) + assertThat(originResponse.webFolder()).isEmpty + assertThat(originResponse.webProxy()).isEmpty + assertThat(originResponse.gcs()).isEmpty + assertThat(originResponse.azureBlob()).isEmpty + assertThat(originResponse.akeneoPim()).isEmpty + } + + @Test + fun ofCloudinaryBackupRoundtrip() { + val jsonMapper = jsonMapper() + val originResponse = + OriginResponse.ofCloudinaryBackup( + OriginResponse.CloudinaryBackup.builder() + .id("id") + .bucket("product-images") + .includeCanonicalHeader(false) + .name("US S3 Storage") + .prefix("raw-assets") + .baseUrlForCanonicalHeader("https://cdn.example.com") + .build() + ) + + val roundtrippedOriginResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(originResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedOriginResponse).isEqualTo(originResponse) + } + + @Test + fun ofWebFolder() { + val webFolder = + OriginResponse.WebFolder.builder() + .id("id") + .baseUrl("https://images.example.com/assets") + .forwardHostHeaderToOrigin(false) + .includeCanonicalHeader(false) + .name("US S3 Storage") + .baseUrlForCanonicalHeader("https://cdn.example.com") + .build() + + val originResponse = OriginResponse.ofWebFolder(webFolder) + + assertThat(originResponse.s3()).isEmpty + assertThat(originResponse.s3Compatible()).isEmpty + assertThat(originResponse.cloudinaryBackup()).isEmpty + assertThat(originResponse.webFolder()).contains(webFolder) + assertThat(originResponse.webProxy()).isEmpty + assertThat(originResponse.gcs()).isEmpty + assertThat(originResponse.azureBlob()).isEmpty + assertThat(originResponse.akeneoPim()).isEmpty + } + + @Test + fun ofWebFolderRoundtrip() { + val jsonMapper = jsonMapper() + val originResponse = + OriginResponse.ofWebFolder( + OriginResponse.WebFolder.builder() + .id("id") + .baseUrl("https://images.example.com/assets") + .forwardHostHeaderToOrigin(false) + .includeCanonicalHeader(false) + .name("US S3 Storage") + .baseUrlForCanonicalHeader("https://cdn.example.com") + .build() + ) + + val roundtrippedOriginResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(originResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedOriginResponse).isEqualTo(originResponse) + } + + @Test + fun ofWebProxy() { + val webProxy = + OriginResponse.WebProxy.builder() + .id("id") + .includeCanonicalHeader(false) + .name("US S3 Storage") + .baseUrlForCanonicalHeader("https://cdn.example.com") + .build() + + val originResponse = OriginResponse.ofWebProxy(webProxy) + + assertThat(originResponse.s3()).isEmpty + assertThat(originResponse.s3Compatible()).isEmpty + assertThat(originResponse.cloudinaryBackup()).isEmpty + assertThat(originResponse.webFolder()).isEmpty + assertThat(originResponse.webProxy()).contains(webProxy) + assertThat(originResponse.gcs()).isEmpty + assertThat(originResponse.azureBlob()).isEmpty + assertThat(originResponse.akeneoPim()).isEmpty + } + + @Test + fun ofWebProxyRoundtrip() { + val jsonMapper = jsonMapper() + val originResponse = + OriginResponse.ofWebProxy( + OriginResponse.WebProxy.builder() + .id("id") + .includeCanonicalHeader(false) + .name("US S3 Storage") + .baseUrlForCanonicalHeader("https://cdn.example.com") + .build() + ) + + val roundtrippedOriginResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(originResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedOriginResponse).isEqualTo(originResponse) + } + + @Test + fun ofGcs() { + val gcs = + OriginResponse.Gcs.builder() + .id("id") + .bucket("gcs-media") + .clientEmail("service-account@project.iam.gserviceaccount.com") + .includeCanonicalHeader(false) + .name("US S3 Storage") + .prefix("products") + .baseUrlForCanonicalHeader("https://cdn.example.com") + .build() + + val originResponse = OriginResponse.ofGcs(gcs) + + assertThat(originResponse.s3()).isEmpty + assertThat(originResponse.s3Compatible()).isEmpty + assertThat(originResponse.cloudinaryBackup()).isEmpty + assertThat(originResponse.webFolder()).isEmpty + assertThat(originResponse.webProxy()).isEmpty + assertThat(originResponse.gcs()).contains(gcs) + assertThat(originResponse.azureBlob()).isEmpty + assertThat(originResponse.akeneoPim()).isEmpty + } + + @Test + fun ofGcsRoundtrip() { + val jsonMapper = jsonMapper() + val originResponse = + OriginResponse.ofGcs( + OriginResponse.Gcs.builder() + .id("id") + .bucket("gcs-media") + .clientEmail("service-account@project.iam.gserviceaccount.com") + .includeCanonicalHeader(false) + .name("US S3 Storage") + .prefix("products") + .baseUrlForCanonicalHeader("https://cdn.example.com") + .build() + ) + + val roundtrippedOriginResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(originResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedOriginResponse).isEqualTo(originResponse) + } + + @Test + fun ofAzureBlob() { + val azureBlob = + OriginResponse.AzureBlob.builder() + .id("id") + .accountName("account123") + .container("images") + .includeCanonicalHeader(false) + .name("US S3 Storage") + .prefix("uploads") + .baseUrlForCanonicalHeader("https://cdn.example.com") + .build() + + val originResponse = OriginResponse.ofAzureBlob(azureBlob) + + assertThat(originResponse.s3()).isEmpty + assertThat(originResponse.s3Compatible()).isEmpty + assertThat(originResponse.cloudinaryBackup()).isEmpty + assertThat(originResponse.webFolder()).isEmpty + assertThat(originResponse.webProxy()).isEmpty + assertThat(originResponse.gcs()).isEmpty + assertThat(originResponse.azureBlob()).contains(azureBlob) + assertThat(originResponse.akeneoPim()).isEmpty + } + + @Test + fun ofAzureBlobRoundtrip() { + val jsonMapper = jsonMapper() + val originResponse = + OriginResponse.ofAzureBlob( + OriginResponse.AzureBlob.builder() + .id("id") + .accountName("account123") + .container("images") + .includeCanonicalHeader(false) + .name("US S3 Storage") + .prefix("uploads") + .baseUrlForCanonicalHeader("https://cdn.example.com") + .build() + ) + + val roundtrippedOriginResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(originResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedOriginResponse).isEqualTo(originResponse) + } + + @Test + fun ofAkeneoPim() { + val akeneoPim = + OriginResponse.AkeneoPim.builder() + .id("id") + .baseUrl("https://akeneo.company.com") + .includeCanonicalHeader(false) + .name("US S3 Storage") + .baseUrlForCanonicalHeader("https://cdn.example.com") + .build() + + val originResponse = OriginResponse.ofAkeneoPim(akeneoPim) + + assertThat(originResponse.s3()).isEmpty + assertThat(originResponse.s3Compatible()).isEmpty + assertThat(originResponse.cloudinaryBackup()).isEmpty + assertThat(originResponse.webFolder()).isEmpty + assertThat(originResponse.webProxy()).isEmpty + assertThat(originResponse.gcs()).isEmpty + assertThat(originResponse.azureBlob()).isEmpty + assertThat(originResponse.akeneoPim()).contains(akeneoPim) + } + + @Test + fun ofAkeneoPimRoundtrip() { + val jsonMapper = jsonMapper() + val originResponse = + OriginResponse.ofAkeneoPim( + OriginResponse.AkeneoPim.builder() + .id("id") + .baseUrl("https://akeneo.company.com") + .includeCanonicalHeader(false) + .name("US S3 Storage") + .baseUrlForCanonicalHeader("https://cdn.example.com") + .build() + ) + + val roundtrippedOriginResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(originResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedOriginResponse).isEqualTo(originResponse) + } + + enum class IncompatibleJsonShapeTestCase(val value: JsonValue) { + BOOLEAN(JsonValue.from(false)), + STRING(JsonValue.from("invalid")), + INTEGER(JsonValue.from(-1)), + FLOAT(JsonValue.from(3.14)), + ARRAY(JsonValue.from(listOf("invalid", "array"))), + } + + @ParameterizedTest + @EnumSource + fun incompatibleJsonShapeDeserializesToUnknown(testCase: IncompatibleJsonShapeTestCase) { + val originResponse = + jsonMapper().convertValue(testCase.value, jacksonTypeRef()) + + val e = assertThrows { originResponse.validate() } + assertThat(e).hasMessageStartingWith("Unknown ") + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/accounts/origins/OriginUpdateParamsTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/accounts/origins/OriginUpdateParamsTest.kt new file mode 100644 index 0000000..d90d8cc --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/accounts/origins/OriginUpdateParamsTest.kt @@ -0,0 +1,113 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.accounts.origins + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class OriginUpdateParamsTest { + + @Test + fun create() { + OriginUpdateParams.builder() + .id("id") + .originRequest( + OriginRequest.S3.builder() + .accessKey("AKIATEST123") + .bucket("test-bucket") + .name("My S3 Origin") + .secretKey("secrettest123") + .baseUrlForCanonicalHeader("https://cdn.example.com") + .includeCanonicalHeader(false) + .prefix("images") + .build() + ) + .build() + } + + @Test + fun pathParams() { + val params = + OriginUpdateParams.builder() + .id("id") + .originRequest( + OriginRequest.S3.builder() + .accessKey("AKIATEST123") + .bucket("test-bucket") + .name("My S3 Origin") + .secretKey("secrettest123") + .build() + ) + .build() + + assertThat(params._pathParam(0)).isEqualTo("id") + // out-of-bound path param + assertThat(params._pathParam(1)).isEqualTo("") + } + + @Test + fun body() { + val params = + OriginUpdateParams.builder() + .id("id") + .originRequest( + OriginRequest.S3.builder() + .accessKey("AKIATEST123") + .bucket("test-bucket") + .name("My S3 Origin") + .secretKey("secrettest123") + .baseUrlForCanonicalHeader("https://cdn.example.com") + .includeCanonicalHeader(false) + .prefix("images") + .build() + ) + .build() + + val body = params._body() + + assertThat(body) + .isEqualTo( + OriginRequest.ofS3( + OriginRequest.S3.builder() + .accessKey("AKIATEST123") + .bucket("test-bucket") + .name("My S3 Origin") + .secretKey("secrettest123") + .baseUrlForCanonicalHeader("https://cdn.example.com") + .includeCanonicalHeader(false) + .prefix("images") + .build() + ) + ) + } + + @Test + fun bodyWithoutOptionalFields() { + val params = + OriginUpdateParams.builder() + .id("id") + .originRequest( + OriginRequest.S3.builder() + .accessKey("AKIATEST123") + .bucket("test-bucket") + .name("My S3 Origin") + .secretKey("secrettest123") + .build() + ) + .build() + + val body = params._body() + + assertThat(body) + .isEqualTo( + OriginRequest.ofS3( + OriginRequest.S3.builder() + .accessKey("AKIATEST123") + .bucket("test-bucket") + .name("My S3 Origin") + .secretKey("secrettest123") + .build() + ) + ) + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/accounts/urlendpoints/UrlEndpointCreateParamsTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/accounts/urlendpoints/UrlEndpointCreateParamsTest.kt new file mode 100644 index 0000000..93293ea --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/accounts/urlendpoints/UrlEndpointCreateParamsTest.kt @@ -0,0 +1,77 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.accounts.urlendpoints + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class UrlEndpointCreateParamsTest { + + @Test + fun create() { + UrlEndpointCreateParams.builder() + .urlEndpointRequest( + UrlEndpointRequest.builder() + .description("My custom URL endpoint") + .addOrigin("origin-id-1") + .urlPrefix("product-images") + .urlRewriter( + UrlEndpointRequest.UrlRewriter.Cloudinary.builder() + .preserveAssetDeliveryTypes(true) + .build() + ) + .build() + ) + .build() + } + + @Test + fun body() { + val params = + UrlEndpointCreateParams.builder() + .urlEndpointRequest( + UrlEndpointRequest.builder() + .description("My custom URL endpoint") + .addOrigin("origin-id-1") + .urlPrefix("product-images") + .urlRewriter( + UrlEndpointRequest.UrlRewriter.Cloudinary.builder() + .preserveAssetDeliveryTypes(true) + .build() + ) + .build() + ) + .build() + + val body = params._body() + + assertThat(body) + .isEqualTo( + UrlEndpointRequest.builder() + .description("My custom URL endpoint") + .addOrigin("origin-id-1") + .urlPrefix("product-images") + .urlRewriter( + UrlEndpointRequest.UrlRewriter.Cloudinary.builder() + .preserveAssetDeliveryTypes(true) + .build() + ) + .build() + ) + } + + @Test + fun bodyWithoutOptionalFields() { + val params = + UrlEndpointCreateParams.builder() + .urlEndpointRequest( + UrlEndpointRequest.builder().description("My custom URL endpoint").build() + ) + .build() + + val body = params._body() + + assertThat(body) + .isEqualTo(UrlEndpointRequest.builder().description("My custom URL endpoint").build()) + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/accounts/urlendpoints/UrlEndpointDeleteParamsTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/accounts/urlendpoints/UrlEndpointDeleteParamsTest.kt new file mode 100644 index 0000000..180ae83 --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/accounts/urlendpoints/UrlEndpointDeleteParamsTest.kt @@ -0,0 +1,23 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.accounts.urlendpoints + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class UrlEndpointDeleteParamsTest { + + @Test + fun create() { + UrlEndpointDeleteParams.builder().id("id").build() + } + + @Test + fun pathParams() { + val params = UrlEndpointDeleteParams.builder().id("id").build() + + assertThat(params._pathParam(0)).isEqualTo("id") + // out-of-bound path param + assertThat(params._pathParam(1)).isEqualTo("") + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/accounts/urlendpoints/UrlEndpointGetParamsTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/accounts/urlendpoints/UrlEndpointGetParamsTest.kt new file mode 100644 index 0000000..8385155 --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/accounts/urlendpoints/UrlEndpointGetParamsTest.kt @@ -0,0 +1,23 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.accounts.urlendpoints + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class UrlEndpointGetParamsTest { + + @Test + fun create() { + UrlEndpointGetParams.builder().id("id").build() + } + + @Test + fun pathParams() { + val params = UrlEndpointGetParams.builder().id("id").build() + + assertThat(params._pathParam(0)).isEqualTo("id") + // out-of-bound path param + assertThat(params._pathParam(1)).isEqualTo("") + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/accounts/urlendpoints/UrlEndpointListParamsTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/accounts/urlendpoints/UrlEndpointListParamsTest.kt new file mode 100644 index 0000000..0aa9b74 --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/accounts/urlendpoints/UrlEndpointListParamsTest.kt @@ -0,0 +1,13 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.accounts.urlendpoints + +import org.junit.jupiter.api.Test + +internal class UrlEndpointListParamsTest { + + @Test + fun create() { + UrlEndpointListParams.builder().build() + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/accounts/urlendpoints/UrlEndpointRequestTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/accounts/urlendpoints/UrlEndpointRequestTest.kt new file mode 100644 index 0000000..7c2de87 --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/accounts/urlendpoints/UrlEndpointRequestTest.kt @@ -0,0 +1,63 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.accounts.urlendpoints + +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.imagekit.api.core.jsonMapper +import kotlin.jvm.optionals.getOrNull +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class UrlEndpointRequestTest { + + @Test + fun create() { + val urlEndpointRequest = + UrlEndpointRequest.builder() + .description("My custom URL endpoint") + .addOrigin("origin-id-1") + .urlPrefix("product-images") + .urlRewriter( + UrlEndpointRequest.UrlRewriter.Cloudinary.builder() + .preserveAssetDeliveryTypes(true) + .build() + ) + .build() + + assertThat(urlEndpointRequest.description()).isEqualTo("My custom URL endpoint") + assertThat(urlEndpointRequest.origins().getOrNull()).containsExactly("origin-id-1") + assertThat(urlEndpointRequest.urlPrefix()).contains("product-images") + assertThat(urlEndpointRequest.urlRewriter()) + .contains( + UrlEndpointRequest.UrlRewriter.ofCloudinary( + UrlEndpointRequest.UrlRewriter.Cloudinary.builder() + .preserveAssetDeliveryTypes(true) + .build() + ) + ) + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val urlEndpointRequest = + UrlEndpointRequest.builder() + .description("My custom URL endpoint") + .addOrigin("origin-id-1") + .urlPrefix("product-images") + .urlRewriter( + UrlEndpointRequest.UrlRewriter.Cloudinary.builder() + .preserveAssetDeliveryTypes(true) + .build() + ) + .build() + + val roundtrippedUrlEndpointRequest = + jsonMapper.readValue( + jsonMapper.writeValueAsString(urlEndpointRequest), + jacksonTypeRef(), + ) + + assertThat(roundtrippedUrlEndpointRequest).isEqualTo(urlEndpointRequest) + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/accounts/urlendpoints/UrlEndpointResponseTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/accounts/urlendpoints/UrlEndpointResponseTest.kt new file mode 100644 index 0000000..fa5854c --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/accounts/urlendpoints/UrlEndpointResponseTest.kt @@ -0,0 +1,59 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.accounts.urlendpoints + +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.imagekit.api.core.jsonMapper +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class UrlEndpointResponseTest { + + @Test + fun create() { + val urlEndpointResponse = + UrlEndpointResponse.builder() + .id("id") + .description("My custom URL endpoint") + .addOrigin("origin-id-1") + .addOrigin("origin-id-2") + .urlPrefix("product-images") + .cloudinaryUrlRewriter(true) + .build() + + assertThat(urlEndpointResponse.id()).isEqualTo("id") + assertThat(urlEndpointResponse.description()).isEqualTo("My custom URL endpoint") + assertThat(urlEndpointResponse.origins()).containsExactly("origin-id-1", "origin-id-2") + assertThat(urlEndpointResponse.urlPrefix()).isEqualTo("product-images") + assertThat(urlEndpointResponse.urlRewriter()) + .contains( + UrlEndpointResponse.UrlRewriter.ofCloudinary( + UrlEndpointResponse.UrlRewriter.Cloudinary.builder() + .preserveAssetDeliveryTypes(true) + .build() + ) + ) + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val urlEndpointResponse = + UrlEndpointResponse.builder() + .id("id") + .description("My custom URL endpoint") + .addOrigin("origin-id-1") + .addOrigin("origin-id-2") + .urlPrefix("product-images") + .cloudinaryUrlRewriter(true) + .build() + + val roundtrippedUrlEndpointResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(urlEndpointResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedUrlEndpointResponse).isEqualTo(urlEndpointResponse) + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/accounts/urlendpoints/UrlEndpointUpdateParamsTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/accounts/urlendpoints/UrlEndpointUpdateParamsTest.kt new file mode 100644 index 0000000..434647b --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/accounts/urlendpoints/UrlEndpointUpdateParamsTest.kt @@ -0,0 +1,95 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.accounts.urlendpoints + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class UrlEndpointUpdateParamsTest { + + @Test + fun create() { + UrlEndpointUpdateParams.builder() + .id("id") + .urlEndpointRequest( + UrlEndpointRequest.builder() + .description("My custom URL endpoint") + .addOrigin("origin-id-1") + .urlPrefix("product-images") + .urlRewriter( + UrlEndpointRequest.UrlRewriter.Cloudinary.builder() + .preserveAssetDeliveryTypes(true) + .build() + ) + .build() + ) + .build() + } + + @Test + fun pathParams() { + val params = + UrlEndpointUpdateParams.builder() + .id("id") + .urlEndpointRequest( + UrlEndpointRequest.builder().description("My custom URL endpoint").build() + ) + .build() + + assertThat(params._pathParam(0)).isEqualTo("id") + // out-of-bound path param + assertThat(params._pathParam(1)).isEqualTo("") + } + + @Test + fun body() { + val params = + UrlEndpointUpdateParams.builder() + .id("id") + .urlEndpointRequest( + UrlEndpointRequest.builder() + .description("My custom URL endpoint") + .addOrigin("origin-id-1") + .urlPrefix("product-images") + .urlRewriter( + UrlEndpointRequest.UrlRewriter.Cloudinary.builder() + .preserveAssetDeliveryTypes(true) + .build() + ) + .build() + ) + .build() + + val body = params._body() + + assertThat(body) + .isEqualTo( + UrlEndpointRequest.builder() + .description("My custom URL endpoint") + .addOrigin("origin-id-1") + .urlPrefix("product-images") + .urlRewriter( + UrlEndpointRequest.UrlRewriter.Cloudinary.builder() + .preserveAssetDeliveryTypes(true) + .build() + ) + .build() + ) + } + + @Test + fun bodyWithoutOptionalFields() { + val params = + UrlEndpointUpdateParams.builder() + .id("id") + .urlEndpointRequest( + UrlEndpointRequest.builder().description("My custom URL endpoint").build() + ) + .build() + + val body = params._body() + + assertThat(body) + .isEqualTo(UrlEndpointRequest.builder().description("My custom URL endpoint").build()) + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/accounts/usage/UsageGetParamsTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/accounts/usage/UsageGetParamsTest.kt new file mode 100644 index 0000000..260fb48 --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/accounts/usage/UsageGetParamsTest.kt @@ -0,0 +1,38 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.accounts.usage + +import com.imagekit.api.core.http.QueryParams +import java.time.LocalDate +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class UsageGetParamsTest { + + @Test + fun create() { + UsageGetParams.builder() + .endDate(LocalDate.parse("2019-12-27")) + .startDate(LocalDate.parse("2019-12-27")) + .build() + } + + @Test + fun queryParams() { + val params = + UsageGetParams.builder() + .endDate(LocalDate.parse("2019-12-27")) + .startDate(LocalDate.parse("2019-12-27")) + .build() + + val queryParams = params._queryParams() + + assertThat(queryParams) + .isEqualTo( + QueryParams.builder() + .put("endDate", "2019-12-27") + .put("startDate", "2019-12-27") + .build() + ) + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/accounts/usage/UsageGetResponseTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/accounts/usage/UsageGetResponseTest.kt new file mode 100644 index 0000000..c0b5123 --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/accounts/usage/UsageGetResponseTest.kt @@ -0,0 +1,50 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.accounts.usage + +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.imagekit.api.core.jsonMapper +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class UsageGetResponseTest { + + @Test + fun create() { + val usageGetResponse = + UsageGetResponse.builder() + .bandwidthBytes(0L) + .extensionUnitsCount(0L) + .mediaLibraryStorageBytes(0L) + .originalCacheStorageBytes(0L) + .videoProcessingUnitsCount(0L) + .build() + + assertThat(usageGetResponse.bandwidthBytes()).contains(0L) + assertThat(usageGetResponse.extensionUnitsCount()).contains(0L) + assertThat(usageGetResponse.mediaLibraryStorageBytes()).contains(0L) + assertThat(usageGetResponse.originalCacheStorageBytes()).contains(0L) + assertThat(usageGetResponse.videoProcessingUnitsCount()).contains(0L) + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val usageGetResponse = + UsageGetResponse.builder() + .bandwidthBytes(0L) + .extensionUnitsCount(0L) + .mediaLibraryStorageBytes(0L) + .originalCacheStorageBytes(0L) + .videoProcessingUnitsCount(0L) + .build() + + val roundtrippedUsageGetResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(usageGetResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedUsageGetResponse).isEqualTo(usageGetResponse) + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/assets/AssetListParamsTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/assets/AssetListParamsTest.kt new file mode 100644 index 0000000..711b9e1 --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/assets/AssetListParamsTest.kt @@ -0,0 +1,61 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.assets + +import com.imagekit.api.core.http.QueryParams +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class AssetListParamsTest { + + @Test + fun create() { + AssetListParams.builder() + .fileType(AssetListParams.FileType.ALL) + .limit(1L) + .path("path") + .searchQuery("searchQuery") + .skip(0L) + .sort(AssetListParams.Sort.ASC_NAME) + .type(AssetListParams.Type.FILE) + .build() + } + + @Test + fun queryParams() { + val params = + AssetListParams.builder() + .fileType(AssetListParams.FileType.ALL) + .limit(1L) + .path("path") + .searchQuery("searchQuery") + .skip(0L) + .sort(AssetListParams.Sort.ASC_NAME) + .type(AssetListParams.Type.FILE) + .build() + + val queryParams = params._queryParams() + + assertThat(queryParams) + .isEqualTo( + QueryParams.builder() + .put("fileType", "all") + .put("limit", "1") + .put("path", "path") + .put("searchQuery", "searchQuery") + .put("skip", "0") + .put("sort", "ASC_NAME") + .put("type", "file") + .build() + ) + } + + @Test + fun queryParamsWithoutOptionalFields() { + val params = AssetListParams.builder().build() + + val queryParams = params._queryParams() + + assertThat(queryParams).isEqualTo(QueryParams.builder().build()) + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/assets/AssetListResponseTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/assets/AssetListResponseTest.kt new file mode 100644 index 0000000..7089671 --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/assets/AssetListResponseTest.kt @@ -0,0 +1,165 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.assets + +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.imagekit.api.core.JsonValue +import com.imagekit.api.core.jsonMapper +import com.imagekit.api.errors.ImageKitInvalidDataException +import com.imagekit.api.models.files.File +import com.imagekit.api.models.files.Folder +import java.time.OffsetDateTime +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.assertThrows +import org.junit.jupiter.params.ParameterizedTest +import org.junit.jupiter.params.provider.EnumSource + +internal class AssetListResponseTest { + + @Test + fun ofFile() { + val file = + File.builder() + .addAiTag( + File.AiTag.builder().confidence(0.0).name("name").source("source").build() + ) + .createdAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .customCoordinates("customCoordinates") + .customMetadata( + File.CustomMetadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .description("description") + .fileId("fileId") + .filePath("filePath") + .fileType("fileType") + .hasAlpha(true) + .height(0.0) + .isPrivateFile(true) + .isPublished(true) + .mime("mime") + .name("name") + .size(0.0) + .addTag("string") + .thumbnail("https://example.com") + .type(File.Type.FILE) + .updatedAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .url("https://example.com") + .versionInfo(File.VersionInfo.builder().id("id").name("name").build()) + .width(0.0) + .build() + + val assetListResponse = AssetListResponse.ofFile(file) + + assertThat(assetListResponse.file()).contains(file) + assertThat(assetListResponse.folder()).isEmpty + } + + @Test + fun ofFileRoundtrip() { + val jsonMapper = jsonMapper() + val assetListResponse = + AssetListResponse.ofFile( + File.builder() + .addAiTag( + File.AiTag.builder().confidence(0.0).name("name").source("source").build() + ) + .createdAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .customCoordinates("customCoordinates") + .customMetadata( + File.CustomMetadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .description("description") + .fileId("fileId") + .filePath("filePath") + .fileType("fileType") + .hasAlpha(true) + .height(0.0) + .isPrivateFile(true) + .isPublished(true) + .mime("mime") + .name("name") + .size(0.0) + .addTag("string") + .thumbnail("https://example.com") + .type(File.Type.FILE) + .updatedAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .url("https://example.com") + .versionInfo(File.VersionInfo.builder().id("id").name("name").build()) + .width(0.0) + .build() + ) + + val roundtrippedAssetListResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(assetListResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedAssetListResponse).isEqualTo(assetListResponse) + } + + @Test + fun ofFolder() { + val folder = + Folder.builder() + .createdAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .folderId("folderId") + .folderPath("folderPath") + .name("name") + .type(Folder.Type.FOLDER) + .updatedAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .build() + + val assetListResponse = AssetListResponse.ofFolder(folder) + + assertThat(assetListResponse.file()).isEmpty + assertThat(assetListResponse.folder()).contains(folder) + } + + @Test + fun ofFolderRoundtrip() { + val jsonMapper = jsonMapper() + val assetListResponse = + AssetListResponse.ofFolder( + Folder.builder() + .createdAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .folderId("folderId") + .folderPath("folderPath") + .name("name") + .type(Folder.Type.FOLDER) + .updatedAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .build() + ) + + val roundtrippedAssetListResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(assetListResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedAssetListResponse).isEqualTo(assetListResponse) + } + + enum class IncompatibleJsonShapeTestCase(val value: JsonValue) { + BOOLEAN(JsonValue.from(false)), + STRING(JsonValue.from("invalid")), + INTEGER(JsonValue.from(-1)), + FLOAT(JsonValue.from(3.14)), + ARRAY(JsonValue.from(listOf("invalid", "array"))), + } + + @ParameterizedTest + @EnumSource + fun incompatibleJsonShapeDeserializesToUnknown(testCase: IncompatibleJsonShapeTestCase) { + val assetListResponse = + jsonMapper().convertValue(testCase.value, jacksonTypeRef()) + + val e = assertThrows { assetListResponse.validate() } + assertThat(e).hasMessageStartingWith("Unknown ") + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/beta/v2/files/FileUploadParamsTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/beta/v2/files/FileUploadParamsTest.kt new file mode 100644 index 0000000..abc2c34 --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/beta/v2/files/FileUploadParamsTest.kt @@ -0,0 +1,298 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.beta.v2.files + +import com.imagekit.api.core.JsonValue +import com.imagekit.api.core.MultipartField +import com.imagekit.api.models.UnnamedSchemaWithArrayParent3 +import java.io.InputStream +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class FileUploadParamsTest { + + @Test + fun create() { + FileUploadParams.builder() + .file("some content".byteInputStream()) + .fileName("fileName") + .token("token") + .checks("\"request.folder\" : \"marketing/\"\n") + .customCoordinates("customCoordinates") + .customMetadata( + FileUploadParams.CustomMetadata.builder() + .putAdditionalProperty("brand", JsonValue.from("bar")) + .putAdditionalProperty("color", JsonValue.from("bar")) + .build() + ) + .description("Running shoes") + .extensions( + listOf( + UnnamedSchemaWithArrayParent3.ofRemoveBg( + UnnamedSchemaWithArrayParent3.RemoveBg.builder() + .options( + UnnamedSchemaWithArrayParent3.RemoveBg.Options.builder() + .addShadow(true) + .bgColor("bg_color") + .bgImageUrl("bg_image_url") + .semitransparency(true) + .build() + ) + .build() + ), + UnnamedSchemaWithArrayParent3.ofAutoTaggingExtension( + UnnamedSchemaWithArrayParent3.AutoTaggingExtension.builder() + .maxTags(5L) + .minConfidence(95L) + .name( + UnnamedSchemaWithArrayParent3.AutoTaggingExtension.Name + .GOOGLE_AUTO_TAGGING + ) + .build() + ), + UnnamedSchemaWithArrayParent3.ofAiAutoDescription(), + ) + ) + .folder("folder") + .isPrivateFile(true) + .isPublished(true) + .overwriteAiTags(true) + .overwriteCustomMetadata(true) + .overwriteFile(true) + .overwriteTags(true) + .responseFields( + listOf( + FileUploadParams.ResponseField.TAGS, + FileUploadParams.ResponseField.CUSTOM_COORDINATES, + FileUploadParams.ResponseField.IS_PRIVATE_FILE, + ) + ) + .tags(listOf("t-shirt", "round-neck", "men")) + .transformation( + FileUploadParams.Transformation.builder() + .addPost( + FileUploadParams.Transformation.Post.Thumbnail.builder() + .value("w-150,h-150") + .build() + ) + .addPost( + FileUploadParams.Transformation.Post.Abs.builder() + .protocol(FileUploadParams.Transformation.Post.Abs.Protocol.DASH) + .value("sr-240_360_480_720_1080") + .build() + ) + .pre("w-300,h-300,q-80") + .build() + ) + .useUniqueFileName(true) + .webhookUrl("https://example.com") + .build() + } + + @Test + fun body() { + val params = + FileUploadParams.builder() + .file("some content".byteInputStream()) + .fileName("fileName") + .token("token") + .checks("\"request.folder\" : \"marketing/\"\n") + .customCoordinates("customCoordinates") + .customMetadata( + FileUploadParams.CustomMetadata.builder() + .putAdditionalProperty("brand", JsonValue.from("bar")) + .putAdditionalProperty("color", JsonValue.from("bar")) + .build() + ) + .description("Running shoes") + .extensions( + listOf( + UnnamedSchemaWithArrayParent3.ofRemoveBg( + UnnamedSchemaWithArrayParent3.RemoveBg.builder() + .options( + UnnamedSchemaWithArrayParent3.RemoveBg.Options.builder() + .addShadow(true) + .bgColor("bg_color") + .bgImageUrl("bg_image_url") + .semitransparency(true) + .build() + ) + .build() + ), + UnnamedSchemaWithArrayParent3.ofAutoTaggingExtension( + UnnamedSchemaWithArrayParent3.AutoTaggingExtension.builder() + .maxTags(5L) + .minConfidence(95L) + .name( + UnnamedSchemaWithArrayParent3.AutoTaggingExtension.Name + .GOOGLE_AUTO_TAGGING + ) + .build() + ), + UnnamedSchemaWithArrayParent3.ofAiAutoDescription(), + ) + ) + .folder("folder") + .isPrivateFile(true) + .isPublished(true) + .overwriteAiTags(true) + .overwriteCustomMetadata(true) + .overwriteFile(true) + .overwriteTags(true) + .responseFields( + listOf( + FileUploadParams.ResponseField.TAGS, + FileUploadParams.ResponseField.CUSTOM_COORDINATES, + FileUploadParams.ResponseField.IS_PRIVATE_FILE, + ) + ) + .tags(listOf("t-shirt", "round-neck", "men")) + .transformation( + FileUploadParams.Transformation.builder() + .addPost( + FileUploadParams.Transformation.Post.Thumbnail.builder() + .value("w-150,h-150") + .build() + ) + .addPost( + FileUploadParams.Transformation.Post.Abs.builder() + .protocol(FileUploadParams.Transformation.Post.Abs.Protocol.DASH) + .value("sr-240_360_480_720_1080") + .build() + ) + .pre("w-300,h-300,q-80") + .build() + ) + .useUniqueFileName(true) + .webhookUrl("https://example.com") + .build() + + val body = params._body() + + assertThat(body.filterValues { !it.value.isNull() }) + .usingRecursiveComparison() + // TODO(AssertJ): Replace this and the `mapValues` below with: + // https://github.com/assertj/assertj/issues/3165 + .withEqualsForType( + { a, b -> a.readBytes() contentEquals b.readBytes() }, + InputStream::class.java, + ) + .isEqualTo( + mapOf( + "file" to MultipartField.of("some content".byteInputStream()), + "fileName" to MultipartField.of("fileName"), + "token" to MultipartField.of("token"), + "checks" to MultipartField.of("\"request.folder\" : \"marketing/\"\n"), + "customCoordinates" to MultipartField.of("customCoordinates"), + "customMetadata" to + MultipartField.of( + FileUploadParams.CustomMetadata.builder() + .putAdditionalProperty("brand", JsonValue.from("bar")) + .putAdditionalProperty("color", JsonValue.from("bar")) + .build() + ), + "description" to MultipartField.of("Running shoes"), + "extensions" to + MultipartField.of( + listOf( + UnnamedSchemaWithArrayParent3.ofRemoveBg( + UnnamedSchemaWithArrayParent3.RemoveBg.builder() + .options( + UnnamedSchemaWithArrayParent3.RemoveBg.Options + .builder() + .addShadow(true) + .bgColor("bg_color") + .bgImageUrl("bg_image_url") + .semitransparency(true) + .build() + ) + .build() + ), + UnnamedSchemaWithArrayParent3.ofAutoTaggingExtension( + UnnamedSchemaWithArrayParent3.AutoTaggingExtension.builder() + .maxTags(5L) + .minConfidence(95L) + .name( + UnnamedSchemaWithArrayParent3.AutoTaggingExtension + .Name + .GOOGLE_AUTO_TAGGING + ) + .build() + ), + UnnamedSchemaWithArrayParent3.ofAiAutoDescription(), + ) + ), + "folder" to MultipartField.of("folder"), + "isPrivateFile" to MultipartField.of(true), + "isPublished" to MultipartField.of(true), + "overwriteAITags" to MultipartField.of(true), + "overwriteCustomMetadata" to MultipartField.of(true), + "overwriteFile" to MultipartField.of(true), + "overwriteTags" to MultipartField.of(true), + "responseFields" to + MultipartField.of( + listOf( + FileUploadParams.ResponseField.TAGS, + FileUploadParams.ResponseField.CUSTOM_COORDINATES, + FileUploadParams.ResponseField.IS_PRIVATE_FILE, + ) + ), + "tags" to MultipartField.of(listOf("t-shirt", "round-neck", "men")), + "transformation" to + MultipartField.of( + FileUploadParams.Transformation.builder() + .addPost( + FileUploadParams.Transformation.Post.Thumbnail.builder() + .value("w-150,h-150") + .build() + ) + .addPost( + FileUploadParams.Transformation.Post.Abs.builder() + .protocol( + FileUploadParams.Transformation.Post.Abs.Protocol + .DASH + ) + .value("sr-240_360_480_720_1080") + .build() + ) + .pre("w-300,h-300,q-80") + .build() + ), + "useUniqueFileName" to MultipartField.of(true), + "webhookUrl" to MultipartField.of("https://example.com"), + ) + .mapValues { (_, field) -> + field.map { (it as? ByteArray)?.inputStream() ?: it } + } + ) + } + + @Test + fun bodyWithoutOptionalFields() { + val params = + FileUploadParams.builder() + .file("some content".byteInputStream()) + .fileName("fileName") + .build() + + val body = params._body() + + assertThat(body.filterValues { !it.value.isNull() }) + .usingRecursiveComparison() + // TODO(AssertJ): Replace this and the `mapValues` below with: + // https://github.com/assertj/assertj/issues/3165 + .withEqualsForType( + { a, b -> a.readBytes() contentEquals b.readBytes() }, + InputStream::class.java, + ) + .isEqualTo( + mapOf( + "file" to MultipartField.of("some content".byteInputStream()), + "fileName" to MultipartField.of("fileName"), + ) + .mapValues { (_, field) -> + field.map { (it as? ByteArray)?.inputStream() ?: it } + } + ) + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/beta/v2/files/FileUploadResponseTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/beta/v2/files/FileUploadResponseTest.kt new file mode 100644 index 0000000..9c5cab4 --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/beta/v2/files/FileUploadResponseTest.kt @@ -0,0 +1,448 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.beta.v2.files + +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.imagekit.api.core.JsonValue +import com.imagekit.api.core.jsonMapper +import com.imagekit.api.models.files.Metadata +import kotlin.jvm.optionals.getOrNull +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class FileUploadResponseTest { + + @Test + fun create() { + val fileUploadResponse = + FileUploadResponse.builder() + .addAiTag( + FileUploadResponse.AiTag.builder() + .confidence(0.0) + .name("name") + .source("source") + .build() + ) + .audioCodec("audioCodec") + .bitRate(0L) + .customCoordinates("customCoordinates") + .customMetadata( + FileUploadResponse.CustomMetadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .description("description") + .duration(0L) + .embeddedMetadata( + FileUploadResponse.EmbeddedMetadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .extensionStatus( + FileUploadResponse.ExtensionStatus.builder() + .aiAutoDescription( + FileUploadResponse.ExtensionStatus.AiAutoDescription.SUCCESS + ) + .awsAutoTagging(FileUploadResponse.ExtensionStatus.AwsAutoTagging.SUCCESS) + .googleAutoTagging( + FileUploadResponse.ExtensionStatus.GoogleAutoTagging.SUCCESS + ) + .removeBg(FileUploadResponse.ExtensionStatus.RemoveBg.SUCCESS) + .build() + ) + .fileId("fileId") + .filePath("filePath") + .fileType("fileType") + .height(0.0) + .isPrivateFile(true) + .isPublished(true) + .metadata( + Metadata.builder() + .audioCodec("audioCodec") + .bitRate(0L) + .density(0L) + .duration(0L) + .exif( + Metadata.Exif.builder() + .exif( + Metadata.Exif.InnerExif.builder() + .apertureValue(0.0) + .colorSpace(0L) + .createDate("CreateDate") + .customRendered(0L) + .dateTimeOriginal("DateTimeOriginal") + .exifImageHeight(0L) + .exifImageWidth(0L) + .exifVersion("ExifVersion") + .exposureCompensation(0.0) + .exposureMode(0L) + .exposureProgram(0L) + .exposureTime(0.0) + .flash(0L) + .flashpixVersion("FlashpixVersion") + .fNumber(0.0) + .focalLength(0L) + .focalPlaneResolutionUnit(0L) + .focalPlaneXResolution(0.0) + .focalPlaneYResolution(0.0) + .interopOffset(0L) + .iso(0L) + .meteringMode(0L) + .sceneCaptureType(0L) + .shutterSpeedValue(0.0) + .subSecTime("SubSecTime") + .whiteBalance(0L) + .build() + ) + .gps(Metadata.Exif.Gps.builder().addGpsVersionId(0L).build()) + .image( + Metadata.Exif.Image.builder() + .exifOffset(0L) + .gpsInfo(0L) + .make("Make") + .model("Model") + .modifyDate("ModifyDate") + .orientation(0L) + .resolutionUnit(0L) + .software("Software") + .xResolution(0L) + .yCbCrPositioning(0L) + .yResolution(0L) + .build() + ) + .interoperability( + Metadata.Exif.Interoperability.builder() + .interopIndex("InteropIndex") + .interopVersion("InteropVersion") + .build() + ) + .makernote( + Metadata.Exif.Makernote.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .thumbnail( + Metadata.Exif.Thumbnail.builder() + .compression(0L) + .resolutionUnit(0L) + .thumbnailLength(0L) + .thumbnailOffset(0L) + .xResolution(0L) + .yResolution(0L) + .build() + ) + .build() + ) + .format("format") + .hasColorProfile(true) + .hasTransparency(true) + .height(0L) + .pHash("pHash") + .quality(0L) + .size(0L) + .videoCodec("videoCodec") + .width(0L) + .build() + ) + .name("name") + .size(0.0) + .addTag("string") + .thumbnailUrl("thumbnailUrl") + .url("url") + .versionInfo(FileUploadResponse.VersionInfo.builder().id("id").name("name").build()) + .videoCodec("videoCodec") + .width(0.0) + .build() + + assertThat(fileUploadResponse.aiTags().getOrNull()) + .containsExactly( + FileUploadResponse.AiTag.builder() + .confidence(0.0) + .name("name") + .source("source") + .build() + ) + assertThat(fileUploadResponse.audioCodec()).contains("audioCodec") + assertThat(fileUploadResponse.bitRate()).contains(0L) + assertThat(fileUploadResponse.customCoordinates()).contains("customCoordinates") + assertThat(fileUploadResponse.customMetadata()) + .contains( + FileUploadResponse.CustomMetadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + assertThat(fileUploadResponse.description()).contains("description") + assertThat(fileUploadResponse.duration()).contains(0L) + assertThat(fileUploadResponse.embeddedMetadata()) + .contains( + FileUploadResponse.EmbeddedMetadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + assertThat(fileUploadResponse.extensionStatus()) + .contains( + FileUploadResponse.ExtensionStatus.builder() + .aiAutoDescription(FileUploadResponse.ExtensionStatus.AiAutoDescription.SUCCESS) + .awsAutoTagging(FileUploadResponse.ExtensionStatus.AwsAutoTagging.SUCCESS) + .googleAutoTagging(FileUploadResponse.ExtensionStatus.GoogleAutoTagging.SUCCESS) + .removeBg(FileUploadResponse.ExtensionStatus.RemoveBg.SUCCESS) + .build() + ) + assertThat(fileUploadResponse.fileId()).contains("fileId") + assertThat(fileUploadResponse.filePath()).contains("filePath") + assertThat(fileUploadResponse.fileType()).contains("fileType") + assertThat(fileUploadResponse.height()).contains(0.0) + assertThat(fileUploadResponse.isPrivateFile()).contains(true) + assertThat(fileUploadResponse.isPublished()).contains(true) + assertThat(fileUploadResponse.metadata()) + .contains( + Metadata.builder() + .audioCodec("audioCodec") + .bitRate(0L) + .density(0L) + .duration(0L) + .exif( + Metadata.Exif.builder() + .exif( + Metadata.Exif.InnerExif.builder() + .apertureValue(0.0) + .colorSpace(0L) + .createDate("CreateDate") + .customRendered(0L) + .dateTimeOriginal("DateTimeOriginal") + .exifImageHeight(0L) + .exifImageWidth(0L) + .exifVersion("ExifVersion") + .exposureCompensation(0.0) + .exposureMode(0L) + .exposureProgram(0L) + .exposureTime(0.0) + .flash(0L) + .flashpixVersion("FlashpixVersion") + .fNumber(0.0) + .focalLength(0L) + .focalPlaneResolutionUnit(0L) + .focalPlaneXResolution(0.0) + .focalPlaneYResolution(0.0) + .interopOffset(0L) + .iso(0L) + .meteringMode(0L) + .sceneCaptureType(0L) + .shutterSpeedValue(0.0) + .subSecTime("SubSecTime") + .whiteBalance(0L) + .build() + ) + .gps(Metadata.Exif.Gps.builder().addGpsVersionId(0L).build()) + .image( + Metadata.Exif.Image.builder() + .exifOffset(0L) + .gpsInfo(0L) + .make("Make") + .model("Model") + .modifyDate("ModifyDate") + .orientation(0L) + .resolutionUnit(0L) + .software("Software") + .xResolution(0L) + .yCbCrPositioning(0L) + .yResolution(0L) + .build() + ) + .interoperability( + Metadata.Exif.Interoperability.builder() + .interopIndex("InteropIndex") + .interopVersion("InteropVersion") + .build() + ) + .makernote( + Metadata.Exif.Makernote.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .thumbnail( + Metadata.Exif.Thumbnail.builder() + .compression(0L) + .resolutionUnit(0L) + .thumbnailLength(0L) + .thumbnailOffset(0L) + .xResolution(0L) + .yResolution(0L) + .build() + ) + .build() + ) + .format("format") + .hasColorProfile(true) + .hasTransparency(true) + .height(0L) + .pHash("pHash") + .quality(0L) + .size(0L) + .videoCodec("videoCodec") + .width(0L) + .build() + ) + assertThat(fileUploadResponse.name()).contains("name") + assertThat(fileUploadResponse.size()).contains(0.0) + assertThat(fileUploadResponse.tags().getOrNull()).containsExactly("string") + assertThat(fileUploadResponse.thumbnailUrl()).contains("thumbnailUrl") + assertThat(fileUploadResponse.url()).contains("url") + assertThat(fileUploadResponse.versionInfo()) + .contains(FileUploadResponse.VersionInfo.builder().id("id").name("name").build()) + assertThat(fileUploadResponse.videoCodec()).contains("videoCodec") + assertThat(fileUploadResponse.width()).contains(0.0) + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val fileUploadResponse = + FileUploadResponse.builder() + .addAiTag( + FileUploadResponse.AiTag.builder() + .confidence(0.0) + .name("name") + .source("source") + .build() + ) + .audioCodec("audioCodec") + .bitRate(0L) + .customCoordinates("customCoordinates") + .customMetadata( + FileUploadResponse.CustomMetadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .description("description") + .duration(0L) + .embeddedMetadata( + FileUploadResponse.EmbeddedMetadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .extensionStatus( + FileUploadResponse.ExtensionStatus.builder() + .aiAutoDescription( + FileUploadResponse.ExtensionStatus.AiAutoDescription.SUCCESS + ) + .awsAutoTagging(FileUploadResponse.ExtensionStatus.AwsAutoTagging.SUCCESS) + .googleAutoTagging( + FileUploadResponse.ExtensionStatus.GoogleAutoTagging.SUCCESS + ) + .removeBg(FileUploadResponse.ExtensionStatus.RemoveBg.SUCCESS) + .build() + ) + .fileId("fileId") + .filePath("filePath") + .fileType("fileType") + .height(0.0) + .isPrivateFile(true) + .isPublished(true) + .metadata( + Metadata.builder() + .audioCodec("audioCodec") + .bitRate(0L) + .density(0L) + .duration(0L) + .exif( + Metadata.Exif.builder() + .exif( + Metadata.Exif.InnerExif.builder() + .apertureValue(0.0) + .colorSpace(0L) + .createDate("CreateDate") + .customRendered(0L) + .dateTimeOriginal("DateTimeOriginal") + .exifImageHeight(0L) + .exifImageWidth(0L) + .exifVersion("ExifVersion") + .exposureCompensation(0.0) + .exposureMode(0L) + .exposureProgram(0L) + .exposureTime(0.0) + .flash(0L) + .flashpixVersion("FlashpixVersion") + .fNumber(0.0) + .focalLength(0L) + .focalPlaneResolutionUnit(0L) + .focalPlaneXResolution(0.0) + .focalPlaneYResolution(0.0) + .interopOffset(0L) + .iso(0L) + .meteringMode(0L) + .sceneCaptureType(0L) + .shutterSpeedValue(0.0) + .subSecTime("SubSecTime") + .whiteBalance(0L) + .build() + ) + .gps(Metadata.Exif.Gps.builder().addGpsVersionId(0L).build()) + .image( + Metadata.Exif.Image.builder() + .exifOffset(0L) + .gpsInfo(0L) + .make("Make") + .model("Model") + .modifyDate("ModifyDate") + .orientation(0L) + .resolutionUnit(0L) + .software("Software") + .xResolution(0L) + .yCbCrPositioning(0L) + .yResolution(0L) + .build() + ) + .interoperability( + Metadata.Exif.Interoperability.builder() + .interopIndex("InteropIndex") + .interopVersion("InteropVersion") + .build() + ) + .makernote( + Metadata.Exif.Makernote.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .thumbnail( + Metadata.Exif.Thumbnail.builder() + .compression(0L) + .resolutionUnit(0L) + .thumbnailLength(0L) + .thumbnailOffset(0L) + .xResolution(0L) + .yResolution(0L) + .build() + ) + .build() + ) + .format("format") + .hasColorProfile(true) + .hasTransparency(true) + .height(0L) + .pHash("pHash") + .quality(0L) + .size(0L) + .videoCodec("videoCodec") + .width(0L) + .build() + ) + .name("name") + .size(0.0) + .addTag("string") + .thumbnailUrl("thumbnailUrl") + .url("url") + .versionInfo(FileUploadResponse.VersionInfo.builder().id("id").name("name").build()) + .videoCodec("videoCodec") + .width(0.0) + .build() + + val roundtrippedFileUploadResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(fileUploadResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedFileUploadResponse).isEqualTo(fileUploadResponse) + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/cache/invalidation/InvalidationCreateParamsTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/cache/invalidation/InvalidationCreateParamsTest.kt new file mode 100644 index 0000000..94ef7b2 --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/cache/invalidation/InvalidationCreateParamsTest.kt @@ -0,0 +1,29 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.cache.invalidation + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class InvalidationCreateParamsTest { + + @Test + fun create() { + InvalidationCreateParams.builder() + .url("https://ik.imagekit.io/your_imagekit_id/default-image.jpg") + .build() + } + + @Test + fun body() { + val params = + InvalidationCreateParams.builder() + .url("https://ik.imagekit.io/your_imagekit_id/default-image.jpg") + .build() + + val body = params._body() + + assertThat(body.url()) + .isEqualTo("https://ik.imagekit.io/your_imagekit_id/default-image.jpg") + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/cache/invalidation/InvalidationCreateResponseTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/cache/invalidation/InvalidationCreateResponseTest.kt new file mode 100644 index 0000000..70da7c0 --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/cache/invalidation/InvalidationCreateResponseTest.kt @@ -0,0 +1,34 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.cache.invalidation + +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.imagekit.api.core.jsonMapper +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class InvalidationCreateResponseTest { + + @Test + fun create() { + val invalidationCreateResponse = + InvalidationCreateResponse.builder().requestId("requestId").build() + + assertThat(invalidationCreateResponse.requestId()).contains("requestId") + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val invalidationCreateResponse = + InvalidationCreateResponse.builder().requestId("requestId").build() + + val roundtrippedInvalidationCreateResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(invalidationCreateResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedInvalidationCreateResponse).isEqualTo(invalidationCreateResponse) + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/cache/invalidation/InvalidationGetParamsTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/cache/invalidation/InvalidationGetParamsTest.kt new file mode 100644 index 0000000..452b898 --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/cache/invalidation/InvalidationGetParamsTest.kt @@ -0,0 +1,23 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.cache.invalidation + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class InvalidationGetParamsTest { + + @Test + fun create() { + InvalidationGetParams.builder().requestId("requestId").build() + } + + @Test + fun pathParams() { + val params = InvalidationGetParams.builder().requestId("requestId").build() + + assertThat(params._pathParam(0)).isEqualTo("requestId") + // out-of-bound path param + assertThat(params._pathParam(1)).isEqualTo("") + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/cache/invalidation/InvalidationGetResponseTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/cache/invalidation/InvalidationGetResponseTest.kt new file mode 100644 index 0000000..0bcd482 --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/cache/invalidation/InvalidationGetResponseTest.kt @@ -0,0 +1,39 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.cache.invalidation + +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.imagekit.api.core.jsonMapper +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class InvalidationGetResponseTest { + + @Test + fun create() { + val invalidationGetResponse = + InvalidationGetResponse.builder() + .status(InvalidationGetResponse.Status.COMPLETED) + .build() + + assertThat(invalidationGetResponse.status()) + .contains(InvalidationGetResponse.Status.COMPLETED) + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val invalidationGetResponse = + InvalidationGetResponse.builder() + .status(InvalidationGetResponse.Status.COMPLETED) + .build() + + val roundtrippedInvalidationGetResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(invalidationGetResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedInvalidationGetResponse).isEqualTo(invalidationGetResponse) + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/custommetadatafields/CustomMetadataFieldCreateParamsTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/custommetadatafields/CustomMetadataFieldCreateParamsTest.kt new file mode 100644 index 0000000..018fb8c --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/custommetadatafields/CustomMetadataFieldCreateParamsTest.kt @@ -0,0 +1,126 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.custommetadatafields + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class CustomMetadataFieldCreateParamsTest { + + @Test + fun create() { + CustomMetadataFieldCreateParams.builder() + .label("price") + .name("price") + .schema( + CustomMetadataFieldCreateParams.Schema.builder() + .type(CustomMetadataFieldCreateParams.Schema.Type.NUMBER) + .defaultValue("string") + .isValueRequired(true) + .maxLength(0.0) + .maxValue(3000.0) + .minLength(0.0) + .minValue(1000.0) + .selectOptions( + listOf( + CustomMetadataFieldCreateParams.Schema.SelectOption.ofString("small"), + CustomMetadataFieldCreateParams.Schema.SelectOption.ofString("medium"), + CustomMetadataFieldCreateParams.Schema.SelectOption.ofString("large"), + CustomMetadataFieldCreateParams.Schema.SelectOption.ofNumber(30.0), + CustomMetadataFieldCreateParams.Schema.SelectOption.ofNumber(40.0), + CustomMetadataFieldCreateParams.Schema.SelectOption.ofBool(true), + ) + ) + .build() + ) + .build() + } + + @Test + fun body() { + val params = + CustomMetadataFieldCreateParams.builder() + .label("price") + .name("price") + .schema( + CustomMetadataFieldCreateParams.Schema.builder() + .type(CustomMetadataFieldCreateParams.Schema.Type.NUMBER) + .defaultValue("string") + .isValueRequired(true) + .maxLength(0.0) + .maxValue(3000.0) + .minLength(0.0) + .minValue(1000.0) + .selectOptions( + listOf( + CustomMetadataFieldCreateParams.Schema.SelectOption.ofString( + "small" + ), + CustomMetadataFieldCreateParams.Schema.SelectOption.ofString( + "medium" + ), + CustomMetadataFieldCreateParams.Schema.SelectOption.ofString( + "large" + ), + CustomMetadataFieldCreateParams.Schema.SelectOption.ofNumber(30.0), + CustomMetadataFieldCreateParams.Schema.SelectOption.ofNumber(40.0), + CustomMetadataFieldCreateParams.Schema.SelectOption.ofBool(true), + ) + ) + .build() + ) + .build() + + val body = params._body() + + assertThat(body.label()).isEqualTo("price") + assertThat(body.name()).isEqualTo("price") + assertThat(body.schema()) + .isEqualTo( + CustomMetadataFieldCreateParams.Schema.builder() + .type(CustomMetadataFieldCreateParams.Schema.Type.NUMBER) + .defaultValue("string") + .isValueRequired(true) + .maxLength(0.0) + .maxValue(3000.0) + .minLength(0.0) + .minValue(1000.0) + .selectOptions( + listOf( + CustomMetadataFieldCreateParams.Schema.SelectOption.ofString("small"), + CustomMetadataFieldCreateParams.Schema.SelectOption.ofString("medium"), + CustomMetadataFieldCreateParams.Schema.SelectOption.ofString("large"), + CustomMetadataFieldCreateParams.Schema.SelectOption.ofNumber(30.0), + CustomMetadataFieldCreateParams.Schema.SelectOption.ofNumber(40.0), + CustomMetadataFieldCreateParams.Schema.SelectOption.ofBool(true), + ) + ) + .build() + ) + } + + @Test + fun bodyWithoutOptionalFields() { + val params = + CustomMetadataFieldCreateParams.builder() + .label("price") + .name("price") + .schema( + CustomMetadataFieldCreateParams.Schema.builder() + .type(CustomMetadataFieldCreateParams.Schema.Type.NUMBER) + .build() + ) + .build() + + val body = params._body() + + assertThat(body.label()).isEqualTo("price") + assertThat(body.name()).isEqualTo("price") + assertThat(body.schema()) + .isEqualTo( + CustomMetadataFieldCreateParams.Schema.builder() + .type(CustomMetadataFieldCreateParams.Schema.Type.NUMBER) + .build() + ) + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/custommetadatafields/CustomMetadataFieldDeleteParamsTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/custommetadatafields/CustomMetadataFieldDeleteParamsTest.kt new file mode 100644 index 0000000..1ce51ef --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/custommetadatafields/CustomMetadataFieldDeleteParamsTest.kt @@ -0,0 +1,23 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.custommetadatafields + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class CustomMetadataFieldDeleteParamsTest { + + @Test + fun create() { + CustomMetadataFieldDeleteParams.builder().id("id").build() + } + + @Test + fun pathParams() { + val params = CustomMetadataFieldDeleteParams.builder().id("id").build() + + assertThat(params._pathParam(0)).isEqualTo("id") + // out-of-bound path param + assertThat(params._pathParam(1)).isEqualTo("") + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/custommetadatafields/CustomMetadataFieldDeleteResponseTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/custommetadatafields/CustomMetadataFieldDeleteResponseTest.kt new file mode 100644 index 0000000..3f1974c --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/custommetadatafields/CustomMetadataFieldDeleteResponseTest.kt @@ -0,0 +1,31 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.custommetadatafields + +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.imagekit.api.core.jsonMapper +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class CustomMetadataFieldDeleteResponseTest { + + @Test + fun create() { + val customMetadataFieldDeleteResponse = CustomMetadataFieldDeleteResponse.builder().build() + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val customMetadataFieldDeleteResponse = CustomMetadataFieldDeleteResponse.builder().build() + + val roundtrippedCustomMetadataFieldDeleteResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(customMetadataFieldDeleteResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedCustomMetadataFieldDeleteResponse) + .isEqualTo(customMetadataFieldDeleteResponse) + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/custommetadatafields/CustomMetadataFieldListParamsTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/custommetadatafields/CustomMetadataFieldListParamsTest.kt new file mode 100644 index 0000000..df9806a --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/custommetadatafields/CustomMetadataFieldListParamsTest.kt @@ -0,0 +1,34 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.custommetadatafields + +import com.imagekit.api.core.http.QueryParams +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class CustomMetadataFieldListParamsTest { + + @Test + fun create() { + CustomMetadataFieldListParams.builder().includeDeleted(true).build() + } + + @Test + fun queryParams() { + val params = CustomMetadataFieldListParams.builder().includeDeleted(true).build() + + val queryParams = params._queryParams() + + assertThat(queryParams) + .isEqualTo(QueryParams.builder().put("includeDeleted", "true").build()) + } + + @Test + fun queryParamsWithoutOptionalFields() { + val params = CustomMetadataFieldListParams.builder().build() + + val queryParams = params._queryParams() + + assertThat(queryParams).isEqualTo(QueryParams.builder().build()) + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/custommetadatafields/CustomMetadataFieldTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/custommetadatafields/CustomMetadataFieldTest.kt new file mode 100644 index 0000000..14455b9 --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/custommetadatafields/CustomMetadataFieldTest.kt @@ -0,0 +1,108 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.custommetadatafields + +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.imagekit.api.core.jsonMapper +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class CustomMetadataFieldTest { + + @Test + fun create() { + val customMetadataField = + CustomMetadataField.builder() + .id("id") + .label("label") + .name("name") + .schema( + CustomMetadataField.Schema.builder() + .type(CustomMetadataField.Schema.Type.TEXT) + .defaultValue("string") + .isValueRequired(true) + .maxLength(0.0) + .maxValue("string") + .minLength(0.0) + .minValue("string") + .selectOptions( + listOf( + CustomMetadataField.Schema.SelectOption.ofString("small"), + CustomMetadataField.Schema.SelectOption.ofString("medium"), + CustomMetadataField.Schema.SelectOption.ofString("large"), + CustomMetadataField.Schema.SelectOption.ofNumber(30.0), + CustomMetadataField.Schema.SelectOption.ofNumber(40.0), + CustomMetadataField.Schema.SelectOption.ofBool(true), + ) + ) + .build() + ) + .build() + + assertThat(customMetadataField.id()).isEqualTo("id") + assertThat(customMetadataField.label()).isEqualTo("label") + assertThat(customMetadataField.name()).isEqualTo("name") + assertThat(customMetadataField.schema()) + .isEqualTo( + CustomMetadataField.Schema.builder() + .type(CustomMetadataField.Schema.Type.TEXT) + .defaultValue("string") + .isValueRequired(true) + .maxLength(0.0) + .maxValue("string") + .minLength(0.0) + .minValue("string") + .selectOptions( + listOf( + CustomMetadataField.Schema.SelectOption.ofString("small"), + CustomMetadataField.Schema.SelectOption.ofString("medium"), + CustomMetadataField.Schema.SelectOption.ofString("large"), + CustomMetadataField.Schema.SelectOption.ofNumber(30.0), + CustomMetadataField.Schema.SelectOption.ofNumber(40.0), + CustomMetadataField.Schema.SelectOption.ofBool(true), + ) + ) + .build() + ) + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val customMetadataField = + CustomMetadataField.builder() + .id("id") + .label("label") + .name("name") + .schema( + CustomMetadataField.Schema.builder() + .type(CustomMetadataField.Schema.Type.TEXT) + .defaultValue("string") + .isValueRequired(true) + .maxLength(0.0) + .maxValue("string") + .minLength(0.0) + .minValue("string") + .selectOptions( + listOf( + CustomMetadataField.Schema.SelectOption.ofString("small"), + CustomMetadataField.Schema.SelectOption.ofString("medium"), + CustomMetadataField.Schema.SelectOption.ofString("large"), + CustomMetadataField.Schema.SelectOption.ofNumber(30.0), + CustomMetadataField.Schema.SelectOption.ofNumber(40.0), + CustomMetadataField.Schema.SelectOption.ofBool(true), + ) + ) + .build() + ) + .build() + + val roundtrippedCustomMetadataField = + jsonMapper.readValue( + jsonMapper.writeValueAsString(customMetadataField), + jacksonTypeRef(), + ) + + assertThat(roundtrippedCustomMetadataField).isEqualTo(customMetadataField) + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/custommetadatafields/CustomMetadataFieldUpdateParamsTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/custommetadatafields/CustomMetadataFieldUpdateParamsTest.kt new file mode 100644 index 0000000..5611af8 --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/custommetadatafields/CustomMetadataFieldUpdateParamsTest.kt @@ -0,0 +1,113 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.custommetadatafields + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class CustomMetadataFieldUpdateParamsTest { + + @Test + fun create() { + CustomMetadataFieldUpdateParams.builder() + .id("id") + .label("price") + .schema( + CustomMetadataFieldUpdateParams.Schema.builder() + .defaultValue("string") + .isValueRequired(true) + .maxLength(0.0) + .maxValue(3000.0) + .minLength(0.0) + .minValue(1000.0) + .selectOptions( + listOf( + CustomMetadataFieldUpdateParams.Schema.SelectOption.ofString("small"), + CustomMetadataFieldUpdateParams.Schema.SelectOption.ofString("medium"), + CustomMetadataFieldUpdateParams.Schema.SelectOption.ofString("large"), + CustomMetadataFieldUpdateParams.Schema.SelectOption.ofNumber(30.0), + CustomMetadataFieldUpdateParams.Schema.SelectOption.ofNumber(40.0), + CustomMetadataFieldUpdateParams.Schema.SelectOption.ofBool(true), + ) + ) + .build() + ) + .build() + } + + @Test + fun pathParams() { + val params = CustomMetadataFieldUpdateParams.builder().id("id").build() + + assertThat(params._pathParam(0)).isEqualTo("id") + // out-of-bound path param + assertThat(params._pathParam(1)).isEqualTo("") + } + + @Test + fun body() { + val params = + CustomMetadataFieldUpdateParams.builder() + .id("id") + .label("price") + .schema( + CustomMetadataFieldUpdateParams.Schema.builder() + .defaultValue("string") + .isValueRequired(true) + .maxLength(0.0) + .maxValue(3000.0) + .minLength(0.0) + .minValue(1000.0) + .selectOptions( + listOf( + CustomMetadataFieldUpdateParams.Schema.SelectOption.ofString( + "small" + ), + CustomMetadataFieldUpdateParams.Schema.SelectOption.ofString( + "medium" + ), + CustomMetadataFieldUpdateParams.Schema.SelectOption.ofString( + "large" + ), + CustomMetadataFieldUpdateParams.Schema.SelectOption.ofNumber(30.0), + CustomMetadataFieldUpdateParams.Schema.SelectOption.ofNumber(40.0), + CustomMetadataFieldUpdateParams.Schema.SelectOption.ofBool(true), + ) + ) + .build() + ) + .build() + + val body = params._body() + + assertThat(body.label()).contains("price") + assertThat(body.schema()) + .contains( + CustomMetadataFieldUpdateParams.Schema.builder() + .defaultValue("string") + .isValueRequired(true) + .maxLength(0.0) + .maxValue(3000.0) + .minLength(0.0) + .minValue(1000.0) + .selectOptions( + listOf( + CustomMetadataFieldUpdateParams.Schema.SelectOption.ofString("small"), + CustomMetadataFieldUpdateParams.Schema.SelectOption.ofString("medium"), + CustomMetadataFieldUpdateParams.Schema.SelectOption.ofString("large"), + CustomMetadataFieldUpdateParams.Schema.SelectOption.ofNumber(30.0), + CustomMetadataFieldUpdateParams.Schema.SelectOption.ofNumber(40.0), + CustomMetadataFieldUpdateParams.Schema.SelectOption.ofBool(true), + ) + ) + .build() + ) + } + + @Test + fun bodyWithoutOptionalFields() { + val params = CustomMetadataFieldUpdateParams.builder().id("id").build() + + val body = params._body() + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/files/FileCopyParamsTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/files/FileCopyParamsTest.kt new file mode 100644 index 0000000..f6e8ba6 --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/files/FileCopyParamsTest.kt @@ -0,0 +1,48 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.files + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class FileCopyParamsTest { + + @Test + fun create() { + FileCopyParams.builder() + .destinationPath("/folder/to/copy/into/") + .sourceFilePath("/path/to/file.jpg") + .includeFileVersions(false) + .build() + } + + @Test + fun body() { + val params = + FileCopyParams.builder() + .destinationPath("/folder/to/copy/into/") + .sourceFilePath("/path/to/file.jpg") + .includeFileVersions(false) + .build() + + val body = params._body() + + assertThat(body.destinationPath()).isEqualTo("/folder/to/copy/into/") + assertThat(body.sourceFilePath()).isEqualTo("/path/to/file.jpg") + assertThat(body.includeFileVersions()).contains(false) + } + + @Test + fun bodyWithoutOptionalFields() { + val params = + FileCopyParams.builder() + .destinationPath("/folder/to/copy/into/") + .sourceFilePath("/path/to/file.jpg") + .build() + + val body = params._body() + + assertThat(body.destinationPath()).isEqualTo("/folder/to/copy/into/") + assertThat(body.sourceFilePath()).isEqualTo("/path/to/file.jpg") + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/files/FileCopyResponseTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/files/FileCopyResponseTest.kt new file mode 100644 index 0000000..24b46ab --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/files/FileCopyResponseTest.kt @@ -0,0 +1,30 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.files + +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.imagekit.api.core.jsonMapper +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class FileCopyResponseTest { + + @Test + fun create() { + val fileCopyResponse = FileCopyResponse.builder().build() + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val fileCopyResponse = FileCopyResponse.builder().build() + + val roundtrippedFileCopyResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(fileCopyResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedFileCopyResponse).isEqualTo(fileCopyResponse) + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/files/FileDeleteParamsTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/files/FileDeleteParamsTest.kt new file mode 100644 index 0000000..ec09e31 --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/files/FileDeleteParamsTest.kt @@ -0,0 +1,23 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.files + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class FileDeleteParamsTest { + + @Test + fun create() { + FileDeleteParams.builder().fileId("fileId").build() + } + + @Test + fun pathParams() { + val params = FileDeleteParams.builder().fileId("fileId").build() + + assertThat(params._pathParam(0)).isEqualTo("fileId") + // out-of-bound path param + assertThat(params._pathParam(1)).isEqualTo("") + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/files/FileGetParamsTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/files/FileGetParamsTest.kt new file mode 100644 index 0000000..633e0e5 --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/files/FileGetParamsTest.kt @@ -0,0 +1,23 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.files + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class FileGetParamsTest { + + @Test + fun create() { + FileGetParams.builder().fileId("fileId").build() + } + + @Test + fun pathParams() { + val params = FileGetParams.builder().fileId("fileId").build() + + assertThat(params._pathParam(0)).isEqualTo("fileId") + // out-of-bound path param + assertThat(params._pathParam(1)).isEqualTo("") + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/files/FileMoveParamsTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/files/FileMoveParamsTest.kt new file mode 100644 index 0000000..f0cc0dc --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/files/FileMoveParamsTest.kt @@ -0,0 +1,31 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.files + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class FileMoveParamsTest { + + @Test + fun create() { + FileMoveParams.builder() + .destinationPath("/folder/to/move/into/") + .sourceFilePath("/path/to/file.jpg") + .build() + } + + @Test + fun body() { + val params = + FileMoveParams.builder() + .destinationPath("/folder/to/move/into/") + .sourceFilePath("/path/to/file.jpg") + .build() + + val body = params._body() + + assertThat(body.destinationPath()).isEqualTo("/folder/to/move/into/") + assertThat(body.sourceFilePath()).isEqualTo("/path/to/file.jpg") + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/files/FileMoveResponseTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/files/FileMoveResponseTest.kt new file mode 100644 index 0000000..d8560b5 --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/files/FileMoveResponseTest.kt @@ -0,0 +1,30 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.files + +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.imagekit.api.core.jsonMapper +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class FileMoveResponseTest { + + @Test + fun create() { + val fileMoveResponse = FileMoveResponse.builder().build() + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val fileMoveResponse = FileMoveResponse.builder().build() + + val roundtrippedFileMoveResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(fileMoveResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedFileMoveResponse).isEqualTo(fileMoveResponse) + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/files/FileRenameParamsTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/files/FileRenameParamsTest.kt new file mode 100644 index 0000000..cd3b78c --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/files/FileRenameParamsTest.kt @@ -0,0 +1,48 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.files + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class FileRenameParamsTest { + + @Test + fun create() { + FileRenameParams.builder() + .filePath("/path/to/file.jpg") + .newFileName("newFileName.jpg") + .purgeCache(true) + .build() + } + + @Test + fun body() { + val params = + FileRenameParams.builder() + .filePath("/path/to/file.jpg") + .newFileName("newFileName.jpg") + .purgeCache(true) + .build() + + val body = params._body() + + assertThat(body.filePath()).isEqualTo("/path/to/file.jpg") + assertThat(body.newFileName()).isEqualTo("newFileName.jpg") + assertThat(body.purgeCache()).contains(true) + } + + @Test + fun bodyWithoutOptionalFields() { + val params = + FileRenameParams.builder() + .filePath("/path/to/file.jpg") + .newFileName("newFileName.jpg") + .build() + + val body = params._body() + + assertThat(body.filePath()).isEqualTo("/path/to/file.jpg") + assertThat(body.newFileName()).isEqualTo("newFileName.jpg") + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/files/FileRenameResponseTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/files/FileRenameResponseTest.kt new file mode 100644 index 0000000..79e2867 --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/files/FileRenameResponseTest.kt @@ -0,0 +1,34 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.files + +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.imagekit.api.core.jsonMapper +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class FileRenameResponseTest { + + @Test + fun create() { + val fileRenameResponse = + FileRenameResponse.builder().purgeRequestId("purgeRequestId").build() + + assertThat(fileRenameResponse.purgeRequestId()).contains("purgeRequestId") + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val fileRenameResponse = + FileRenameResponse.builder().purgeRequestId("purgeRequestId").build() + + val roundtrippedFileRenameResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(fileRenameResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedFileRenameResponse).isEqualTo(fileRenameResponse) + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/files/FileTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/files/FileTest.kt new file mode 100644 index 0000000..78282e9 --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/files/FileTest.kt @@ -0,0 +1,122 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.files + +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.imagekit.api.core.JsonValue +import com.imagekit.api.core.jsonMapper +import java.time.OffsetDateTime +import kotlin.jvm.optionals.getOrNull +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class FileTest { + + @Test + fun create() { + val file = + File.builder() + .addAiTag( + File.AiTag.builder().confidence(0.0).name("name").source("source").build() + ) + .createdAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .customCoordinates("customCoordinates") + .customMetadata( + File.CustomMetadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .description("description") + .fileId("fileId") + .filePath("filePath") + .fileType("fileType") + .hasAlpha(true) + .height(0.0) + .isPrivateFile(true) + .isPublished(true) + .mime("mime") + .name("name") + .size(0.0) + .addTag("string") + .thumbnail("https://example.com") + .type(File.Type.FILE) + .updatedAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .url("https://example.com") + .versionInfo(File.VersionInfo.builder().id("id").name("name").build()) + .width(0.0) + .build() + + assertThat(file.aiTags().getOrNull()) + .containsExactly( + File.AiTag.builder().confidence(0.0).name("name").source("source").build() + ) + assertThat(file.createdAt()).contains(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + assertThat(file.customCoordinates()).contains("customCoordinates") + assertThat(file.customMetadata()) + .contains( + File.CustomMetadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + assertThat(file.description()).contains("description") + assertThat(file.fileId()).contains("fileId") + assertThat(file.filePath()).contains("filePath") + assertThat(file.fileType()).contains("fileType") + assertThat(file.hasAlpha()).contains(true) + assertThat(file.height()).contains(0.0) + assertThat(file.isPrivateFile()).contains(true) + assertThat(file.isPublished()).contains(true) + assertThat(file.mime()).contains("mime") + assertThat(file.name()).contains("name") + assertThat(file.size()).contains(0.0) + assertThat(file.tags().getOrNull()).containsExactly("string") + assertThat(file.thumbnail()).contains("https://example.com") + assertThat(file.type()).contains(File.Type.FILE) + assertThat(file.updatedAt()).contains(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + assertThat(file.url()).contains("https://example.com") + assertThat(file.versionInfo()) + .contains(File.VersionInfo.builder().id("id").name("name").build()) + assertThat(file.width()).contains(0.0) + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val file = + File.builder() + .addAiTag( + File.AiTag.builder().confidence(0.0).name("name").source("source").build() + ) + .createdAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .customCoordinates("customCoordinates") + .customMetadata( + File.CustomMetadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .description("description") + .fileId("fileId") + .filePath("filePath") + .fileType("fileType") + .hasAlpha(true) + .height(0.0) + .isPrivateFile(true) + .isPublished(true) + .mime("mime") + .name("name") + .size(0.0) + .addTag("string") + .thumbnail("https://example.com") + .type(File.Type.FILE) + .updatedAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .url("https://example.com") + .versionInfo(File.VersionInfo.builder().id("id").name("name").build()) + .width(0.0) + .build() + + val roundtrippedFile = + jsonMapper.readValue(jsonMapper.writeValueAsString(file), jacksonTypeRef()) + + assertThat(roundtrippedFile).isEqualTo(file) + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/files/FileUpdateParamsTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/files/FileUpdateParamsTest.kt new file mode 100644 index 0000000..d3d44b3 --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/files/FileUpdateParamsTest.kt @@ -0,0 +1,208 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.files + +import com.imagekit.api.core.JsonValue +import com.imagekit.api.models.UnnamedSchemaWithArrayParent3 +import kotlin.jvm.optionals.getOrNull +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class FileUpdateParamsTest { + + @Test + fun create() { + FileUpdateParams.builder() + .fileId("fileId") + .body( + FileUpdateParams.Body.UpdateFileDetails.builder() + .customCoordinates("10,10,100,100") + .customMetadata( + FileUpdateParams.Body.UpdateFileDetails.CustomMetadata.builder() + .putAdditionalProperty("brand", JsonValue.from("bar")) + .putAdditionalProperty("color", JsonValue.from("bar")) + .build() + ) + .description("description") + .extensions( + listOf( + UnnamedSchemaWithArrayParent3.ofRemoveBg( + UnnamedSchemaWithArrayParent3.RemoveBg.builder() + .options( + UnnamedSchemaWithArrayParent3.RemoveBg.Options.builder() + .addShadow(true) + .bgColor("bg_color") + .bgImageUrl("bg_image_url") + .semitransparency(true) + .build() + ) + .build() + ), + UnnamedSchemaWithArrayParent3.ofAutoTaggingExtension( + UnnamedSchemaWithArrayParent3.AutoTaggingExtension.builder() + .maxTags(10L) + .minConfidence(80L) + .name( + UnnamedSchemaWithArrayParent3.AutoTaggingExtension.Name + .GOOGLE_AUTO_TAGGING + ) + .build() + ), + UnnamedSchemaWithArrayParent3.ofAutoTaggingExtension( + UnnamedSchemaWithArrayParent3.AutoTaggingExtension.builder() + .maxTags(10L) + .minConfidence(80L) + .name( + UnnamedSchemaWithArrayParent3.AutoTaggingExtension.Name + .AWS_AUTO_TAGGING + ) + .build() + ), + UnnamedSchemaWithArrayParent3.ofAiAutoDescription(), + ) + ) + .removeAiTagsOfStrings(listOf("car", "vehicle", "motorsports")) + .addTag("tag1") + .addTag("tag2") + .webhookUrl("https://webhook.site/0d6b6c7a-8e5a-4b3a-8b7c-0d6b6c7a8e5a") + .build() + ) + .build() + } + + @Test + fun pathParams() { + val params = FileUpdateParams.builder().fileId("fileId").build() + + assertThat(params._pathParam(0)).isEqualTo("fileId") + // out-of-bound path param + assertThat(params._pathParam(1)).isEqualTo("") + } + + @Test + fun body() { + val params = + FileUpdateParams.builder() + .fileId("fileId") + .body( + FileUpdateParams.Body.UpdateFileDetails.builder() + .customCoordinates("10,10,100,100") + .customMetadata( + FileUpdateParams.Body.UpdateFileDetails.CustomMetadata.builder() + .putAdditionalProperty("brand", JsonValue.from("bar")) + .putAdditionalProperty("color", JsonValue.from("bar")) + .build() + ) + .description("description") + .extensions( + listOf( + UnnamedSchemaWithArrayParent3.ofRemoveBg( + UnnamedSchemaWithArrayParent3.RemoveBg.builder() + .options( + UnnamedSchemaWithArrayParent3.RemoveBg.Options.builder() + .addShadow(true) + .bgColor("bg_color") + .bgImageUrl("bg_image_url") + .semitransparency(true) + .build() + ) + .build() + ), + UnnamedSchemaWithArrayParent3.ofAutoTaggingExtension( + UnnamedSchemaWithArrayParent3.AutoTaggingExtension.builder() + .maxTags(10L) + .minConfidence(80L) + .name( + UnnamedSchemaWithArrayParent3.AutoTaggingExtension.Name + .GOOGLE_AUTO_TAGGING + ) + .build() + ), + UnnamedSchemaWithArrayParent3.ofAutoTaggingExtension( + UnnamedSchemaWithArrayParent3.AutoTaggingExtension.builder() + .maxTags(10L) + .minConfidence(80L) + .name( + UnnamedSchemaWithArrayParent3.AutoTaggingExtension.Name + .AWS_AUTO_TAGGING + ) + .build() + ), + UnnamedSchemaWithArrayParent3.ofAiAutoDescription(), + ) + ) + .removeAiTagsOfStrings(listOf("car", "vehicle", "motorsports")) + .addTag("tag1") + .addTag("tag2") + .webhookUrl("https://webhook.site/0d6b6c7a-8e5a-4b3a-8b7c-0d6b6c7a8e5a") + .build() + ) + .build() + + val body = params._body().getOrNull() + + assertThat(body) + .isEqualTo( + FileUpdateParams.Body.ofUpdateFileDetails( + FileUpdateParams.Body.UpdateFileDetails.builder() + .customCoordinates("10,10,100,100") + .customMetadata( + FileUpdateParams.Body.UpdateFileDetails.CustomMetadata.builder() + .putAdditionalProperty("brand", JsonValue.from("bar")) + .putAdditionalProperty("color", JsonValue.from("bar")) + .build() + ) + .description("description") + .extensions( + listOf( + UnnamedSchemaWithArrayParent3.ofRemoveBg( + UnnamedSchemaWithArrayParent3.RemoveBg.builder() + .options( + UnnamedSchemaWithArrayParent3.RemoveBg.Options.builder() + .addShadow(true) + .bgColor("bg_color") + .bgImageUrl("bg_image_url") + .semitransparency(true) + .build() + ) + .build() + ), + UnnamedSchemaWithArrayParent3.ofAutoTaggingExtension( + UnnamedSchemaWithArrayParent3.AutoTaggingExtension.builder() + .maxTags(10L) + .minConfidence(80L) + .name( + UnnamedSchemaWithArrayParent3.AutoTaggingExtension.Name + .GOOGLE_AUTO_TAGGING + ) + .build() + ), + UnnamedSchemaWithArrayParent3.ofAutoTaggingExtension( + UnnamedSchemaWithArrayParent3.AutoTaggingExtension.builder() + .maxTags(10L) + .minConfidence(80L) + .name( + UnnamedSchemaWithArrayParent3.AutoTaggingExtension.Name + .AWS_AUTO_TAGGING + ) + .build() + ), + UnnamedSchemaWithArrayParent3.ofAiAutoDescription(), + ) + ) + .removeAiTagsOfStrings(listOf("car", "vehicle", "motorsports")) + .addTag("tag1") + .addTag("tag2") + .webhookUrl("https://webhook.site/0d6b6c7a-8e5a-4b3a-8b7c-0d6b6c7a8e5a") + .build() + ) + ) + } + + @Test + fun bodyWithoutOptionalFields() { + val params = FileUpdateParams.builder().fileId("fileId").build() + + val body = params._body().getOrNull() + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/files/FileUpdateResponseTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/files/FileUpdateResponseTest.kt new file mode 100644 index 0000000..de6e3a6 --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/files/FileUpdateResponseTest.kt @@ -0,0 +1,160 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.files + +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.imagekit.api.core.JsonValue +import com.imagekit.api.core.jsonMapper +import java.time.OffsetDateTime +import kotlin.jvm.optionals.getOrNull +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class FileUpdateResponseTest { + + @Test + fun create() { + val fileUpdateResponse = + FileUpdateResponse.builder() + .addAiTag( + File.AiTag.builder().confidence(0.0).name("name").source("source").build() + ) + .createdAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .customCoordinates("customCoordinates") + .customMetadata( + File.CustomMetadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .description("description") + .fileId("fileId") + .filePath("filePath") + .fileType("fileType") + .hasAlpha(true) + .height(0.0) + .isPrivateFile(true) + .isPublished(true) + .mime("mime") + .name("name") + .size(0.0) + .addTag("string") + .thumbnail("https://example.com") + .type(File.Type.FILE) + .updatedAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .url("https://example.com") + .versionInfo(File.VersionInfo.builder().id("id").name("name").build()) + .width(0.0) + .extensionStatus( + FileUpdateResponse.ExtensionStatus.builder() + .aiAutoDescription( + FileUpdateResponse.ExtensionStatus.AiAutoDescription.SUCCESS + ) + .awsAutoTagging(FileUpdateResponse.ExtensionStatus.AwsAutoTagging.SUCCESS) + .googleAutoTagging( + FileUpdateResponse.ExtensionStatus.GoogleAutoTagging.SUCCESS + ) + .removeBg(FileUpdateResponse.ExtensionStatus.RemoveBg.SUCCESS) + .build() + ) + .build() + + assertThat(fileUpdateResponse.aiTags().getOrNull()) + .containsExactly( + File.AiTag.builder().confidence(0.0).name("name").source("source").build() + ) + assertThat(fileUpdateResponse.createdAt()) + .contains(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + assertThat(fileUpdateResponse.customCoordinates()).contains("customCoordinates") + assertThat(fileUpdateResponse.customMetadata()) + .contains( + File.CustomMetadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + assertThat(fileUpdateResponse.description()).contains("description") + assertThat(fileUpdateResponse.fileId()).contains("fileId") + assertThat(fileUpdateResponse.filePath()).contains("filePath") + assertThat(fileUpdateResponse.fileType()).contains("fileType") + assertThat(fileUpdateResponse.hasAlpha()).contains(true) + assertThat(fileUpdateResponse.height()).contains(0.0) + assertThat(fileUpdateResponse.isPrivateFile()).contains(true) + assertThat(fileUpdateResponse.isPublished()).contains(true) + assertThat(fileUpdateResponse.mime()).contains("mime") + assertThat(fileUpdateResponse.name()).contains("name") + assertThat(fileUpdateResponse.size()).contains(0.0) + assertThat(fileUpdateResponse.tags().getOrNull()).containsExactly("string") + assertThat(fileUpdateResponse.thumbnail()).contains("https://example.com") + assertThat(fileUpdateResponse.type()).contains(File.Type.FILE) + assertThat(fileUpdateResponse.updatedAt()) + .contains(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + assertThat(fileUpdateResponse.url()).contains("https://example.com") + assertThat(fileUpdateResponse.versionInfo()) + .contains(File.VersionInfo.builder().id("id").name("name").build()) + assertThat(fileUpdateResponse.width()).contains(0.0) + assertThat(fileUpdateResponse.extensionStatus()) + .contains( + FileUpdateResponse.ExtensionStatus.builder() + .aiAutoDescription(FileUpdateResponse.ExtensionStatus.AiAutoDescription.SUCCESS) + .awsAutoTagging(FileUpdateResponse.ExtensionStatus.AwsAutoTagging.SUCCESS) + .googleAutoTagging(FileUpdateResponse.ExtensionStatus.GoogleAutoTagging.SUCCESS) + .removeBg(FileUpdateResponse.ExtensionStatus.RemoveBg.SUCCESS) + .build() + ) + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val fileUpdateResponse = + FileUpdateResponse.builder() + .addAiTag( + File.AiTag.builder().confidence(0.0).name("name").source("source").build() + ) + .createdAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .customCoordinates("customCoordinates") + .customMetadata( + File.CustomMetadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .description("description") + .fileId("fileId") + .filePath("filePath") + .fileType("fileType") + .hasAlpha(true) + .height(0.0) + .isPrivateFile(true) + .isPublished(true) + .mime("mime") + .name("name") + .size(0.0) + .addTag("string") + .thumbnail("https://example.com") + .type(File.Type.FILE) + .updatedAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .url("https://example.com") + .versionInfo(File.VersionInfo.builder().id("id").name("name").build()) + .width(0.0) + .extensionStatus( + FileUpdateResponse.ExtensionStatus.builder() + .aiAutoDescription( + FileUpdateResponse.ExtensionStatus.AiAutoDescription.SUCCESS + ) + .awsAutoTagging(FileUpdateResponse.ExtensionStatus.AwsAutoTagging.SUCCESS) + .googleAutoTagging( + FileUpdateResponse.ExtensionStatus.GoogleAutoTagging.SUCCESS + ) + .removeBg(FileUpdateResponse.ExtensionStatus.RemoveBg.SUCCESS) + .build() + ) + .build() + + val roundtrippedFileUpdateResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(fileUpdateResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedFileUpdateResponse).isEqualTo(fileUpdateResponse) + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/files/FileUploadParamsTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/files/FileUploadParamsTest.kt new file mode 100644 index 0000000..36a3646 --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/files/FileUploadParamsTest.kt @@ -0,0 +1,307 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.files + +import com.imagekit.api.core.JsonValue +import com.imagekit.api.core.MultipartField +import com.imagekit.api.models.UnnamedSchemaWithArrayParent3 +import java.io.InputStream +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class FileUploadParamsTest { + + @Test + fun create() { + FileUploadParams.builder() + .file("some content".byteInputStream()) + .fileName("fileName") + .token("token") + .checks("\"request.folder\" : \"marketing/\"\n") + .customCoordinates("customCoordinates") + .customMetadata( + FileUploadParams.CustomMetadata.builder() + .putAdditionalProperty("brand", JsonValue.from("bar")) + .putAdditionalProperty("color", JsonValue.from("bar")) + .build() + ) + .description("Running shoes") + .expire(0L) + .extensions( + listOf( + UnnamedSchemaWithArrayParent3.ofRemoveBg( + UnnamedSchemaWithArrayParent3.RemoveBg.builder() + .options( + UnnamedSchemaWithArrayParent3.RemoveBg.Options.builder() + .addShadow(true) + .bgColor("bg_color") + .bgImageUrl("bg_image_url") + .semitransparency(true) + .build() + ) + .build() + ), + UnnamedSchemaWithArrayParent3.ofAutoTaggingExtension( + UnnamedSchemaWithArrayParent3.AutoTaggingExtension.builder() + .maxTags(5L) + .minConfidence(95L) + .name( + UnnamedSchemaWithArrayParent3.AutoTaggingExtension.Name + .GOOGLE_AUTO_TAGGING + ) + .build() + ), + UnnamedSchemaWithArrayParent3.ofAiAutoDescription(), + ) + ) + .folder("folder") + .isPrivateFile(true) + .isPublished(true) + .overwriteAiTags(true) + .overwriteCustomMetadata(true) + .overwriteFile(true) + .overwriteTags(true) + .publicKey("publicKey") + .responseFields( + listOf( + FileUploadParams.ResponseField.TAGS, + FileUploadParams.ResponseField.CUSTOM_COORDINATES, + FileUploadParams.ResponseField.IS_PRIVATE_FILE, + ) + ) + .signature("signature") + .tags(listOf("t-shirt", "round-neck", "men")) + .transformation( + FileUploadParams.Transformation.builder() + .addPost( + FileUploadParams.Transformation.Post.Thumbnail.builder() + .value("w-150,h-150") + .build() + ) + .addPost( + FileUploadParams.Transformation.Post.Abs.builder() + .protocol(FileUploadParams.Transformation.Post.Abs.Protocol.DASH) + .value("sr-240_360_480_720_1080") + .build() + ) + .pre("w-300,h-300,q-80") + .build() + ) + .useUniqueFileName(true) + .webhookUrl("https://example.com") + .build() + } + + @Test + fun body() { + val params = + FileUploadParams.builder() + .file("some content".byteInputStream()) + .fileName("fileName") + .token("token") + .checks("\"request.folder\" : \"marketing/\"\n") + .customCoordinates("customCoordinates") + .customMetadata( + FileUploadParams.CustomMetadata.builder() + .putAdditionalProperty("brand", JsonValue.from("bar")) + .putAdditionalProperty("color", JsonValue.from("bar")) + .build() + ) + .description("Running shoes") + .expire(0L) + .extensions( + listOf( + UnnamedSchemaWithArrayParent3.ofRemoveBg( + UnnamedSchemaWithArrayParent3.RemoveBg.builder() + .options( + UnnamedSchemaWithArrayParent3.RemoveBg.Options.builder() + .addShadow(true) + .bgColor("bg_color") + .bgImageUrl("bg_image_url") + .semitransparency(true) + .build() + ) + .build() + ), + UnnamedSchemaWithArrayParent3.ofAutoTaggingExtension( + UnnamedSchemaWithArrayParent3.AutoTaggingExtension.builder() + .maxTags(5L) + .minConfidence(95L) + .name( + UnnamedSchemaWithArrayParent3.AutoTaggingExtension.Name + .GOOGLE_AUTO_TAGGING + ) + .build() + ), + UnnamedSchemaWithArrayParent3.ofAiAutoDescription(), + ) + ) + .folder("folder") + .isPrivateFile(true) + .isPublished(true) + .overwriteAiTags(true) + .overwriteCustomMetadata(true) + .overwriteFile(true) + .overwriteTags(true) + .publicKey("publicKey") + .responseFields( + listOf( + FileUploadParams.ResponseField.TAGS, + FileUploadParams.ResponseField.CUSTOM_COORDINATES, + FileUploadParams.ResponseField.IS_PRIVATE_FILE, + ) + ) + .signature("signature") + .tags(listOf("t-shirt", "round-neck", "men")) + .transformation( + FileUploadParams.Transformation.builder() + .addPost( + FileUploadParams.Transformation.Post.Thumbnail.builder() + .value("w-150,h-150") + .build() + ) + .addPost( + FileUploadParams.Transformation.Post.Abs.builder() + .protocol(FileUploadParams.Transformation.Post.Abs.Protocol.DASH) + .value("sr-240_360_480_720_1080") + .build() + ) + .pre("w-300,h-300,q-80") + .build() + ) + .useUniqueFileName(true) + .webhookUrl("https://example.com") + .build() + + val body = params._body() + + assertThat(body.filterValues { !it.value.isNull() }) + .usingRecursiveComparison() + // TODO(AssertJ): Replace this and the `mapValues` below with: + // https://github.com/assertj/assertj/issues/3165 + .withEqualsForType( + { a, b -> a.readBytes() contentEquals b.readBytes() }, + InputStream::class.java, + ) + .isEqualTo( + mapOf( + "file" to MultipartField.of("some content".byteInputStream()), + "fileName" to MultipartField.of("fileName"), + "token" to MultipartField.of("token"), + "checks" to MultipartField.of("\"request.folder\" : \"marketing/\"\n"), + "customCoordinates" to MultipartField.of("customCoordinates"), + "customMetadata" to + MultipartField.of( + FileUploadParams.CustomMetadata.builder() + .putAdditionalProperty("brand", JsonValue.from("bar")) + .putAdditionalProperty("color", JsonValue.from("bar")) + .build() + ), + "description" to MultipartField.of("Running shoes"), + "expire" to MultipartField.of(0L), + "extensions" to + MultipartField.of( + listOf( + UnnamedSchemaWithArrayParent3.ofRemoveBg( + UnnamedSchemaWithArrayParent3.RemoveBg.builder() + .options( + UnnamedSchemaWithArrayParent3.RemoveBg.Options + .builder() + .addShadow(true) + .bgColor("bg_color") + .bgImageUrl("bg_image_url") + .semitransparency(true) + .build() + ) + .build() + ), + UnnamedSchemaWithArrayParent3.ofAutoTaggingExtension( + UnnamedSchemaWithArrayParent3.AutoTaggingExtension.builder() + .maxTags(5L) + .minConfidence(95L) + .name( + UnnamedSchemaWithArrayParent3.AutoTaggingExtension + .Name + .GOOGLE_AUTO_TAGGING + ) + .build() + ), + UnnamedSchemaWithArrayParent3.ofAiAutoDescription(), + ) + ), + "folder" to MultipartField.of("folder"), + "isPrivateFile" to MultipartField.of(true), + "isPublished" to MultipartField.of(true), + "overwriteAITags" to MultipartField.of(true), + "overwriteCustomMetadata" to MultipartField.of(true), + "overwriteFile" to MultipartField.of(true), + "overwriteTags" to MultipartField.of(true), + "publicKey" to MultipartField.of("publicKey"), + "responseFields" to + MultipartField.of( + listOf( + FileUploadParams.ResponseField.TAGS, + FileUploadParams.ResponseField.CUSTOM_COORDINATES, + FileUploadParams.ResponseField.IS_PRIVATE_FILE, + ) + ), + "signature" to MultipartField.of("signature"), + "tags" to MultipartField.of(listOf("t-shirt", "round-neck", "men")), + "transformation" to + MultipartField.of( + FileUploadParams.Transformation.builder() + .addPost( + FileUploadParams.Transformation.Post.Thumbnail.builder() + .value("w-150,h-150") + .build() + ) + .addPost( + FileUploadParams.Transformation.Post.Abs.builder() + .protocol( + FileUploadParams.Transformation.Post.Abs.Protocol + .DASH + ) + .value("sr-240_360_480_720_1080") + .build() + ) + .pre("w-300,h-300,q-80") + .build() + ), + "useUniqueFileName" to MultipartField.of(true), + "webhookUrl" to MultipartField.of("https://example.com"), + ) + .mapValues { (_, field) -> + field.map { (it as? ByteArray)?.inputStream() ?: it } + } + ) + } + + @Test + fun bodyWithoutOptionalFields() { + val params = + FileUploadParams.builder() + .file("some content".byteInputStream()) + .fileName("fileName") + .build() + + val body = params._body() + + assertThat(body.filterValues { !it.value.isNull() }) + .usingRecursiveComparison() + // TODO(AssertJ): Replace this and the `mapValues` below with: + // https://github.com/assertj/assertj/issues/3165 + .withEqualsForType( + { a, b -> a.readBytes() contentEquals b.readBytes() }, + InputStream::class.java, + ) + .isEqualTo( + mapOf( + "file" to MultipartField.of("some content".byteInputStream()), + "fileName" to MultipartField.of("fileName"), + ) + .mapValues { (_, field) -> + field.map { (it as? ByteArray)?.inputStream() ?: it } + } + ) + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/files/FileUploadResponseTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/files/FileUploadResponseTest.kt new file mode 100644 index 0000000..48c228e --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/files/FileUploadResponseTest.kt @@ -0,0 +1,447 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.files + +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.imagekit.api.core.JsonValue +import com.imagekit.api.core.jsonMapper +import kotlin.jvm.optionals.getOrNull +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class FileUploadResponseTest { + + @Test + fun create() { + val fileUploadResponse = + FileUploadResponse.builder() + .addAiTag( + FileUploadResponse.AiTag.builder() + .confidence(0.0) + .name("name") + .source("source") + .build() + ) + .audioCodec("audioCodec") + .bitRate(0L) + .customCoordinates("customCoordinates") + .customMetadata( + FileUploadResponse.CustomMetadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .description("description") + .duration(0L) + .embeddedMetadata( + FileUploadResponse.EmbeddedMetadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .extensionStatus( + FileUploadResponse.ExtensionStatus.builder() + .aiAutoDescription( + FileUploadResponse.ExtensionStatus.AiAutoDescription.SUCCESS + ) + .awsAutoTagging(FileUploadResponse.ExtensionStatus.AwsAutoTagging.SUCCESS) + .googleAutoTagging( + FileUploadResponse.ExtensionStatus.GoogleAutoTagging.SUCCESS + ) + .removeBg(FileUploadResponse.ExtensionStatus.RemoveBg.SUCCESS) + .build() + ) + .fileId("fileId") + .filePath("filePath") + .fileType("fileType") + .height(0.0) + .isPrivateFile(true) + .isPublished(true) + .metadata( + Metadata.builder() + .audioCodec("audioCodec") + .bitRate(0L) + .density(0L) + .duration(0L) + .exif( + Metadata.Exif.builder() + .exif( + Metadata.Exif.InnerExif.builder() + .apertureValue(0.0) + .colorSpace(0L) + .createDate("CreateDate") + .customRendered(0L) + .dateTimeOriginal("DateTimeOriginal") + .exifImageHeight(0L) + .exifImageWidth(0L) + .exifVersion("ExifVersion") + .exposureCompensation(0.0) + .exposureMode(0L) + .exposureProgram(0L) + .exposureTime(0.0) + .flash(0L) + .flashpixVersion("FlashpixVersion") + .fNumber(0.0) + .focalLength(0L) + .focalPlaneResolutionUnit(0L) + .focalPlaneXResolution(0.0) + .focalPlaneYResolution(0.0) + .interopOffset(0L) + .iso(0L) + .meteringMode(0L) + .sceneCaptureType(0L) + .shutterSpeedValue(0.0) + .subSecTime("SubSecTime") + .whiteBalance(0L) + .build() + ) + .gps(Metadata.Exif.Gps.builder().addGpsVersionId(0L).build()) + .image( + Metadata.Exif.Image.builder() + .exifOffset(0L) + .gpsInfo(0L) + .make("Make") + .model("Model") + .modifyDate("ModifyDate") + .orientation(0L) + .resolutionUnit(0L) + .software("Software") + .xResolution(0L) + .yCbCrPositioning(0L) + .yResolution(0L) + .build() + ) + .interoperability( + Metadata.Exif.Interoperability.builder() + .interopIndex("InteropIndex") + .interopVersion("InteropVersion") + .build() + ) + .makernote( + Metadata.Exif.Makernote.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .thumbnail( + Metadata.Exif.Thumbnail.builder() + .compression(0L) + .resolutionUnit(0L) + .thumbnailLength(0L) + .thumbnailOffset(0L) + .xResolution(0L) + .yResolution(0L) + .build() + ) + .build() + ) + .format("format") + .hasColorProfile(true) + .hasTransparency(true) + .height(0L) + .pHash("pHash") + .quality(0L) + .size(0L) + .videoCodec("videoCodec") + .width(0L) + .build() + ) + .name("name") + .size(0.0) + .addTag("string") + .thumbnailUrl("thumbnailUrl") + .url("url") + .versionInfo(FileUploadResponse.VersionInfo.builder().id("id").name("name").build()) + .videoCodec("videoCodec") + .width(0.0) + .build() + + assertThat(fileUploadResponse.aiTags().getOrNull()) + .containsExactly( + FileUploadResponse.AiTag.builder() + .confidence(0.0) + .name("name") + .source("source") + .build() + ) + assertThat(fileUploadResponse.audioCodec()).contains("audioCodec") + assertThat(fileUploadResponse.bitRate()).contains(0L) + assertThat(fileUploadResponse.customCoordinates()).contains("customCoordinates") + assertThat(fileUploadResponse.customMetadata()) + .contains( + FileUploadResponse.CustomMetadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + assertThat(fileUploadResponse.description()).contains("description") + assertThat(fileUploadResponse.duration()).contains(0L) + assertThat(fileUploadResponse.embeddedMetadata()) + .contains( + FileUploadResponse.EmbeddedMetadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + assertThat(fileUploadResponse.extensionStatus()) + .contains( + FileUploadResponse.ExtensionStatus.builder() + .aiAutoDescription(FileUploadResponse.ExtensionStatus.AiAutoDescription.SUCCESS) + .awsAutoTagging(FileUploadResponse.ExtensionStatus.AwsAutoTagging.SUCCESS) + .googleAutoTagging(FileUploadResponse.ExtensionStatus.GoogleAutoTagging.SUCCESS) + .removeBg(FileUploadResponse.ExtensionStatus.RemoveBg.SUCCESS) + .build() + ) + assertThat(fileUploadResponse.fileId()).contains("fileId") + assertThat(fileUploadResponse.filePath()).contains("filePath") + assertThat(fileUploadResponse.fileType()).contains("fileType") + assertThat(fileUploadResponse.height()).contains(0.0) + assertThat(fileUploadResponse.isPrivateFile()).contains(true) + assertThat(fileUploadResponse.isPublished()).contains(true) + assertThat(fileUploadResponse.metadata()) + .contains( + Metadata.builder() + .audioCodec("audioCodec") + .bitRate(0L) + .density(0L) + .duration(0L) + .exif( + Metadata.Exif.builder() + .exif( + Metadata.Exif.InnerExif.builder() + .apertureValue(0.0) + .colorSpace(0L) + .createDate("CreateDate") + .customRendered(0L) + .dateTimeOriginal("DateTimeOriginal") + .exifImageHeight(0L) + .exifImageWidth(0L) + .exifVersion("ExifVersion") + .exposureCompensation(0.0) + .exposureMode(0L) + .exposureProgram(0L) + .exposureTime(0.0) + .flash(0L) + .flashpixVersion("FlashpixVersion") + .fNumber(0.0) + .focalLength(0L) + .focalPlaneResolutionUnit(0L) + .focalPlaneXResolution(0.0) + .focalPlaneYResolution(0.0) + .interopOffset(0L) + .iso(0L) + .meteringMode(0L) + .sceneCaptureType(0L) + .shutterSpeedValue(0.0) + .subSecTime("SubSecTime") + .whiteBalance(0L) + .build() + ) + .gps(Metadata.Exif.Gps.builder().addGpsVersionId(0L).build()) + .image( + Metadata.Exif.Image.builder() + .exifOffset(0L) + .gpsInfo(0L) + .make("Make") + .model("Model") + .modifyDate("ModifyDate") + .orientation(0L) + .resolutionUnit(0L) + .software("Software") + .xResolution(0L) + .yCbCrPositioning(0L) + .yResolution(0L) + .build() + ) + .interoperability( + Metadata.Exif.Interoperability.builder() + .interopIndex("InteropIndex") + .interopVersion("InteropVersion") + .build() + ) + .makernote( + Metadata.Exif.Makernote.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .thumbnail( + Metadata.Exif.Thumbnail.builder() + .compression(0L) + .resolutionUnit(0L) + .thumbnailLength(0L) + .thumbnailOffset(0L) + .xResolution(0L) + .yResolution(0L) + .build() + ) + .build() + ) + .format("format") + .hasColorProfile(true) + .hasTransparency(true) + .height(0L) + .pHash("pHash") + .quality(0L) + .size(0L) + .videoCodec("videoCodec") + .width(0L) + .build() + ) + assertThat(fileUploadResponse.name()).contains("name") + assertThat(fileUploadResponse.size()).contains(0.0) + assertThat(fileUploadResponse.tags().getOrNull()).containsExactly("string") + assertThat(fileUploadResponse.thumbnailUrl()).contains("thumbnailUrl") + assertThat(fileUploadResponse.url()).contains("url") + assertThat(fileUploadResponse.versionInfo()) + .contains(FileUploadResponse.VersionInfo.builder().id("id").name("name").build()) + assertThat(fileUploadResponse.videoCodec()).contains("videoCodec") + assertThat(fileUploadResponse.width()).contains(0.0) + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val fileUploadResponse = + FileUploadResponse.builder() + .addAiTag( + FileUploadResponse.AiTag.builder() + .confidence(0.0) + .name("name") + .source("source") + .build() + ) + .audioCodec("audioCodec") + .bitRate(0L) + .customCoordinates("customCoordinates") + .customMetadata( + FileUploadResponse.CustomMetadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .description("description") + .duration(0L) + .embeddedMetadata( + FileUploadResponse.EmbeddedMetadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .extensionStatus( + FileUploadResponse.ExtensionStatus.builder() + .aiAutoDescription( + FileUploadResponse.ExtensionStatus.AiAutoDescription.SUCCESS + ) + .awsAutoTagging(FileUploadResponse.ExtensionStatus.AwsAutoTagging.SUCCESS) + .googleAutoTagging( + FileUploadResponse.ExtensionStatus.GoogleAutoTagging.SUCCESS + ) + .removeBg(FileUploadResponse.ExtensionStatus.RemoveBg.SUCCESS) + .build() + ) + .fileId("fileId") + .filePath("filePath") + .fileType("fileType") + .height(0.0) + .isPrivateFile(true) + .isPublished(true) + .metadata( + Metadata.builder() + .audioCodec("audioCodec") + .bitRate(0L) + .density(0L) + .duration(0L) + .exif( + Metadata.Exif.builder() + .exif( + Metadata.Exif.InnerExif.builder() + .apertureValue(0.0) + .colorSpace(0L) + .createDate("CreateDate") + .customRendered(0L) + .dateTimeOriginal("DateTimeOriginal") + .exifImageHeight(0L) + .exifImageWidth(0L) + .exifVersion("ExifVersion") + .exposureCompensation(0.0) + .exposureMode(0L) + .exposureProgram(0L) + .exposureTime(0.0) + .flash(0L) + .flashpixVersion("FlashpixVersion") + .fNumber(0.0) + .focalLength(0L) + .focalPlaneResolutionUnit(0L) + .focalPlaneXResolution(0.0) + .focalPlaneYResolution(0.0) + .interopOffset(0L) + .iso(0L) + .meteringMode(0L) + .sceneCaptureType(0L) + .shutterSpeedValue(0.0) + .subSecTime("SubSecTime") + .whiteBalance(0L) + .build() + ) + .gps(Metadata.Exif.Gps.builder().addGpsVersionId(0L).build()) + .image( + Metadata.Exif.Image.builder() + .exifOffset(0L) + .gpsInfo(0L) + .make("Make") + .model("Model") + .modifyDate("ModifyDate") + .orientation(0L) + .resolutionUnit(0L) + .software("Software") + .xResolution(0L) + .yCbCrPositioning(0L) + .yResolution(0L) + .build() + ) + .interoperability( + Metadata.Exif.Interoperability.builder() + .interopIndex("InteropIndex") + .interopVersion("InteropVersion") + .build() + ) + .makernote( + Metadata.Exif.Makernote.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .thumbnail( + Metadata.Exif.Thumbnail.builder() + .compression(0L) + .resolutionUnit(0L) + .thumbnailLength(0L) + .thumbnailOffset(0L) + .xResolution(0L) + .yResolution(0L) + .build() + ) + .build() + ) + .format("format") + .hasColorProfile(true) + .hasTransparency(true) + .height(0L) + .pHash("pHash") + .quality(0L) + .size(0L) + .videoCodec("videoCodec") + .width(0L) + .build() + ) + .name("name") + .size(0.0) + .addTag("string") + .thumbnailUrl("thumbnailUrl") + .url("url") + .versionInfo(FileUploadResponse.VersionInfo.builder().id("id").name("name").build()) + .videoCodec("videoCodec") + .width(0.0) + .build() + + val roundtrippedFileUploadResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(fileUploadResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedFileUploadResponse).isEqualTo(fileUploadResponse) + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/files/FolderTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/files/FolderTest.kt new file mode 100644 index 0000000..e4c406e --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/files/FolderTest.kt @@ -0,0 +1,51 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.files + +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.imagekit.api.core.jsonMapper +import java.time.OffsetDateTime +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class FolderTest { + + @Test + fun create() { + val folder = + Folder.builder() + .createdAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .folderId("folderId") + .folderPath("folderPath") + .name("name") + .type(Folder.Type.FOLDER) + .updatedAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .build() + + assertThat(folder.createdAt()).contains(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + assertThat(folder.folderId()).contains("folderId") + assertThat(folder.folderPath()).contains("folderPath") + assertThat(folder.name()).contains("name") + assertThat(folder.type()).contains(Folder.Type.FOLDER) + assertThat(folder.updatedAt()).contains(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val folder = + Folder.builder() + .createdAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .folderId("folderId") + .folderPath("folderPath") + .name("name") + .type(Folder.Type.FOLDER) + .updatedAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .build() + + val roundtrippedFolder = + jsonMapper.readValue(jsonMapper.writeValueAsString(folder), jacksonTypeRef()) + + assertThat(roundtrippedFolder).isEqualTo(folder) + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/files/MetadataTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/files/MetadataTest.kt new file mode 100644 index 0000000..aacb71c --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/files/MetadataTest.kt @@ -0,0 +1,289 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.files + +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.imagekit.api.core.JsonValue +import com.imagekit.api.core.jsonMapper +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class MetadataTest { + + @Test + fun create() { + val metadata = + Metadata.builder() + .audioCodec("audioCodec") + .bitRate(0L) + .density(0L) + .duration(0L) + .exif( + Metadata.Exif.builder() + .exif( + Metadata.Exif.InnerExif.builder() + .apertureValue(0.0) + .colorSpace(0L) + .createDate("CreateDate") + .customRendered(0L) + .dateTimeOriginal("DateTimeOriginal") + .exifImageHeight(0L) + .exifImageWidth(0L) + .exifVersion("ExifVersion") + .exposureCompensation(0.0) + .exposureMode(0L) + .exposureProgram(0L) + .exposureTime(0.0) + .flash(0L) + .flashpixVersion("FlashpixVersion") + .fNumber(0.0) + .focalLength(0L) + .focalPlaneResolutionUnit(0L) + .focalPlaneXResolution(0.0) + .focalPlaneYResolution(0.0) + .interopOffset(0L) + .iso(0L) + .meteringMode(0L) + .sceneCaptureType(0L) + .shutterSpeedValue(0.0) + .subSecTime("SubSecTime") + .whiteBalance(0L) + .build() + ) + .gps(Metadata.Exif.Gps.builder().addGpsVersionId(0L).build()) + .image( + Metadata.Exif.Image.builder() + .exifOffset(0L) + .gpsInfo(0L) + .make("Make") + .model("Model") + .modifyDate("ModifyDate") + .orientation(0L) + .resolutionUnit(0L) + .software("Software") + .xResolution(0L) + .yCbCrPositioning(0L) + .yResolution(0L) + .build() + ) + .interoperability( + Metadata.Exif.Interoperability.builder() + .interopIndex("InteropIndex") + .interopVersion("InteropVersion") + .build() + ) + .makernote( + Metadata.Exif.Makernote.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .thumbnail( + Metadata.Exif.Thumbnail.builder() + .compression(0L) + .resolutionUnit(0L) + .thumbnailLength(0L) + .thumbnailOffset(0L) + .xResolution(0L) + .yResolution(0L) + .build() + ) + .build() + ) + .format("format") + .hasColorProfile(true) + .hasTransparency(true) + .height(0L) + .pHash("pHash") + .quality(0L) + .size(0L) + .videoCodec("videoCodec") + .width(0L) + .build() + + assertThat(metadata.audioCodec()).contains("audioCodec") + assertThat(metadata.bitRate()).contains(0L) + assertThat(metadata.density()).contains(0L) + assertThat(metadata.duration()).contains(0L) + assertThat(metadata.exif()) + .contains( + Metadata.Exif.builder() + .exif( + Metadata.Exif.InnerExif.builder() + .apertureValue(0.0) + .colorSpace(0L) + .createDate("CreateDate") + .customRendered(0L) + .dateTimeOriginal("DateTimeOriginal") + .exifImageHeight(0L) + .exifImageWidth(0L) + .exifVersion("ExifVersion") + .exposureCompensation(0.0) + .exposureMode(0L) + .exposureProgram(0L) + .exposureTime(0.0) + .flash(0L) + .flashpixVersion("FlashpixVersion") + .fNumber(0.0) + .focalLength(0L) + .focalPlaneResolutionUnit(0L) + .focalPlaneXResolution(0.0) + .focalPlaneYResolution(0.0) + .interopOffset(0L) + .iso(0L) + .meteringMode(0L) + .sceneCaptureType(0L) + .shutterSpeedValue(0.0) + .subSecTime("SubSecTime") + .whiteBalance(0L) + .build() + ) + .gps(Metadata.Exif.Gps.builder().addGpsVersionId(0L).build()) + .image( + Metadata.Exif.Image.builder() + .exifOffset(0L) + .gpsInfo(0L) + .make("Make") + .model("Model") + .modifyDate("ModifyDate") + .orientation(0L) + .resolutionUnit(0L) + .software("Software") + .xResolution(0L) + .yCbCrPositioning(0L) + .yResolution(0L) + .build() + ) + .interoperability( + Metadata.Exif.Interoperability.builder() + .interopIndex("InteropIndex") + .interopVersion("InteropVersion") + .build() + ) + .makernote( + Metadata.Exif.Makernote.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .thumbnail( + Metadata.Exif.Thumbnail.builder() + .compression(0L) + .resolutionUnit(0L) + .thumbnailLength(0L) + .thumbnailOffset(0L) + .xResolution(0L) + .yResolution(0L) + .build() + ) + .build() + ) + assertThat(metadata.format()).contains("format") + assertThat(metadata.hasColorProfile()).contains(true) + assertThat(metadata.hasTransparency()).contains(true) + assertThat(metadata.height()).contains(0L) + assertThat(metadata.pHash()).contains("pHash") + assertThat(metadata.quality()).contains(0L) + assertThat(metadata.size()).contains(0L) + assertThat(metadata.videoCodec()).contains("videoCodec") + assertThat(metadata.width()).contains(0L) + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val metadata = + Metadata.builder() + .audioCodec("audioCodec") + .bitRate(0L) + .density(0L) + .duration(0L) + .exif( + Metadata.Exif.builder() + .exif( + Metadata.Exif.InnerExif.builder() + .apertureValue(0.0) + .colorSpace(0L) + .createDate("CreateDate") + .customRendered(0L) + .dateTimeOriginal("DateTimeOriginal") + .exifImageHeight(0L) + .exifImageWidth(0L) + .exifVersion("ExifVersion") + .exposureCompensation(0.0) + .exposureMode(0L) + .exposureProgram(0L) + .exposureTime(0.0) + .flash(0L) + .flashpixVersion("FlashpixVersion") + .fNumber(0.0) + .focalLength(0L) + .focalPlaneResolutionUnit(0L) + .focalPlaneXResolution(0.0) + .focalPlaneYResolution(0.0) + .interopOffset(0L) + .iso(0L) + .meteringMode(0L) + .sceneCaptureType(0L) + .shutterSpeedValue(0.0) + .subSecTime("SubSecTime") + .whiteBalance(0L) + .build() + ) + .gps(Metadata.Exif.Gps.builder().addGpsVersionId(0L).build()) + .image( + Metadata.Exif.Image.builder() + .exifOffset(0L) + .gpsInfo(0L) + .make("Make") + .model("Model") + .modifyDate("ModifyDate") + .orientation(0L) + .resolutionUnit(0L) + .software("Software") + .xResolution(0L) + .yCbCrPositioning(0L) + .yResolution(0L) + .build() + ) + .interoperability( + Metadata.Exif.Interoperability.builder() + .interopIndex("InteropIndex") + .interopVersion("InteropVersion") + .build() + ) + .makernote( + Metadata.Exif.Makernote.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .thumbnail( + Metadata.Exif.Thumbnail.builder() + .compression(0L) + .resolutionUnit(0L) + .thumbnailLength(0L) + .thumbnailOffset(0L) + .xResolution(0L) + .yResolution(0L) + .build() + ) + .build() + ) + .format("format") + .hasColorProfile(true) + .hasTransparency(true) + .height(0L) + .pHash("pHash") + .quality(0L) + .size(0L) + .videoCodec("videoCodec") + .width(0L) + .build() + + val roundtrippedMetadata = + jsonMapper.readValue( + jsonMapper.writeValueAsString(metadata), + jacksonTypeRef(), + ) + + assertThat(roundtrippedMetadata).isEqualTo(metadata) + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/files/bulk/BulkAddTagsParamsTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/files/bulk/BulkAddTagsParamsTest.kt new file mode 100644 index 0000000..e4f8750 --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/files/bulk/BulkAddTagsParamsTest.kt @@ -0,0 +1,34 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.files.bulk + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class BulkAddTagsParamsTest { + + @Test + fun create() { + BulkAddTagsParams.builder() + .addFileId("598821f949c0a938d57563bd") + .addFileId("598821f949c0a938d57563be") + .tags(listOf("t-shirt", "round-neck", "sale2019")) + .build() + } + + @Test + fun body() { + val params = + BulkAddTagsParams.builder() + .addFileId("598821f949c0a938d57563bd") + .addFileId("598821f949c0a938d57563be") + .tags(listOf("t-shirt", "round-neck", "sale2019")) + .build() + + val body = params._body() + + assertThat(body.fileIds()) + .containsExactly("598821f949c0a938d57563bd", "598821f949c0a938d57563be") + assertThat(body.tags()).containsExactly("t-shirt", "round-neck", "sale2019") + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/files/bulk/BulkAddTagsResponseTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/files/bulk/BulkAddTagsResponseTest.kt new file mode 100644 index 0000000..78d57ab --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/files/bulk/BulkAddTagsResponseTest.kt @@ -0,0 +1,36 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.files.bulk + +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.imagekit.api.core.jsonMapper +import kotlin.jvm.optionals.getOrNull +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class BulkAddTagsResponseTest { + + @Test + fun create() { + val bulkAddTagsResponse = + BulkAddTagsResponse.builder().addSuccessfullyUpdatedFileId("string").build() + + assertThat(bulkAddTagsResponse.successfullyUpdatedFileIds().getOrNull()) + .containsExactly("string") + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val bulkAddTagsResponse = + BulkAddTagsResponse.builder().addSuccessfullyUpdatedFileId("string").build() + + val roundtrippedBulkAddTagsResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(bulkAddTagsResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedBulkAddTagsResponse).isEqualTo(bulkAddTagsResponse) + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/files/bulk/BulkDeleteParamsTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/files/bulk/BulkDeleteParamsTest.kt new file mode 100644 index 0000000..c7ff476 --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/files/bulk/BulkDeleteParamsTest.kt @@ -0,0 +1,31 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.files.bulk + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class BulkDeleteParamsTest { + + @Test + fun create() { + BulkDeleteParams.builder() + .addFileId("598821f949c0a938d57563bd") + .addFileId("598821f949c0a938d57563be") + .build() + } + + @Test + fun body() { + val params = + BulkDeleteParams.builder() + .addFileId("598821f949c0a938d57563bd") + .addFileId("598821f949c0a938d57563be") + .build() + + val body = params._body() + + assertThat(body.fileIds()) + .containsExactly("598821f949c0a938d57563bd", "598821f949c0a938d57563be") + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/files/bulk/BulkDeleteResponseTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/files/bulk/BulkDeleteResponseTest.kt new file mode 100644 index 0000000..f0b7a28 --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/files/bulk/BulkDeleteResponseTest.kt @@ -0,0 +1,36 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.files.bulk + +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.imagekit.api.core.jsonMapper +import kotlin.jvm.optionals.getOrNull +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class BulkDeleteResponseTest { + + @Test + fun create() { + val bulkDeleteResponse = + BulkDeleteResponse.builder().addSuccessfullyDeletedFileId("string").build() + + assertThat(bulkDeleteResponse.successfullyDeletedFileIds().getOrNull()) + .containsExactly("string") + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val bulkDeleteResponse = + BulkDeleteResponse.builder().addSuccessfullyDeletedFileId("string").build() + + val roundtrippedBulkDeleteResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(bulkDeleteResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedBulkDeleteResponse).isEqualTo(bulkDeleteResponse) + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/files/bulk/BulkRemoveAiTagsParamsTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/files/bulk/BulkRemoveAiTagsParamsTest.kt new file mode 100644 index 0000000..21a08ec --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/files/bulk/BulkRemoveAiTagsParamsTest.kt @@ -0,0 +1,34 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.files.bulk + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class BulkRemoveAiTagsParamsTest { + + @Test + fun create() { + BulkRemoveAiTagsParams.builder() + .aiTags(listOf("t-shirt", "round-neck", "sale2019")) + .addFileId("598821f949c0a938d57563bd") + .addFileId("598821f949c0a938d57563be") + .build() + } + + @Test + fun body() { + val params = + BulkRemoveAiTagsParams.builder() + .aiTags(listOf("t-shirt", "round-neck", "sale2019")) + .addFileId("598821f949c0a938d57563bd") + .addFileId("598821f949c0a938d57563be") + .build() + + val body = params._body() + + assertThat(body.aiTags()).containsExactly("t-shirt", "round-neck", "sale2019") + assertThat(body.fileIds()) + .containsExactly("598821f949c0a938d57563bd", "598821f949c0a938d57563be") + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/files/bulk/BulkRemoveAiTagsResponseTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/files/bulk/BulkRemoveAiTagsResponseTest.kt new file mode 100644 index 0000000..f483100 --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/files/bulk/BulkRemoveAiTagsResponseTest.kt @@ -0,0 +1,36 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.files.bulk + +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.imagekit.api.core.jsonMapper +import kotlin.jvm.optionals.getOrNull +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class BulkRemoveAiTagsResponseTest { + + @Test + fun create() { + val bulkRemoveAiTagsResponse = + BulkRemoveAiTagsResponse.builder().addSuccessfullyUpdatedFileId("string").build() + + assertThat(bulkRemoveAiTagsResponse.successfullyUpdatedFileIds().getOrNull()) + .containsExactly("string") + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val bulkRemoveAiTagsResponse = + BulkRemoveAiTagsResponse.builder().addSuccessfullyUpdatedFileId("string").build() + + val roundtrippedBulkRemoveAiTagsResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(bulkRemoveAiTagsResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedBulkRemoveAiTagsResponse).isEqualTo(bulkRemoveAiTagsResponse) + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/files/bulk/BulkRemoveTagsParamsTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/files/bulk/BulkRemoveTagsParamsTest.kt new file mode 100644 index 0000000..0f1de44 --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/files/bulk/BulkRemoveTagsParamsTest.kt @@ -0,0 +1,34 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.files.bulk + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class BulkRemoveTagsParamsTest { + + @Test + fun create() { + BulkRemoveTagsParams.builder() + .addFileId("598821f949c0a938d57563bd") + .addFileId("598821f949c0a938d57563be") + .tags(listOf("t-shirt", "round-neck", "sale2019")) + .build() + } + + @Test + fun body() { + val params = + BulkRemoveTagsParams.builder() + .addFileId("598821f949c0a938d57563bd") + .addFileId("598821f949c0a938d57563be") + .tags(listOf("t-shirt", "round-neck", "sale2019")) + .build() + + val body = params._body() + + assertThat(body.fileIds()) + .containsExactly("598821f949c0a938d57563bd", "598821f949c0a938d57563be") + assertThat(body.tags()).containsExactly("t-shirt", "round-neck", "sale2019") + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/files/bulk/BulkRemoveTagsResponseTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/files/bulk/BulkRemoveTagsResponseTest.kt new file mode 100644 index 0000000..ce35438 --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/files/bulk/BulkRemoveTagsResponseTest.kt @@ -0,0 +1,36 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.files.bulk + +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.imagekit.api.core.jsonMapper +import kotlin.jvm.optionals.getOrNull +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class BulkRemoveTagsResponseTest { + + @Test + fun create() { + val bulkRemoveTagsResponse = + BulkRemoveTagsResponse.builder().addSuccessfullyUpdatedFileId("string").build() + + assertThat(bulkRemoveTagsResponse.successfullyUpdatedFileIds().getOrNull()) + .containsExactly("string") + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val bulkRemoveTagsResponse = + BulkRemoveTagsResponse.builder().addSuccessfullyUpdatedFileId("string").build() + + val roundtrippedBulkRemoveTagsResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(bulkRemoveTagsResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedBulkRemoveTagsResponse).isEqualTo(bulkRemoveTagsResponse) + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/files/metadata/MetadataGetFromUrlParamsTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/files/metadata/MetadataGetFromUrlParamsTest.kt new file mode 100644 index 0000000..2d4617b --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/files/metadata/MetadataGetFromUrlParamsTest.kt @@ -0,0 +1,25 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.files.metadata + +import com.imagekit.api.core.http.QueryParams +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class MetadataGetFromUrlParamsTest { + + @Test + fun create() { + MetadataGetFromUrlParams.builder().url("https://example.com").build() + } + + @Test + fun queryParams() { + val params = MetadataGetFromUrlParams.builder().url("https://example.com").build() + + val queryParams = params._queryParams() + + assertThat(queryParams) + .isEqualTo(QueryParams.builder().put("url", "https://example.com").build()) + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/files/metadata/MetadataGetParamsTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/files/metadata/MetadataGetParamsTest.kt new file mode 100644 index 0000000..566257d --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/files/metadata/MetadataGetParamsTest.kt @@ -0,0 +1,23 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.files.metadata + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class MetadataGetParamsTest { + + @Test + fun create() { + MetadataGetParams.builder().fileId("fileId").build() + } + + @Test + fun pathParams() { + val params = MetadataGetParams.builder().fileId("fileId").build() + + assertThat(params._pathParam(0)).isEqualTo("fileId") + // out-of-bound path param + assertThat(params._pathParam(1)).isEqualTo("") + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/files/versions/VersionDeleteParamsTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/files/versions/VersionDeleteParamsTest.kt new file mode 100644 index 0000000..67e06b9 --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/files/versions/VersionDeleteParamsTest.kt @@ -0,0 +1,24 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.files.versions + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class VersionDeleteParamsTest { + + @Test + fun create() { + VersionDeleteParams.builder().fileId("fileId").versionId("versionId").build() + } + + @Test + fun pathParams() { + val params = VersionDeleteParams.builder().fileId("fileId").versionId("versionId").build() + + assertThat(params._pathParam(0)).isEqualTo("fileId") + assertThat(params._pathParam(1)).isEqualTo("versionId") + // out-of-bound path param + assertThat(params._pathParam(2)).isEqualTo("") + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/files/versions/VersionDeleteResponseTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/files/versions/VersionDeleteResponseTest.kt new file mode 100644 index 0000000..c6c6c19 --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/files/versions/VersionDeleteResponseTest.kt @@ -0,0 +1,30 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.files.versions + +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.imagekit.api.core.jsonMapper +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class VersionDeleteResponseTest { + + @Test + fun create() { + val versionDeleteResponse = VersionDeleteResponse.builder().build() + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val versionDeleteResponse = VersionDeleteResponse.builder().build() + + val roundtrippedVersionDeleteResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(versionDeleteResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedVersionDeleteResponse).isEqualTo(versionDeleteResponse) + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/files/versions/VersionGetParamsTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/files/versions/VersionGetParamsTest.kt new file mode 100644 index 0000000..223c398 --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/files/versions/VersionGetParamsTest.kt @@ -0,0 +1,24 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.files.versions + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class VersionGetParamsTest { + + @Test + fun create() { + VersionGetParams.builder().fileId("fileId").versionId("versionId").build() + } + + @Test + fun pathParams() { + val params = VersionGetParams.builder().fileId("fileId").versionId("versionId").build() + + assertThat(params._pathParam(0)).isEqualTo("fileId") + assertThat(params._pathParam(1)).isEqualTo("versionId") + // out-of-bound path param + assertThat(params._pathParam(2)).isEqualTo("") + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/files/versions/VersionListParamsTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/files/versions/VersionListParamsTest.kt new file mode 100644 index 0000000..76dcfa0 --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/files/versions/VersionListParamsTest.kt @@ -0,0 +1,23 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.files.versions + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class VersionListParamsTest { + + @Test + fun create() { + VersionListParams.builder().fileId("fileId").build() + } + + @Test + fun pathParams() { + val params = VersionListParams.builder().fileId("fileId").build() + + assertThat(params._pathParam(0)).isEqualTo("fileId") + // out-of-bound path param + assertThat(params._pathParam(1)).isEqualTo("") + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/files/versions/VersionRestoreParamsTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/files/versions/VersionRestoreParamsTest.kt new file mode 100644 index 0000000..cb877ca --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/files/versions/VersionRestoreParamsTest.kt @@ -0,0 +1,24 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.files.versions + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class VersionRestoreParamsTest { + + @Test + fun create() { + VersionRestoreParams.builder().fileId("fileId").versionId("versionId").build() + } + + @Test + fun pathParams() { + val params = VersionRestoreParams.builder().fileId("fileId").versionId("versionId").build() + + assertThat(params._pathParam(0)).isEqualTo("fileId") + assertThat(params._pathParam(1)).isEqualTo("versionId") + // out-of-bound path param + assertThat(params._pathParam(2)).isEqualTo("") + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/folders/FolderCopyParamsTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/folders/FolderCopyParamsTest.kt new file mode 100644 index 0000000..2592d7a --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/folders/FolderCopyParamsTest.kt @@ -0,0 +1,48 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.folders + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class FolderCopyParamsTest { + + @Test + fun create() { + FolderCopyParams.builder() + .destinationPath("/path/of/destination/folder") + .sourceFolderPath("/path/of/source/folder") + .includeVersions(true) + .build() + } + + @Test + fun body() { + val params = + FolderCopyParams.builder() + .destinationPath("/path/of/destination/folder") + .sourceFolderPath("/path/of/source/folder") + .includeVersions(true) + .build() + + val body = params._body() + + assertThat(body.destinationPath()).isEqualTo("/path/of/destination/folder") + assertThat(body.sourceFolderPath()).isEqualTo("/path/of/source/folder") + assertThat(body.includeVersions()).contains(true) + } + + @Test + fun bodyWithoutOptionalFields() { + val params = + FolderCopyParams.builder() + .destinationPath("/path/of/destination/folder") + .sourceFolderPath("/path/of/source/folder") + .build() + + val body = params._body() + + assertThat(body.destinationPath()).isEqualTo("/path/of/destination/folder") + assertThat(body.sourceFolderPath()).isEqualTo("/path/of/source/folder") + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/folders/FolderCopyResponseTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/folders/FolderCopyResponseTest.kt new file mode 100644 index 0000000..43edd66 --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/folders/FolderCopyResponseTest.kt @@ -0,0 +1,32 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.folders + +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.imagekit.api.core.jsonMapper +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class FolderCopyResponseTest { + + @Test + fun create() { + val folderCopyResponse = FolderCopyResponse.builder().jobId("jobId").build() + + assertThat(folderCopyResponse.jobId()).isEqualTo("jobId") + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val folderCopyResponse = FolderCopyResponse.builder().jobId("jobId").build() + + val roundtrippedFolderCopyResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(folderCopyResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedFolderCopyResponse).isEqualTo(folderCopyResponse) + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/folders/FolderCreateParamsTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/folders/FolderCreateParamsTest.kt new file mode 100644 index 0000000..7f8ba55 --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/folders/FolderCreateParamsTest.kt @@ -0,0 +1,31 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.folders + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class FolderCreateParamsTest { + + @Test + fun create() { + FolderCreateParams.builder() + .folderName("summer") + .parentFolderPath("/product/images/") + .build() + } + + @Test + fun body() { + val params = + FolderCreateParams.builder() + .folderName("summer") + .parentFolderPath("/product/images/") + .build() + + val body = params._body() + + assertThat(body.folderName()).isEqualTo("summer") + assertThat(body.parentFolderPath()).isEqualTo("/product/images/") + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/folders/FolderCreateResponseTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/folders/FolderCreateResponseTest.kt new file mode 100644 index 0000000..de873d3 --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/folders/FolderCreateResponseTest.kt @@ -0,0 +1,30 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.folders + +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.imagekit.api.core.jsonMapper +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class FolderCreateResponseTest { + + @Test + fun create() { + val folderCreateResponse = FolderCreateResponse.builder().build() + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val folderCreateResponse = FolderCreateResponse.builder().build() + + val roundtrippedFolderCreateResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(folderCreateResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedFolderCreateResponse).isEqualTo(folderCreateResponse) + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/folders/FolderDeleteParamsTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/folders/FolderDeleteParamsTest.kt new file mode 100644 index 0000000..7a1a4fc --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/folders/FolderDeleteParamsTest.kt @@ -0,0 +1,23 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.folders + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class FolderDeleteParamsTest { + + @Test + fun create() { + FolderDeleteParams.builder().folderPath("/folder/to/delete/").build() + } + + @Test + fun body() { + val params = FolderDeleteParams.builder().folderPath("/folder/to/delete/").build() + + val body = params._body() + + assertThat(body.folderPath()).isEqualTo("/folder/to/delete/") + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/folders/FolderDeleteResponseTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/folders/FolderDeleteResponseTest.kt new file mode 100644 index 0000000..332055e --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/folders/FolderDeleteResponseTest.kt @@ -0,0 +1,30 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.folders + +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.imagekit.api.core.jsonMapper +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class FolderDeleteResponseTest { + + @Test + fun create() { + val folderDeleteResponse = FolderDeleteResponse.builder().build() + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val folderDeleteResponse = FolderDeleteResponse.builder().build() + + val roundtrippedFolderDeleteResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(folderDeleteResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedFolderDeleteResponse).isEqualTo(folderDeleteResponse) + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/folders/FolderMoveParamsTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/folders/FolderMoveParamsTest.kt new file mode 100644 index 0000000..7df75c0 --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/folders/FolderMoveParamsTest.kt @@ -0,0 +1,31 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.folders + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class FolderMoveParamsTest { + + @Test + fun create() { + FolderMoveParams.builder() + .destinationPath("/path/of/destination/folder") + .sourceFolderPath("/path/of/source/folder") + .build() + } + + @Test + fun body() { + val params = + FolderMoveParams.builder() + .destinationPath("/path/of/destination/folder") + .sourceFolderPath("/path/of/source/folder") + .build() + + val body = params._body() + + assertThat(body.destinationPath()).isEqualTo("/path/of/destination/folder") + assertThat(body.sourceFolderPath()).isEqualTo("/path/of/source/folder") + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/folders/FolderMoveResponseTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/folders/FolderMoveResponseTest.kt new file mode 100644 index 0000000..c0bbe47 --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/folders/FolderMoveResponseTest.kt @@ -0,0 +1,32 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.folders + +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.imagekit.api.core.jsonMapper +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class FolderMoveResponseTest { + + @Test + fun create() { + val folderMoveResponse = FolderMoveResponse.builder().jobId("jobId").build() + + assertThat(folderMoveResponse.jobId()).isEqualTo("jobId") + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val folderMoveResponse = FolderMoveResponse.builder().jobId("jobId").build() + + val roundtrippedFolderMoveResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(folderMoveResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedFolderMoveResponse).isEqualTo(folderMoveResponse) + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/folders/FolderRenameParamsTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/folders/FolderRenameParamsTest.kt new file mode 100644 index 0000000..46e4677 --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/folders/FolderRenameParamsTest.kt @@ -0,0 +1,48 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.folders + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class FolderRenameParamsTest { + + @Test + fun create() { + FolderRenameParams.builder() + .folderPath("/path/of/folder") + .newFolderName("new-folder-name") + .purgeCache(true) + .build() + } + + @Test + fun body() { + val params = + FolderRenameParams.builder() + .folderPath("/path/of/folder") + .newFolderName("new-folder-name") + .purgeCache(true) + .build() + + val body = params._body() + + assertThat(body.folderPath()).isEqualTo("/path/of/folder") + assertThat(body.newFolderName()).isEqualTo("new-folder-name") + assertThat(body.purgeCache()).contains(true) + } + + @Test + fun bodyWithoutOptionalFields() { + val params = + FolderRenameParams.builder() + .folderPath("/path/of/folder") + .newFolderName("new-folder-name") + .build() + + val body = params._body() + + assertThat(body.folderPath()).isEqualTo("/path/of/folder") + assertThat(body.newFolderName()).isEqualTo("new-folder-name") + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/folders/FolderRenameResponseTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/folders/FolderRenameResponseTest.kt new file mode 100644 index 0000000..73535f7 --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/folders/FolderRenameResponseTest.kt @@ -0,0 +1,32 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.folders + +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.imagekit.api.core.jsonMapper +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class FolderRenameResponseTest { + + @Test + fun create() { + val folderRenameResponse = FolderRenameResponse.builder().jobId("jobId").build() + + assertThat(folderRenameResponse.jobId()).isEqualTo("jobId") + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val folderRenameResponse = FolderRenameResponse.builder().jobId("jobId").build() + + val roundtrippedFolderRenameResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(folderRenameResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedFolderRenameResponse).isEqualTo(folderRenameResponse) + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/folders/job/JobGetParamsTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/folders/job/JobGetParamsTest.kt new file mode 100644 index 0000000..0128480 --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/folders/job/JobGetParamsTest.kt @@ -0,0 +1,23 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.folders.job + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class JobGetParamsTest { + + @Test + fun create() { + JobGetParams.builder().jobId("jobId").build() + } + + @Test + fun pathParams() { + val params = JobGetParams.builder().jobId("jobId").build() + + assertThat(params._pathParam(0)).isEqualTo("jobId") + // out-of-bound path param + assertThat(params._pathParam(1)).isEqualTo("") + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/folders/job/JobGetResponseTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/folders/job/JobGetResponseTest.kt new file mode 100644 index 0000000..502bf54 --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/folders/job/JobGetResponseTest.kt @@ -0,0 +1,47 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.folders.job + +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.imagekit.api.core.jsonMapper +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class JobGetResponseTest { + + @Test + fun create() { + val jobGetResponse = + JobGetResponse.builder() + .jobId("5d5b1a9b4c8c4c0001f3e4a2") + .purgeRequestId("purgeRequestId") + .status(JobGetResponse.Status.COMPLETED) + .type(JobGetResponse.Type.COPY_FOLDER) + .build() + + assertThat(jobGetResponse.jobId()).contains("5d5b1a9b4c8c4c0001f3e4a2") + assertThat(jobGetResponse.purgeRequestId()).contains("purgeRequestId") + assertThat(jobGetResponse.status()).contains(JobGetResponse.Status.COMPLETED) + assertThat(jobGetResponse.type()).contains(JobGetResponse.Type.COPY_FOLDER) + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val jobGetResponse = + JobGetResponse.builder() + .jobId("5d5b1a9b4c8c4c0001f3e4a2") + .purgeRequestId("purgeRequestId") + .status(JobGetResponse.Status.COMPLETED) + .type(JobGetResponse.Type.COPY_FOLDER) + .build() + + val roundtrippedJobGetResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(jobGetResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedJobGetResponse).isEqualTo(jobGetResponse) + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/webhooks/BaseWebhookEventTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/webhooks/BaseWebhookEventTest.kt new file mode 100644 index 0000000..577eb73 --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/webhooks/BaseWebhookEventTest.kt @@ -0,0 +1,33 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.webhooks + +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.imagekit.api.core.jsonMapper +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class BaseWebhookEventTest { + + @Test + fun create() { + val baseWebhookEvent = BaseWebhookEvent.builder().id("id").type("type").build() + + assertThat(baseWebhookEvent.id()).isEqualTo("id") + assertThat(baseWebhookEvent.type()).isEqualTo("type") + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val baseWebhookEvent = BaseWebhookEvent.builder().id("id").type("type").build() + + val roundtrippedBaseWebhookEvent = + jsonMapper.readValue( + jsonMapper.writeValueAsString(baseWebhookEvent), + jacksonTypeRef(), + ) + + assertThat(roundtrippedBaseWebhookEvent).isEqualTo(baseWebhookEvent) + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/webhooks/UnsafeUnwrapWebhookEventTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/webhooks/UnsafeUnwrapWebhookEventTest.kt new file mode 100644 index 0000000..b319bfe --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/webhooks/UnsafeUnwrapWebhookEventTest.kt @@ -0,0 +1,1239 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.webhooks + +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.imagekit.api.core.JsonValue +import com.imagekit.api.core.jsonMapper +import com.imagekit.api.errors.ImageKitInvalidDataException +import com.imagekit.api.models.files.Metadata +import java.time.OffsetDateTime +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.assertThrows +import org.junit.jupiter.params.ParameterizedTest +import org.junit.jupiter.params.provider.EnumSource + +internal class UnsafeUnwrapWebhookEventTest { + + @Test + fun ofVideoTransformationAccepted() { + val videoTransformationAccepted = + VideoTransformationAcceptedEvent.builder() + .id("id") + .type("video.transformation.accepted") + .createdAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .data( + VideoTransformationAcceptedEvent.Data.builder() + .asset( + VideoTransformationAcceptedEvent.Data.Asset.builder() + .url("https://example.com") + .build() + ) + .transformation( + VideoTransformationAcceptedEvent.Data.Transformation.builder() + .type( + VideoTransformationAcceptedEvent.Data.Transformation.Type + .VIDEO_TRANSFORMATION + ) + .options( + VideoTransformationAcceptedEvent.Data.Transformation.Options + .builder() + .audioCodec( + VideoTransformationAcceptedEvent.Data.Transformation + .Options + .AudioCodec + .AAC + ) + .autoRotate(true) + .format( + VideoTransformationAcceptedEvent.Data.Transformation + .Options + .Format + .MP4 + ) + .quality(0L) + .streamProtocol( + VideoTransformationAcceptedEvent.Data.Transformation + .Options + .StreamProtocol + .HLS + ) + .addVariant("string") + .videoCodec( + VideoTransformationAcceptedEvent.Data.Transformation + .Options + .VideoCodec + .H264 + ) + .build() + ) + .build() + ) + .build() + ) + .request( + VideoTransformationAcceptedEvent.Request.builder() + .url("https://example.com") + .xRequestId("x_request_id") + .userAgent("user_agent") + .build() + ) + .build() + + val unsafeUnwrapWebhookEvent = + UnsafeUnwrapWebhookEvent.ofVideoTransformationAccepted(videoTransformationAccepted) + + assertThat(unsafeUnwrapWebhookEvent.videoTransformationAccepted()) + .contains(videoTransformationAccepted) + assertThat(unsafeUnwrapWebhookEvent.videoTransformationReady()).isEmpty + assertThat(unsafeUnwrapWebhookEvent.videoTransformationError()).isEmpty + assertThat(unsafeUnwrapWebhookEvent.uploadPreTransformSuccess()).isEmpty + assertThat(unsafeUnwrapWebhookEvent.uploadPreTransformError()).isEmpty + assertThat(unsafeUnwrapWebhookEvent.uploadPostTransformSuccess()).isEmpty + assertThat(unsafeUnwrapWebhookEvent.uploadPostTransformError()).isEmpty + } + + @Test + fun ofVideoTransformationAcceptedRoundtrip() { + val jsonMapper = jsonMapper() + val unsafeUnwrapWebhookEvent = + UnsafeUnwrapWebhookEvent.ofVideoTransformationAccepted( + VideoTransformationAcceptedEvent.builder() + .id("id") + .type("video.transformation.accepted") + .createdAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .data( + VideoTransformationAcceptedEvent.Data.builder() + .asset( + VideoTransformationAcceptedEvent.Data.Asset.builder() + .url("https://example.com") + .build() + ) + .transformation( + VideoTransformationAcceptedEvent.Data.Transformation.builder() + .type( + VideoTransformationAcceptedEvent.Data.Transformation.Type + .VIDEO_TRANSFORMATION + ) + .options( + VideoTransformationAcceptedEvent.Data.Transformation.Options + .builder() + .audioCodec( + VideoTransformationAcceptedEvent.Data.Transformation + .Options + .AudioCodec + .AAC + ) + .autoRotate(true) + .format( + VideoTransformationAcceptedEvent.Data.Transformation + .Options + .Format + .MP4 + ) + .quality(0L) + .streamProtocol( + VideoTransformationAcceptedEvent.Data.Transformation + .Options + .StreamProtocol + .HLS + ) + .addVariant("string") + .videoCodec( + VideoTransformationAcceptedEvent.Data.Transformation + .Options + .VideoCodec + .H264 + ) + .build() + ) + .build() + ) + .build() + ) + .request( + VideoTransformationAcceptedEvent.Request.builder() + .url("https://example.com") + .xRequestId("x_request_id") + .userAgent("user_agent") + .build() + ) + .build() + ) + + val roundtrippedUnsafeUnwrapWebhookEvent = + jsonMapper.readValue( + jsonMapper.writeValueAsString(unsafeUnwrapWebhookEvent), + jacksonTypeRef(), + ) + + assertThat(roundtrippedUnsafeUnwrapWebhookEvent).isEqualTo(unsafeUnwrapWebhookEvent) + } + + @Test + fun ofVideoTransformationReady() { + val videoTransformationReady = + VideoTransformationReadyEvent.builder() + .id("id") + .type("video.transformation.ready") + .createdAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .data( + VideoTransformationReadyEvent.Data.builder() + .asset( + VideoTransformationReadyEvent.Data.Asset.builder() + .url("https://example.com") + .build() + ) + .transformation( + VideoTransformationReadyEvent.Data.Transformation.builder() + .type( + VideoTransformationReadyEvent.Data.Transformation.Type + .VIDEO_TRANSFORMATION + ) + .options( + VideoTransformationReadyEvent.Data.Transformation.Options + .builder() + .audioCodec( + VideoTransformationReadyEvent.Data.Transformation + .Options + .AudioCodec + .AAC + ) + .autoRotate(true) + .format( + VideoTransformationReadyEvent.Data.Transformation + .Options + .Format + .MP4 + ) + .quality(0L) + .streamProtocol( + VideoTransformationReadyEvent.Data.Transformation + .Options + .StreamProtocol + .HLS + ) + .addVariant("string") + .videoCodec( + VideoTransformationReadyEvent.Data.Transformation + .Options + .VideoCodec + .H264 + ) + .build() + ) + .output( + VideoTransformationReadyEvent.Data.Transformation.Output + .builder() + .url("https://example.com") + .videoMetadata( + VideoTransformationReadyEvent.Data.Transformation.Output + .VideoMetadata + .builder() + .bitrate(0L) + .duration(0.0) + .height(0L) + .width(0L) + .build() + ) + .build() + ) + .build() + ) + .build() + ) + .request( + VideoTransformationReadyEvent.Request.builder() + .url("https://example.com") + .xRequestId("x_request_id") + .userAgent("user_agent") + .build() + ) + .timings( + VideoTransformationReadyEvent.Timings.builder() + .downloadDuration(0L) + .encodingDuration(0L) + .build() + ) + .build() + + val unsafeUnwrapWebhookEvent = + UnsafeUnwrapWebhookEvent.ofVideoTransformationReady(videoTransformationReady) + + assertThat(unsafeUnwrapWebhookEvent.videoTransformationAccepted()).isEmpty + assertThat(unsafeUnwrapWebhookEvent.videoTransformationReady()) + .contains(videoTransformationReady) + assertThat(unsafeUnwrapWebhookEvent.videoTransformationError()).isEmpty + assertThat(unsafeUnwrapWebhookEvent.uploadPreTransformSuccess()).isEmpty + assertThat(unsafeUnwrapWebhookEvent.uploadPreTransformError()).isEmpty + assertThat(unsafeUnwrapWebhookEvent.uploadPostTransformSuccess()).isEmpty + assertThat(unsafeUnwrapWebhookEvent.uploadPostTransformError()).isEmpty + } + + @Test + fun ofVideoTransformationReadyRoundtrip() { + val jsonMapper = jsonMapper() + val unsafeUnwrapWebhookEvent = + UnsafeUnwrapWebhookEvent.ofVideoTransformationReady( + VideoTransformationReadyEvent.builder() + .id("id") + .type("video.transformation.ready") + .createdAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .data( + VideoTransformationReadyEvent.Data.builder() + .asset( + VideoTransformationReadyEvent.Data.Asset.builder() + .url("https://example.com") + .build() + ) + .transformation( + VideoTransformationReadyEvent.Data.Transformation.builder() + .type( + VideoTransformationReadyEvent.Data.Transformation.Type + .VIDEO_TRANSFORMATION + ) + .options( + VideoTransformationReadyEvent.Data.Transformation.Options + .builder() + .audioCodec( + VideoTransformationReadyEvent.Data.Transformation + .Options + .AudioCodec + .AAC + ) + .autoRotate(true) + .format( + VideoTransformationReadyEvent.Data.Transformation + .Options + .Format + .MP4 + ) + .quality(0L) + .streamProtocol( + VideoTransformationReadyEvent.Data.Transformation + .Options + .StreamProtocol + .HLS + ) + .addVariant("string") + .videoCodec( + VideoTransformationReadyEvent.Data.Transformation + .Options + .VideoCodec + .H264 + ) + .build() + ) + .output( + VideoTransformationReadyEvent.Data.Transformation.Output + .builder() + .url("https://example.com") + .videoMetadata( + VideoTransformationReadyEvent.Data.Transformation + .Output + .VideoMetadata + .builder() + .bitrate(0L) + .duration(0.0) + .height(0L) + .width(0L) + .build() + ) + .build() + ) + .build() + ) + .build() + ) + .request( + VideoTransformationReadyEvent.Request.builder() + .url("https://example.com") + .xRequestId("x_request_id") + .userAgent("user_agent") + .build() + ) + .timings( + VideoTransformationReadyEvent.Timings.builder() + .downloadDuration(0L) + .encodingDuration(0L) + .build() + ) + .build() + ) + + val roundtrippedUnsafeUnwrapWebhookEvent = + jsonMapper.readValue( + jsonMapper.writeValueAsString(unsafeUnwrapWebhookEvent), + jacksonTypeRef(), + ) + + assertThat(roundtrippedUnsafeUnwrapWebhookEvent).isEqualTo(unsafeUnwrapWebhookEvent) + } + + @Test + fun ofVideoTransformationError() { + val videoTransformationError = + VideoTransformationErrorEvent.builder() + .id("id") + .type("video.transformation.error") + .createdAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .data( + VideoTransformationErrorEvent.Data.builder() + .asset( + VideoTransformationErrorEvent.Data.Asset.builder() + .url("https://example.com") + .build() + ) + .transformation( + VideoTransformationErrorEvent.Data.Transformation.builder() + .type( + VideoTransformationErrorEvent.Data.Transformation.Type + .VIDEO_TRANSFORMATION + ) + .error( + VideoTransformationErrorEvent.Data.Transformation.Error + .builder() + .reason( + VideoTransformationErrorEvent.Data.Transformation.Error + .Reason + .ENCODING_FAILED + ) + .build() + ) + .options( + VideoTransformationErrorEvent.Data.Transformation.Options + .builder() + .audioCodec( + VideoTransformationErrorEvent.Data.Transformation + .Options + .AudioCodec + .AAC + ) + .autoRotate(true) + .format( + VideoTransformationErrorEvent.Data.Transformation + .Options + .Format + .MP4 + ) + .quality(0L) + .streamProtocol( + VideoTransformationErrorEvent.Data.Transformation + .Options + .StreamProtocol + .HLS + ) + .addVariant("string") + .videoCodec( + VideoTransformationErrorEvent.Data.Transformation + .Options + .VideoCodec + .H264 + ) + .build() + ) + .build() + ) + .build() + ) + .request( + VideoTransformationErrorEvent.Request.builder() + .url("https://example.com") + .xRequestId("x_request_id") + .userAgent("user_agent") + .build() + ) + .build() + + val unsafeUnwrapWebhookEvent = + UnsafeUnwrapWebhookEvent.ofVideoTransformationError(videoTransformationError) + + assertThat(unsafeUnwrapWebhookEvent.videoTransformationAccepted()).isEmpty + assertThat(unsafeUnwrapWebhookEvent.videoTransformationReady()).isEmpty + assertThat(unsafeUnwrapWebhookEvent.videoTransformationError()) + .contains(videoTransformationError) + assertThat(unsafeUnwrapWebhookEvent.uploadPreTransformSuccess()).isEmpty + assertThat(unsafeUnwrapWebhookEvent.uploadPreTransformError()).isEmpty + assertThat(unsafeUnwrapWebhookEvent.uploadPostTransformSuccess()).isEmpty + assertThat(unsafeUnwrapWebhookEvent.uploadPostTransformError()).isEmpty + } + + @Test + fun ofVideoTransformationErrorRoundtrip() { + val jsonMapper = jsonMapper() + val unsafeUnwrapWebhookEvent = + UnsafeUnwrapWebhookEvent.ofVideoTransformationError( + VideoTransformationErrorEvent.builder() + .id("id") + .type("video.transformation.error") + .createdAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .data( + VideoTransformationErrorEvent.Data.builder() + .asset( + VideoTransformationErrorEvent.Data.Asset.builder() + .url("https://example.com") + .build() + ) + .transformation( + VideoTransformationErrorEvent.Data.Transformation.builder() + .type( + VideoTransformationErrorEvent.Data.Transformation.Type + .VIDEO_TRANSFORMATION + ) + .error( + VideoTransformationErrorEvent.Data.Transformation.Error + .builder() + .reason( + VideoTransformationErrorEvent.Data.Transformation + .Error + .Reason + .ENCODING_FAILED + ) + .build() + ) + .options( + VideoTransformationErrorEvent.Data.Transformation.Options + .builder() + .audioCodec( + VideoTransformationErrorEvent.Data.Transformation + .Options + .AudioCodec + .AAC + ) + .autoRotate(true) + .format( + VideoTransformationErrorEvent.Data.Transformation + .Options + .Format + .MP4 + ) + .quality(0L) + .streamProtocol( + VideoTransformationErrorEvent.Data.Transformation + .Options + .StreamProtocol + .HLS + ) + .addVariant("string") + .videoCodec( + VideoTransformationErrorEvent.Data.Transformation + .Options + .VideoCodec + .H264 + ) + .build() + ) + .build() + ) + .build() + ) + .request( + VideoTransformationErrorEvent.Request.builder() + .url("https://example.com") + .xRequestId("x_request_id") + .userAgent("user_agent") + .build() + ) + .build() + ) + + val roundtrippedUnsafeUnwrapWebhookEvent = + jsonMapper.readValue( + jsonMapper.writeValueAsString(unsafeUnwrapWebhookEvent), + jacksonTypeRef(), + ) + + assertThat(roundtrippedUnsafeUnwrapWebhookEvent).isEqualTo(unsafeUnwrapWebhookEvent) + } + + @Test + fun ofUploadPreTransformSuccess() { + val uploadPreTransformSuccess = + UploadPreTransformSuccessEvent.builder() + .id("id") + .type("upload.pre-transform.success") + .createdAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .data( + UploadPreTransformSuccessEvent.Data.builder() + .addAiTag( + UploadPreTransformSuccessEvent.Data.AiTag.builder() + .confidence(0.0) + .name("name") + .source("source") + .build() + ) + .audioCodec("audioCodec") + .bitRate(0L) + .customCoordinates("customCoordinates") + .customMetadata( + UploadPreTransformSuccessEvent.Data.CustomMetadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .description("description") + .duration(0L) + .embeddedMetadata( + UploadPreTransformSuccessEvent.Data.EmbeddedMetadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .extensionStatus( + UploadPreTransformSuccessEvent.Data.ExtensionStatus.builder() + .aiAutoDescription( + UploadPreTransformSuccessEvent.Data.ExtensionStatus + .AiAutoDescription + .SUCCESS + ) + .awsAutoTagging( + UploadPreTransformSuccessEvent.Data.ExtensionStatus + .AwsAutoTagging + .SUCCESS + ) + .googleAutoTagging( + UploadPreTransformSuccessEvent.Data.ExtensionStatus + .GoogleAutoTagging + .SUCCESS + ) + .removeBg( + UploadPreTransformSuccessEvent.Data.ExtensionStatus.RemoveBg + .SUCCESS + ) + .build() + ) + .fileId("fileId") + .filePath("filePath") + .fileType("fileType") + .height(0.0) + .isPrivateFile(true) + .isPublished(true) + .metadata( + Metadata.builder() + .audioCodec("audioCodec") + .bitRate(0L) + .density(0L) + .duration(0L) + .exif( + Metadata.Exif.builder() + .exif( + Metadata.Exif.InnerExif.builder() + .apertureValue(0.0) + .colorSpace(0L) + .createDate("CreateDate") + .customRendered(0L) + .dateTimeOriginal("DateTimeOriginal") + .exifImageHeight(0L) + .exifImageWidth(0L) + .exifVersion("ExifVersion") + .exposureCompensation(0.0) + .exposureMode(0L) + .exposureProgram(0L) + .exposureTime(0.0) + .flash(0L) + .flashpixVersion("FlashpixVersion") + .fNumber(0.0) + .focalLength(0L) + .focalPlaneResolutionUnit(0L) + .focalPlaneXResolution(0.0) + .focalPlaneYResolution(0.0) + .interopOffset(0L) + .iso(0L) + .meteringMode(0L) + .sceneCaptureType(0L) + .shutterSpeedValue(0.0) + .subSecTime("SubSecTime") + .whiteBalance(0L) + .build() + ) + .gps( + Metadata.Exif.Gps.builder().addGpsVersionId(0L).build() + ) + .image( + Metadata.Exif.Image.builder() + .exifOffset(0L) + .gpsInfo(0L) + .make("Make") + .model("Model") + .modifyDate("ModifyDate") + .orientation(0L) + .resolutionUnit(0L) + .software("Software") + .xResolution(0L) + .yCbCrPositioning(0L) + .yResolution(0L) + .build() + ) + .interoperability( + Metadata.Exif.Interoperability.builder() + .interopIndex("InteropIndex") + .interopVersion("InteropVersion") + .build() + ) + .makernote( + Metadata.Exif.Makernote.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .thumbnail( + Metadata.Exif.Thumbnail.builder() + .compression(0L) + .resolutionUnit(0L) + .thumbnailLength(0L) + .thumbnailOffset(0L) + .xResolution(0L) + .yResolution(0L) + .build() + ) + .build() + ) + .format("format") + .hasColorProfile(true) + .hasTransparency(true) + .height(0L) + .pHash("pHash") + .quality(0L) + .size(0L) + .videoCodec("videoCodec") + .width(0L) + .build() + ) + .name("name") + .size(0.0) + .addTag("string") + .thumbnailUrl("thumbnailUrl") + .url("url") + .versionInfo( + UploadPreTransformSuccessEvent.Data.VersionInfo.builder() + .id("id") + .name("name") + .build() + ) + .videoCodec("videoCodec") + .width(0.0) + .build() + ) + .request( + UploadPreTransformSuccessEvent.Request.builder() + .transformation("transformation") + .xRequestId("x_request_id") + .build() + ) + .build() + + val unsafeUnwrapWebhookEvent = + UnsafeUnwrapWebhookEvent.ofUploadPreTransformSuccess(uploadPreTransformSuccess) + + assertThat(unsafeUnwrapWebhookEvent.videoTransformationAccepted()).isEmpty + assertThat(unsafeUnwrapWebhookEvent.videoTransformationReady()).isEmpty + assertThat(unsafeUnwrapWebhookEvent.videoTransformationError()).isEmpty + assertThat(unsafeUnwrapWebhookEvent.uploadPreTransformSuccess()) + .contains(uploadPreTransformSuccess) + assertThat(unsafeUnwrapWebhookEvent.uploadPreTransformError()).isEmpty + assertThat(unsafeUnwrapWebhookEvent.uploadPostTransformSuccess()).isEmpty + assertThat(unsafeUnwrapWebhookEvent.uploadPostTransformError()).isEmpty + } + + @Test + fun ofUploadPreTransformSuccessRoundtrip() { + val jsonMapper = jsonMapper() + val unsafeUnwrapWebhookEvent = + UnsafeUnwrapWebhookEvent.ofUploadPreTransformSuccess( + UploadPreTransformSuccessEvent.builder() + .id("id") + .type("upload.pre-transform.success") + .createdAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .data( + UploadPreTransformSuccessEvent.Data.builder() + .addAiTag( + UploadPreTransformSuccessEvent.Data.AiTag.builder() + .confidence(0.0) + .name("name") + .source("source") + .build() + ) + .audioCodec("audioCodec") + .bitRate(0L) + .customCoordinates("customCoordinates") + .customMetadata( + UploadPreTransformSuccessEvent.Data.CustomMetadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .description("description") + .duration(0L) + .embeddedMetadata( + UploadPreTransformSuccessEvent.Data.EmbeddedMetadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .extensionStatus( + UploadPreTransformSuccessEvent.Data.ExtensionStatus.builder() + .aiAutoDescription( + UploadPreTransformSuccessEvent.Data.ExtensionStatus + .AiAutoDescription + .SUCCESS + ) + .awsAutoTagging( + UploadPreTransformSuccessEvent.Data.ExtensionStatus + .AwsAutoTagging + .SUCCESS + ) + .googleAutoTagging( + UploadPreTransformSuccessEvent.Data.ExtensionStatus + .GoogleAutoTagging + .SUCCESS + ) + .removeBg( + UploadPreTransformSuccessEvent.Data.ExtensionStatus.RemoveBg + .SUCCESS + ) + .build() + ) + .fileId("fileId") + .filePath("filePath") + .fileType("fileType") + .height(0.0) + .isPrivateFile(true) + .isPublished(true) + .metadata( + Metadata.builder() + .audioCodec("audioCodec") + .bitRate(0L) + .density(0L) + .duration(0L) + .exif( + Metadata.Exif.builder() + .exif( + Metadata.Exif.InnerExif.builder() + .apertureValue(0.0) + .colorSpace(0L) + .createDate("CreateDate") + .customRendered(0L) + .dateTimeOriginal("DateTimeOriginal") + .exifImageHeight(0L) + .exifImageWidth(0L) + .exifVersion("ExifVersion") + .exposureCompensation(0.0) + .exposureMode(0L) + .exposureProgram(0L) + .exposureTime(0.0) + .flash(0L) + .flashpixVersion("FlashpixVersion") + .fNumber(0.0) + .focalLength(0L) + .focalPlaneResolutionUnit(0L) + .focalPlaneXResolution(0.0) + .focalPlaneYResolution(0.0) + .interopOffset(0L) + .iso(0L) + .meteringMode(0L) + .sceneCaptureType(0L) + .shutterSpeedValue(0.0) + .subSecTime("SubSecTime") + .whiteBalance(0L) + .build() + ) + .gps( + Metadata.Exif.Gps.builder() + .addGpsVersionId(0L) + .build() + ) + .image( + Metadata.Exif.Image.builder() + .exifOffset(0L) + .gpsInfo(0L) + .make("Make") + .model("Model") + .modifyDate("ModifyDate") + .orientation(0L) + .resolutionUnit(0L) + .software("Software") + .xResolution(0L) + .yCbCrPositioning(0L) + .yResolution(0L) + .build() + ) + .interoperability( + Metadata.Exif.Interoperability.builder() + .interopIndex("InteropIndex") + .interopVersion("InteropVersion") + .build() + ) + .makernote( + Metadata.Exif.Makernote.builder() + .putAdditionalProperty( + "foo", + JsonValue.from("bar"), + ) + .build() + ) + .thumbnail( + Metadata.Exif.Thumbnail.builder() + .compression(0L) + .resolutionUnit(0L) + .thumbnailLength(0L) + .thumbnailOffset(0L) + .xResolution(0L) + .yResolution(0L) + .build() + ) + .build() + ) + .format("format") + .hasColorProfile(true) + .hasTransparency(true) + .height(0L) + .pHash("pHash") + .quality(0L) + .size(0L) + .videoCodec("videoCodec") + .width(0L) + .build() + ) + .name("name") + .size(0.0) + .addTag("string") + .thumbnailUrl("thumbnailUrl") + .url("url") + .versionInfo( + UploadPreTransformSuccessEvent.Data.VersionInfo.builder() + .id("id") + .name("name") + .build() + ) + .videoCodec("videoCodec") + .width(0.0) + .build() + ) + .request( + UploadPreTransformSuccessEvent.Request.builder() + .transformation("transformation") + .xRequestId("x_request_id") + .build() + ) + .build() + ) + + val roundtrippedUnsafeUnwrapWebhookEvent = + jsonMapper.readValue( + jsonMapper.writeValueAsString(unsafeUnwrapWebhookEvent), + jacksonTypeRef(), + ) + + assertThat(roundtrippedUnsafeUnwrapWebhookEvent).isEqualTo(unsafeUnwrapWebhookEvent) + } + + @Test + fun ofUploadPreTransformError() { + val uploadPreTransformError = + UploadPreTransformErrorEvent.builder() + .id("id") + .type("upload.pre-transform.error") + .createdAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .data( + UploadPreTransformErrorEvent.Data.builder() + .name("name") + .path("path") + .transformation( + UploadPreTransformErrorEvent.Data.Transformation.builder() + .error( + UploadPreTransformErrorEvent.Data.Transformation.Error.builder() + .reason("encoding_failed") + .build() + ) + .build() + ) + .build() + ) + .request( + UploadPreTransformErrorEvent.Request.builder() + .transformation("transformation") + .xRequestId("x_request_id") + .build() + ) + .build() + + val unsafeUnwrapWebhookEvent = + UnsafeUnwrapWebhookEvent.ofUploadPreTransformError(uploadPreTransformError) + + assertThat(unsafeUnwrapWebhookEvent.videoTransformationAccepted()).isEmpty + assertThat(unsafeUnwrapWebhookEvent.videoTransformationReady()).isEmpty + assertThat(unsafeUnwrapWebhookEvent.videoTransformationError()).isEmpty + assertThat(unsafeUnwrapWebhookEvent.uploadPreTransformSuccess()).isEmpty + assertThat(unsafeUnwrapWebhookEvent.uploadPreTransformError()) + .contains(uploadPreTransformError) + assertThat(unsafeUnwrapWebhookEvent.uploadPostTransformSuccess()).isEmpty + assertThat(unsafeUnwrapWebhookEvent.uploadPostTransformError()).isEmpty + } + + @Test + fun ofUploadPreTransformErrorRoundtrip() { + val jsonMapper = jsonMapper() + val unsafeUnwrapWebhookEvent = + UnsafeUnwrapWebhookEvent.ofUploadPreTransformError( + UploadPreTransformErrorEvent.builder() + .id("id") + .type("upload.pre-transform.error") + .createdAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .data( + UploadPreTransformErrorEvent.Data.builder() + .name("name") + .path("path") + .transformation( + UploadPreTransformErrorEvent.Data.Transformation.builder() + .error( + UploadPreTransformErrorEvent.Data.Transformation.Error + .builder() + .reason("encoding_failed") + .build() + ) + .build() + ) + .build() + ) + .request( + UploadPreTransformErrorEvent.Request.builder() + .transformation("transformation") + .xRequestId("x_request_id") + .build() + ) + .build() + ) + + val roundtrippedUnsafeUnwrapWebhookEvent = + jsonMapper.readValue( + jsonMapper.writeValueAsString(unsafeUnwrapWebhookEvent), + jacksonTypeRef(), + ) + + assertThat(roundtrippedUnsafeUnwrapWebhookEvent).isEqualTo(unsafeUnwrapWebhookEvent) + } + + @Test + fun ofUploadPostTransformSuccess() { + val uploadPostTransformSuccess = + UploadPostTransformSuccessEvent.builder() + .id("id") + .type("upload.post-transform.success") + .createdAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .data( + UploadPostTransformSuccessEvent.Data.builder() + .fileId("fileId") + .name("name") + .url("https://example.com") + .build() + ) + .request( + UploadPostTransformSuccessEvent.Request.builder() + .transformation( + UploadPostTransformSuccessEvent.Request.Transformation.builder() + .type( + UploadPostTransformSuccessEvent.Request.Transformation.Type + .TRANSFORMATION + ) + .protocol( + UploadPostTransformSuccessEvent.Request.Transformation.Protocol + .HLS + ) + .value("value") + .build() + ) + .xRequestId("x_request_id") + .build() + ) + .build() + + val unsafeUnwrapWebhookEvent = + UnsafeUnwrapWebhookEvent.ofUploadPostTransformSuccess(uploadPostTransformSuccess) + + assertThat(unsafeUnwrapWebhookEvent.videoTransformationAccepted()).isEmpty + assertThat(unsafeUnwrapWebhookEvent.videoTransformationReady()).isEmpty + assertThat(unsafeUnwrapWebhookEvent.videoTransformationError()).isEmpty + assertThat(unsafeUnwrapWebhookEvent.uploadPreTransformSuccess()).isEmpty + assertThat(unsafeUnwrapWebhookEvent.uploadPreTransformError()).isEmpty + assertThat(unsafeUnwrapWebhookEvent.uploadPostTransformSuccess()) + .contains(uploadPostTransformSuccess) + assertThat(unsafeUnwrapWebhookEvent.uploadPostTransformError()).isEmpty + } + + @Test + fun ofUploadPostTransformSuccessRoundtrip() { + val jsonMapper = jsonMapper() + val unsafeUnwrapWebhookEvent = + UnsafeUnwrapWebhookEvent.ofUploadPostTransformSuccess( + UploadPostTransformSuccessEvent.builder() + .id("id") + .type("upload.post-transform.success") + .createdAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .data( + UploadPostTransformSuccessEvent.Data.builder() + .fileId("fileId") + .name("name") + .url("https://example.com") + .build() + ) + .request( + UploadPostTransformSuccessEvent.Request.builder() + .transformation( + UploadPostTransformSuccessEvent.Request.Transformation.builder() + .type( + UploadPostTransformSuccessEvent.Request.Transformation.Type + .TRANSFORMATION + ) + .protocol( + UploadPostTransformSuccessEvent.Request.Transformation + .Protocol + .HLS + ) + .value("value") + .build() + ) + .xRequestId("x_request_id") + .build() + ) + .build() + ) + + val roundtrippedUnsafeUnwrapWebhookEvent = + jsonMapper.readValue( + jsonMapper.writeValueAsString(unsafeUnwrapWebhookEvent), + jacksonTypeRef(), + ) + + assertThat(roundtrippedUnsafeUnwrapWebhookEvent).isEqualTo(unsafeUnwrapWebhookEvent) + } + + @Test + fun ofUploadPostTransformError() { + val uploadPostTransformError = + UploadPostTransformErrorEvent.builder() + .id("id") + .type("upload.post-transform.error") + .createdAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .data( + UploadPostTransformErrorEvent.Data.builder() + .fileId("fileId") + .name("name") + .path("path") + .transformation( + UploadPostTransformErrorEvent.Data.Transformation.builder() + .error( + UploadPostTransformErrorEvent.Data.Transformation.Error + .builder() + .reason("encoding_failed") + .build() + ) + .build() + ) + .url("https://example.com") + .build() + ) + .request( + UploadPostTransformErrorEvent.Request.builder() + .transformation( + UploadPostTransformErrorEvent.Request.Transformation.builder() + .type( + UploadPostTransformErrorEvent.Request.Transformation.Type + .TRANSFORMATION + ) + .protocol( + UploadPostTransformErrorEvent.Request.Transformation.Protocol + .HLS + ) + .value("value") + .build() + ) + .xRequestId("x_request_id") + .build() + ) + .build() + + val unsafeUnwrapWebhookEvent = + UnsafeUnwrapWebhookEvent.ofUploadPostTransformError(uploadPostTransformError) + + assertThat(unsafeUnwrapWebhookEvent.videoTransformationAccepted()).isEmpty + assertThat(unsafeUnwrapWebhookEvent.videoTransformationReady()).isEmpty + assertThat(unsafeUnwrapWebhookEvent.videoTransformationError()).isEmpty + assertThat(unsafeUnwrapWebhookEvent.uploadPreTransformSuccess()).isEmpty + assertThat(unsafeUnwrapWebhookEvent.uploadPreTransformError()).isEmpty + assertThat(unsafeUnwrapWebhookEvent.uploadPostTransformSuccess()).isEmpty + assertThat(unsafeUnwrapWebhookEvent.uploadPostTransformError()) + .contains(uploadPostTransformError) + } + + @Test + fun ofUploadPostTransformErrorRoundtrip() { + val jsonMapper = jsonMapper() + val unsafeUnwrapWebhookEvent = + UnsafeUnwrapWebhookEvent.ofUploadPostTransformError( + UploadPostTransformErrorEvent.builder() + .id("id") + .type("upload.post-transform.error") + .createdAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .data( + UploadPostTransformErrorEvent.Data.builder() + .fileId("fileId") + .name("name") + .path("path") + .transformation( + UploadPostTransformErrorEvent.Data.Transformation.builder() + .error( + UploadPostTransformErrorEvent.Data.Transformation.Error + .builder() + .reason("encoding_failed") + .build() + ) + .build() + ) + .url("https://example.com") + .build() + ) + .request( + UploadPostTransformErrorEvent.Request.builder() + .transformation( + UploadPostTransformErrorEvent.Request.Transformation.builder() + .type( + UploadPostTransformErrorEvent.Request.Transformation.Type + .TRANSFORMATION + ) + .protocol( + UploadPostTransformErrorEvent.Request.Transformation + .Protocol + .HLS + ) + .value("value") + .build() + ) + .xRequestId("x_request_id") + .build() + ) + .build() + ) + + val roundtrippedUnsafeUnwrapWebhookEvent = + jsonMapper.readValue( + jsonMapper.writeValueAsString(unsafeUnwrapWebhookEvent), + jacksonTypeRef(), + ) + + assertThat(roundtrippedUnsafeUnwrapWebhookEvent).isEqualTo(unsafeUnwrapWebhookEvent) + } + + enum class IncompatibleJsonShapeTestCase(val value: JsonValue) { + BOOLEAN(JsonValue.from(false)), + STRING(JsonValue.from("invalid")), + INTEGER(JsonValue.from(-1)), + FLOAT(JsonValue.from(3.14)), + ARRAY(JsonValue.from(listOf("invalid", "array"))), + } + + @ParameterizedTest + @EnumSource + fun incompatibleJsonShapeDeserializesToUnknown(testCase: IncompatibleJsonShapeTestCase) { + val unsafeUnwrapWebhookEvent = + jsonMapper().convertValue(testCase.value, jacksonTypeRef()) + + val e = assertThrows { unsafeUnwrapWebhookEvent.validate() } + assertThat(e).hasMessageStartingWith("Unknown ") + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/webhooks/UnwrapWebhookEventTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/webhooks/UnwrapWebhookEventTest.kt new file mode 100644 index 0000000..3addab0 --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/webhooks/UnwrapWebhookEventTest.kt @@ -0,0 +1,1235 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.webhooks + +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.imagekit.api.core.JsonValue +import com.imagekit.api.core.jsonMapper +import com.imagekit.api.errors.ImageKitInvalidDataException +import com.imagekit.api.models.files.Metadata +import java.time.OffsetDateTime +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.assertThrows +import org.junit.jupiter.params.ParameterizedTest +import org.junit.jupiter.params.provider.EnumSource + +internal class UnwrapWebhookEventTest { + + @Test + fun ofVideoTransformationAccepted() { + val videoTransformationAccepted = + VideoTransformationAcceptedEvent.builder() + .id("id") + .type("video.transformation.accepted") + .createdAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .data( + VideoTransformationAcceptedEvent.Data.builder() + .asset( + VideoTransformationAcceptedEvent.Data.Asset.builder() + .url("https://example.com") + .build() + ) + .transformation( + VideoTransformationAcceptedEvent.Data.Transformation.builder() + .type( + VideoTransformationAcceptedEvent.Data.Transformation.Type + .VIDEO_TRANSFORMATION + ) + .options( + VideoTransformationAcceptedEvent.Data.Transformation.Options + .builder() + .audioCodec( + VideoTransformationAcceptedEvent.Data.Transformation + .Options + .AudioCodec + .AAC + ) + .autoRotate(true) + .format( + VideoTransformationAcceptedEvent.Data.Transformation + .Options + .Format + .MP4 + ) + .quality(0L) + .streamProtocol( + VideoTransformationAcceptedEvent.Data.Transformation + .Options + .StreamProtocol + .HLS + ) + .addVariant("string") + .videoCodec( + VideoTransformationAcceptedEvent.Data.Transformation + .Options + .VideoCodec + .H264 + ) + .build() + ) + .build() + ) + .build() + ) + .request( + VideoTransformationAcceptedEvent.Request.builder() + .url("https://example.com") + .xRequestId("x_request_id") + .userAgent("user_agent") + .build() + ) + .build() + + val unwrapWebhookEvent = + UnwrapWebhookEvent.ofVideoTransformationAccepted(videoTransformationAccepted) + + assertThat(unwrapWebhookEvent.videoTransformationAccepted()) + .contains(videoTransformationAccepted) + assertThat(unwrapWebhookEvent.videoTransformationReady()).isEmpty + assertThat(unwrapWebhookEvent.videoTransformationError()).isEmpty + assertThat(unwrapWebhookEvent.uploadPreTransformSuccess()).isEmpty + assertThat(unwrapWebhookEvent.uploadPreTransformError()).isEmpty + assertThat(unwrapWebhookEvent.uploadPostTransformSuccess()).isEmpty + assertThat(unwrapWebhookEvent.uploadPostTransformError()).isEmpty + } + + @Test + fun ofVideoTransformationAcceptedRoundtrip() { + val jsonMapper = jsonMapper() + val unwrapWebhookEvent = + UnwrapWebhookEvent.ofVideoTransformationAccepted( + VideoTransformationAcceptedEvent.builder() + .id("id") + .type("video.transformation.accepted") + .createdAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .data( + VideoTransformationAcceptedEvent.Data.builder() + .asset( + VideoTransformationAcceptedEvent.Data.Asset.builder() + .url("https://example.com") + .build() + ) + .transformation( + VideoTransformationAcceptedEvent.Data.Transformation.builder() + .type( + VideoTransformationAcceptedEvent.Data.Transformation.Type + .VIDEO_TRANSFORMATION + ) + .options( + VideoTransformationAcceptedEvent.Data.Transformation.Options + .builder() + .audioCodec( + VideoTransformationAcceptedEvent.Data.Transformation + .Options + .AudioCodec + .AAC + ) + .autoRotate(true) + .format( + VideoTransformationAcceptedEvent.Data.Transformation + .Options + .Format + .MP4 + ) + .quality(0L) + .streamProtocol( + VideoTransformationAcceptedEvent.Data.Transformation + .Options + .StreamProtocol + .HLS + ) + .addVariant("string") + .videoCodec( + VideoTransformationAcceptedEvent.Data.Transformation + .Options + .VideoCodec + .H264 + ) + .build() + ) + .build() + ) + .build() + ) + .request( + VideoTransformationAcceptedEvent.Request.builder() + .url("https://example.com") + .xRequestId("x_request_id") + .userAgent("user_agent") + .build() + ) + .build() + ) + + val roundtrippedUnwrapWebhookEvent = + jsonMapper.readValue( + jsonMapper.writeValueAsString(unwrapWebhookEvent), + jacksonTypeRef(), + ) + + assertThat(roundtrippedUnwrapWebhookEvent).isEqualTo(unwrapWebhookEvent) + } + + @Test + fun ofVideoTransformationReady() { + val videoTransformationReady = + VideoTransformationReadyEvent.builder() + .id("id") + .type("video.transformation.ready") + .createdAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .data( + VideoTransformationReadyEvent.Data.builder() + .asset( + VideoTransformationReadyEvent.Data.Asset.builder() + .url("https://example.com") + .build() + ) + .transformation( + VideoTransformationReadyEvent.Data.Transformation.builder() + .type( + VideoTransformationReadyEvent.Data.Transformation.Type + .VIDEO_TRANSFORMATION + ) + .options( + VideoTransformationReadyEvent.Data.Transformation.Options + .builder() + .audioCodec( + VideoTransformationReadyEvent.Data.Transformation + .Options + .AudioCodec + .AAC + ) + .autoRotate(true) + .format( + VideoTransformationReadyEvent.Data.Transformation + .Options + .Format + .MP4 + ) + .quality(0L) + .streamProtocol( + VideoTransformationReadyEvent.Data.Transformation + .Options + .StreamProtocol + .HLS + ) + .addVariant("string") + .videoCodec( + VideoTransformationReadyEvent.Data.Transformation + .Options + .VideoCodec + .H264 + ) + .build() + ) + .output( + VideoTransformationReadyEvent.Data.Transformation.Output + .builder() + .url("https://example.com") + .videoMetadata( + VideoTransformationReadyEvent.Data.Transformation.Output + .VideoMetadata + .builder() + .bitrate(0L) + .duration(0.0) + .height(0L) + .width(0L) + .build() + ) + .build() + ) + .build() + ) + .build() + ) + .request( + VideoTransformationReadyEvent.Request.builder() + .url("https://example.com") + .xRequestId("x_request_id") + .userAgent("user_agent") + .build() + ) + .timings( + VideoTransformationReadyEvent.Timings.builder() + .downloadDuration(0L) + .encodingDuration(0L) + .build() + ) + .build() + + val unwrapWebhookEvent = + UnwrapWebhookEvent.ofVideoTransformationReady(videoTransformationReady) + + assertThat(unwrapWebhookEvent.videoTransformationAccepted()).isEmpty + assertThat(unwrapWebhookEvent.videoTransformationReady()).contains(videoTransformationReady) + assertThat(unwrapWebhookEvent.videoTransformationError()).isEmpty + assertThat(unwrapWebhookEvent.uploadPreTransformSuccess()).isEmpty + assertThat(unwrapWebhookEvent.uploadPreTransformError()).isEmpty + assertThat(unwrapWebhookEvent.uploadPostTransformSuccess()).isEmpty + assertThat(unwrapWebhookEvent.uploadPostTransformError()).isEmpty + } + + @Test + fun ofVideoTransformationReadyRoundtrip() { + val jsonMapper = jsonMapper() + val unwrapWebhookEvent = + UnwrapWebhookEvent.ofVideoTransformationReady( + VideoTransformationReadyEvent.builder() + .id("id") + .type("video.transformation.ready") + .createdAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .data( + VideoTransformationReadyEvent.Data.builder() + .asset( + VideoTransformationReadyEvent.Data.Asset.builder() + .url("https://example.com") + .build() + ) + .transformation( + VideoTransformationReadyEvent.Data.Transformation.builder() + .type( + VideoTransformationReadyEvent.Data.Transformation.Type + .VIDEO_TRANSFORMATION + ) + .options( + VideoTransformationReadyEvent.Data.Transformation.Options + .builder() + .audioCodec( + VideoTransformationReadyEvent.Data.Transformation + .Options + .AudioCodec + .AAC + ) + .autoRotate(true) + .format( + VideoTransformationReadyEvent.Data.Transformation + .Options + .Format + .MP4 + ) + .quality(0L) + .streamProtocol( + VideoTransformationReadyEvent.Data.Transformation + .Options + .StreamProtocol + .HLS + ) + .addVariant("string") + .videoCodec( + VideoTransformationReadyEvent.Data.Transformation + .Options + .VideoCodec + .H264 + ) + .build() + ) + .output( + VideoTransformationReadyEvent.Data.Transformation.Output + .builder() + .url("https://example.com") + .videoMetadata( + VideoTransformationReadyEvent.Data.Transformation + .Output + .VideoMetadata + .builder() + .bitrate(0L) + .duration(0.0) + .height(0L) + .width(0L) + .build() + ) + .build() + ) + .build() + ) + .build() + ) + .request( + VideoTransformationReadyEvent.Request.builder() + .url("https://example.com") + .xRequestId("x_request_id") + .userAgent("user_agent") + .build() + ) + .timings( + VideoTransformationReadyEvent.Timings.builder() + .downloadDuration(0L) + .encodingDuration(0L) + .build() + ) + .build() + ) + + val roundtrippedUnwrapWebhookEvent = + jsonMapper.readValue( + jsonMapper.writeValueAsString(unwrapWebhookEvent), + jacksonTypeRef(), + ) + + assertThat(roundtrippedUnwrapWebhookEvent).isEqualTo(unwrapWebhookEvent) + } + + @Test + fun ofVideoTransformationError() { + val videoTransformationError = + VideoTransformationErrorEvent.builder() + .id("id") + .type("video.transformation.error") + .createdAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .data( + VideoTransformationErrorEvent.Data.builder() + .asset( + VideoTransformationErrorEvent.Data.Asset.builder() + .url("https://example.com") + .build() + ) + .transformation( + VideoTransformationErrorEvent.Data.Transformation.builder() + .type( + VideoTransformationErrorEvent.Data.Transformation.Type + .VIDEO_TRANSFORMATION + ) + .error( + VideoTransformationErrorEvent.Data.Transformation.Error + .builder() + .reason( + VideoTransformationErrorEvent.Data.Transformation.Error + .Reason + .ENCODING_FAILED + ) + .build() + ) + .options( + VideoTransformationErrorEvent.Data.Transformation.Options + .builder() + .audioCodec( + VideoTransformationErrorEvent.Data.Transformation + .Options + .AudioCodec + .AAC + ) + .autoRotate(true) + .format( + VideoTransformationErrorEvent.Data.Transformation + .Options + .Format + .MP4 + ) + .quality(0L) + .streamProtocol( + VideoTransformationErrorEvent.Data.Transformation + .Options + .StreamProtocol + .HLS + ) + .addVariant("string") + .videoCodec( + VideoTransformationErrorEvent.Data.Transformation + .Options + .VideoCodec + .H264 + ) + .build() + ) + .build() + ) + .build() + ) + .request( + VideoTransformationErrorEvent.Request.builder() + .url("https://example.com") + .xRequestId("x_request_id") + .userAgent("user_agent") + .build() + ) + .build() + + val unwrapWebhookEvent = + UnwrapWebhookEvent.ofVideoTransformationError(videoTransformationError) + + assertThat(unwrapWebhookEvent.videoTransformationAccepted()).isEmpty + assertThat(unwrapWebhookEvent.videoTransformationReady()).isEmpty + assertThat(unwrapWebhookEvent.videoTransformationError()).contains(videoTransformationError) + assertThat(unwrapWebhookEvent.uploadPreTransformSuccess()).isEmpty + assertThat(unwrapWebhookEvent.uploadPreTransformError()).isEmpty + assertThat(unwrapWebhookEvent.uploadPostTransformSuccess()).isEmpty + assertThat(unwrapWebhookEvent.uploadPostTransformError()).isEmpty + } + + @Test + fun ofVideoTransformationErrorRoundtrip() { + val jsonMapper = jsonMapper() + val unwrapWebhookEvent = + UnwrapWebhookEvent.ofVideoTransformationError( + VideoTransformationErrorEvent.builder() + .id("id") + .type("video.transformation.error") + .createdAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .data( + VideoTransformationErrorEvent.Data.builder() + .asset( + VideoTransformationErrorEvent.Data.Asset.builder() + .url("https://example.com") + .build() + ) + .transformation( + VideoTransformationErrorEvent.Data.Transformation.builder() + .type( + VideoTransformationErrorEvent.Data.Transformation.Type + .VIDEO_TRANSFORMATION + ) + .error( + VideoTransformationErrorEvent.Data.Transformation.Error + .builder() + .reason( + VideoTransformationErrorEvent.Data.Transformation + .Error + .Reason + .ENCODING_FAILED + ) + .build() + ) + .options( + VideoTransformationErrorEvent.Data.Transformation.Options + .builder() + .audioCodec( + VideoTransformationErrorEvent.Data.Transformation + .Options + .AudioCodec + .AAC + ) + .autoRotate(true) + .format( + VideoTransformationErrorEvent.Data.Transformation + .Options + .Format + .MP4 + ) + .quality(0L) + .streamProtocol( + VideoTransformationErrorEvent.Data.Transformation + .Options + .StreamProtocol + .HLS + ) + .addVariant("string") + .videoCodec( + VideoTransformationErrorEvent.Data.Transformation + .Options + .VideoCodec + .H264 + ) + .build() + ) + .build() + ) + .build() + ) + .request( + VideoTransformationErrorEvent.Request.builder() + .url("https://example.com") + .xRequestId("x_request_id") + .userAgent("user_agent") + .build() + ) + .build() + ) + + val roundtrippedUnwrapWebhookEvent = + jsonMapper.readValue( + jsonMapper.writeValueAsString(unwrapWebhookEvent), + jacksonTypeRef(), + ) + + assertThat(roundtrippedUnwrapWebhookEvent).isEqualTo(unwrapWebhookEvent) + } + + @Test + fun ofUploadPreTransformSuccess() { + val uploadPreTransformSuccess = + UploadPreTransformSuccessEvent.builder() + .id("id") + .type("upload.pre-transform.success") + .createdAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .data( + UploadPreTransformSuccessEvent.Data.builder() + .addAiTag( + UploadPreTransformSuccessEvent.Data.AiTag.builder() + .confidence(0.0) + .name("name") + .source("source") + .build() + ) + .audioCodec("audioCodec") + .bitRate(0L) + .customCoordinates("customCoordinates") + .customMetadata( + UploadPreTransformSuccessEvent.Data.CustomMetadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .description("description") + .duration(0L) + .embeddedMetadata( + UploadPreTransformSuccessEvent.Data.EmbeddedMetadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .extensionStatus( + UploadPreTransformSuccessEvent.Data.ExtensionStatus.builder() + .aiAutoDescription( + UploadPreTransformSuccessEvent.Data.ExtensionStatus + .AiAutoDescription + .SUCCESS + ) + .awsAutoTagging( + UploadPreTransformSuccessEvent.Data.ExtensionStatus + .AwsAutoTagging + .SUCCESS + ) + .googleAutoTagging( + UploadPreTransformSuccessEvent.Data.ExtensionStatus + .GoogleAutoTagging + .SUCCESS + ) + .removeBg( + UploadPreTransformSuccessEvent.Data.ExtensionStatus.RemoveBg + .SUCCESS + ) + .build() + ) + .fileId("fileId") + .filePath("filePath") + .fileType("fileType") + .height(0.0) + .isPrivateFile(true) + .isPublished(true) + .metadata( + Metadata.builder() + .audioCodec("audioCodec") + .bitRate(0L) + .density(0L) + .duration(0L) + .exif( + Metadata.Exif.builder() + .exif( + Metadata.Exif.InnerExif.builder() + .apertureValue(0.0) + .colorSpace(0L) + .createDate("CreateDate") + .customRendered(0L) + .dateTimeOriginal("DateTimeOriginal") + .exifImageHeight(0L) + .exifImageWidth(0L) + .exifVersion("ExifVersion") + .exposureCompensation(0.0) + .exposureMode(0L) + .exposureProgram(0L) + .exposureTime(0.0) + .flash(0L) + .flashpixVersion("FlashpixVersion") + .fNumber(0.0) + .focalLength(0L) + .focalPlaneResolutionUnit(0L) + .focalPlaneXResolution(0.0) + .focalPlaneYResolution(0.0) + .interopOffset(0L) + .iso(0L) + .meteringMode(0L) + .sceneCaptureType(0L) + .shutterSpeedValue(0.0) + .subSecTime("SubSecTime") + .whiteBalance(0L) + .build() + ) + .gps( + Metadata.Exif.Gps.builder().addGpsVersionId(0L).build() + ) + .image( + Metadata.Exif.Image.builder() + .exifOffset(0L) + .gpsInfo(0L) + .make("Make") + .model("Model") + .modifyDate("ModifyDate") + .orientation(0L) + .resolutionUnit(0L) + .software("Software") + .xResolution(0L) + .yCbCrPositioning(0L) + .yResolution(0L) + .build() + ) + .interoperability( + Metadata.Exif.Interoperability.builder() + .interopIndex("InteropIndex") + .interopVersion("InteropVersion") + .build() + ) + .makernote( + Metadata.Exif.Makernote.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .thumbnail( + Metadata.Exif.Thumbnail.builder() + .compression(0L) + .resolutionUnit(0L) + .thumbnailLength(0L) + .thumbnailOffset(0L) + .xResolution(0L) + .yResolution(0L) + .build() + ) + .build() + ) + .format("format") + .hasColorProfile(true) + .hasTransparency(true) + .height(0L) + .pHash("pHash") + .quality(0L) + .size(0L) + .videoCodec("videoCodec") + .width(0L) + .build() + ) + .name("name") + .size(0.0) + .addTag("string") + .thumbnailUrl("thumbnailUrl") + .url("url") + .versionInfo( + UploadPreTransformSuccessEvent.Data.VersionInfo.builder() + .id("id") + .name("name") + .build() + ) + .videoCodec("videoCodec") + .width(0.0) + .build() + ) + .request( + UploadPreTransformSuccessEvent.Request.builder() + .transformation("transformation") + .xRequestId("x_request_id") + .build() + ) + .build() + + val unwrapWebhookEvent = + UnwrapWebhookEvent.ofUploadPreTransformSuccess(uploadPreTransformSuccess) + + assertThat(unwrapWebhookEvent.videoTransformationAccepted()).isEmpty + assertThat(unwrapWebhookEvent.videoTransformationReady()).isEmpty + assertThat(unwrapWebhookEvent.videoTransformationError()).isEmpty + assertThat(unwrapWebhookEvent.uploadPreTransformSuccess()) + .contains(uploadPreTransformSuccess) + assertThat(unwrapWebhookEvent.uploadPreTransformError()).isEmpty + assertThat(unwrapWebhookEvent.uploadPostTransformSuccess()).isEmpty + assertThat(unwrapWebhookEvent.uploadPostTransformError()).isEmpty + } + + @Test + fun ofUploadPreTransformSuccessRoundtrip() { + val jsonMapper = jsonMapper() + val unwrapWebhookEvent = + UnwrapWebhookEvent.ofUploadPreTransformSuccess( + UploadPreTransformSuccessEvent.builder() + .id("id") + .type("upload.pre-transform.success") + .createdAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .data( + UploadPreTransformSuccessEvent.Data.builder() + .addAiTag( + UploadPreTransformSuccessEvent.Data.AiTag.builder() + .confidence(0.0) + .name("name") + .source("source") + .build() + ) + .audioCodec("audioCodec") + .bitRate(0L) + .customCoordinates("customCoordinates") + .customMetadata( + UploadPreTransformSuccessEvent.Data.CustomMetadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .description("description") + .duration(0L) + .embeddedMetadata( + UploadPreTransformSuccessEvent.Data.EmbeddedMetadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .extensionStatus( + UploadPreTransformSuccessEvent.Data.ExtensionStatus.builder() + .aiAutoDescription( + UploadPreTransformSuccessEvent.Data.ExtensionStatus + .AiAutoDescription + .SUCCESS + ) + .awsAutoTagging( + UploadPreTransformSuccessEvent.Data.ExtensionStatus + .AwsAutoTagging + .SUCCESS + ) + .googleAutoTagging( + UploadPreTransformSuccessEvent.Data.ExtensionStatus + .GoogleAutoTagging + .SUCCESS + ) + .removeBg( + UploadPreTransformSuccessEvent.Data.ExtensionStatus.RemoveBg + .SUCCESS + ) + .build() + ) + .fileId("fileId") + .filePath("filePath") + .fileType("fileType") + .height(0.0) + .isPrivateFile(true) + .isPublished(true) + .metadata( + Metadata.builder() + .audioCodec("audioCodec") + .bitRate(0L) + .density(0L) + .duration(0L) + .exif( + Metadata.Exif.builder() + .exif( + Metadata.Exif.InnerExif.builder() + .apertureValue(0.0) + .colorSpace(0L) + .createDate("CreateDate") + .customRendered(0L) + .dateTimeOriginal("DateTimeOriginal") + .exifImageHeight(0L) + .exifImageWidth(0L) + .exifVersion("ExifVersion") + .exposureCompensation(0.0) + .exposureMode(0L) + .exposureProgram(0L) + .exposureTime(0.0) + .flash(0L) + .flashpixVersion("FlashpixVersion") + .fNumber(0.0) + .focalLength(0L) + .focalPlaneResolutionUnit(0L) + .focalPlaneXResolution(0.0) + .focalPlaneYResolution(0.0) + .interopOffset(0L) + .iso(0L) + .meteringMode(0L) + .sceneCaptureType(0L) + .shutterSpeedValue(0.0) + .subSecTime("SubSecTime") + .whiteBalance(0L) + .build() + ) + .gps( + Metadata.Exif.Gps.builder() + .addGpsVersionId(0L) + .build() + ) + .image( + Metadata.Exif.Image.builder() + .exifOffset(0L) + .gpsInfo(0L) + .make("Make") + .model("Model") + .modifyDate("ModifyDate") + .orientation(0L) + .resolutionUnit(0L) + .software("Software") + .xResolution(0L) + .yCbCrPositioning(0L) + .yResolution(0L) + .build() + ) + .interoperability( + Metadata.Exif.Interoperability.builder() + .interopIndex("InteropIndex") + .interopVersion("InteropVersion") + .build() + ) + .makernote( + Metadata.Exif.Makernote.builder() + .putAdditionalProperty( + "foo", + JsonValue.from("bar"), + ) + .build() + ) + .thumbnail( + Metadata.Exif.Thumbnail.builder() + .compression(0L) + .resolutionUnit(0L) + .thumbnailLength(0L) + .thumbnailOffset(0L) + .xResolution(0L) + .yResolution(0L) + .build() + ) + .build() + ) + .format("format") + .hasColorProfile(true) + .hasTransparency(true) + .height(0L) + .pHash("pHash") + .quality(0L) + .size(0L) + .videoCodec("videoCodec") + .width(0L) + .build() + ) + .name("name") + .size(0.0) + .addTag("string") + .thumbnailUrl("thumbnailUrl") + .url("url") + .versionInfo( + UploadPreTransformSuccessEvent.Data.VersionInfo.builder() + .id("id") + .name("name") + .build() + ) + .videoCodec("videoCodec") + .width(0.0) + .build() + ) + .request( + UploadPreTransformSuccessEvent.Request.builder() + .transformation("transformation") + .xRequestId("x_request_id") + .build() + ) + .build() + ) + + val roundtrippedUnwrapWebhookEvent = + jsonMapper.readValue( + jsonMapper.writeValueAsString(unwrapWebhookEvent), + jacksonTypeRef(), + ) + + assertThat(roundtrippedUnwrapWebhookEvent).isEqualTo(unwrapWebhookEvent) + } + + @Test + fun ofUploadPreTransformError() { + val uploadPreTransformError = + UploadPreTransformErrorEvent.builder() + .id("id") + .type("upload.pre-transform.error") + .createdAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .data( + UploadPreTransformErrorEvent.Data.builder() + .name("name") + .path("path") + .transformation( + UploadPreTransformErrorEvent.Data.Transformation.builder() + .error( + UploadPreTransformErrorEvent.Data.Transformation.Error.builder() + .reason("encoding_failed") + .build() + ) + .build() + ) + .build() + ) + .request( + UploadPreTransformErrorEvent.Request.builder() + .transformation("transformation") + .xRequestId("x_request_id") + .build() + ) + .build() + + val unwrapWebhookEvent = + UnwrapWebhookEvent.ofUploadPreTransformError(uploadPreTransformError) + + assertThat(unwrapWebhookEvent.videoTransformationAccepted()).isEmpty + assertThat(unwrapWebhookEvent.videoTransformationReady()).isEmpty + assertThat(unwrapWebhookEvent.videoTransformationError()).isEmpty + assertThat(unwrapWebhookEvent.uploadPreTransformSuccess()).isEmpty + assertThat(unwrapWebhookEvent.uploadPreTransformError()).contains(uploadPreTransformError) + assertThat(unwrapWebhookEvent.uploadPostTransformSuccess()).isEmpty + assertThat(unwrapWebhookEvent.uploadPostTransformError()).isEmpty + } + + @Test + fun ofUploadPreTransformErrorRoundtrip() { + val jsonMapper = jsonMapper() + val unwrapWebhookEvent = + UnwrapWebhookEvent.ofUploadPreTransformError( + UploadPreTransformErrorEvent.builder() + .id("id") + .type("upload.pre-transform.error") + .createdAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .data( + UploadPreTransformErrorEvent.Data.builder() + .name("name") + .path("path") + .transformation( + UploadPreTransformErrorEvent.Data.Transformation.builder() + .error( + UploadPreTransformErrorEvent.Data.Transformation.Error + .builder() + .reason("encoding_failed") + .build() + ) + .build() + ) + .build() + ) + .request( + UploadPreTransformErrorEvent.Request.builder() + .transformation("transformation") + .xRequestId("x_request_id") + .build() + ) + .build() + ) + + val roundtrippedUnwrapWebhookEvent = + jsonMapper.readValue( + jsonMapper.writeValueAsString(unwrapWebhookEvent), + jacksonTypeRef(), + ) + + assertThat(roundtrippedUnwrapWebhookEvent).isEqualTo(unwrapWebhookEvent) + } + + @Test + fun ofUploadPostTransformSuccess() { + val uploadPostTransformSuccess = + UploadPostTransformSuccessEvent.builder() + .id("id") + .type("upload.post-transform.success") + .createdAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .data( + UploadPostTransformSuccessEvent.Data.builder() + .fileId("fileId") + .name("name") + .url("https://example.com") + .build() + ) + .request( + UploadPostTransformSuccessEvent.Request.builder() + .transformation( + UploadPostTransformSuccessEvent.Request.Transformation.builder() + .type( + UploadPostTransformSuccessEvent.Request.Transformation.Type + .TRANSFORMATION + ) + .protocol( + UploadPostTransformSuccessEvent.Request.Transformation.Protocol + .HLS + ) + .value("value") + .build() + ) + .xRequestId("x_request_id") + .build() + ) + .build() + + val unwrapWebhookEvent = + UnwrapWebhookEvent.ofUploadPostTransformSuccess(uploadPostTransformSuccess) + + assertThat(unwrapWebhookEvent.videoTransformationAccepted()).isEmpty + assertThat(unwrapWebhookEvent.videoTransformationReady()).isEmpty + assertThat(unwrapWebhookEvent.videoTransformationError()).isEmpty + assertThat(unwrapWebhookEvent.uploadPreTransformSuccess()).isEmpty + assertThat(unwrapWebhookEvent.uploadPreTransformError()).isEmpty + assertThat(unwrapWebhookEvent.uploadPostTransformSuccess()) + .contains(uploadPostTransformSuccess) + assertThat(unwrapWebhookEvent.uploadPostTransformError()).isEmpty + } + + @Test + fun ofUploadPostTransformSuccessRoundtrip() { + val jsonMapper = jsonMapper() + val unwrapWebhookEvent = + UnwrapWebhookEvent.ofUploadPostTransformSuccess( + UploadPostTransformSuccessEvent.builder() + .id("id") + .type("upload.post-transform.success") + .createdAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .data( + UploadPostTransformSuccessEvent.Data.builder() + .fileId("fileId") + .name("name") + .url("https://example.com") + .build() + ) + .request( + UploadPostTransformSuccessEvent.Request.builder() + .transformation( + UploadPostTransformSuccessEvent.Request.Transformation.builder() + .type( + UploadPostTransformSuccessEvent.Request.Transformation.Type + .TRANSFORMATION + ) + .protocol( + UploadPostTransformSuccessEvent.Request.Transformation + .Protocol + .HLS + ) + .value("value") + .build() + ) + .xRequestId("x_request_id") + .build() + ) + .build() + ) + + val roundtrippedUnwrapWebhookEvent = + jsonMapper.readValue( + jsonMapper.writeValueAsString(unwrapWebhookEvent), + jacksonTypeRef(), + ) + + assertThat(roundtrippedUnwrapWebhookEvent).isEqualTo(unwrapWebhookEvent) + } + + @Test + fun ofUploadPostTransformError() { + val uploadPostTransformError = + UploadPostTransformErrorEvent.builder() + .id("id") + .type("upload.post-transform.error") + .createdAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .data( + UploadPostTransformErrorEvent.Data.builder() + .fileId("fileId") + .name("name") + .path("path") + .transformation( + UploadPostTransformErrorEvent.Data.Transformation.builder() + .error( + UploadPostTransformErrorEvent.Data.Transformation.Error + .builder() + .reason("encoding_failed") + .build() + ) + .build() + ) + .url("https://example.com") + .build() + ) + .request( + UploadPostTransformErrorEvent.Request.builder() + .transformation( + UploadPostTransformErrorEvent.Request.Transformation.builder() + .type( + UploadPostTransformErrorEvent.Request.Transformation.Type + .TRANSFORMATION + ) + .protocol( + UploadPostTransformErrorEvent.Request.Transformation.Protocol + .HLS + ) + .value("value") + .build() + ) + .xRequestId("x_request_id") + .build() + ) + .build() + + val unwrapWebhookEvent = + UnwrapWebhookEvent.ofUploadPostTransformError(uploadPostTransformError) + + assertThat(unwrapWebhookEvent.videoTransformationAccepted()).isEmpty + assertThat(unwrapWebhookEvent.videoTransformationReady()).isEmpty + assertThat(unwrapWebhookEvent.videoTransformationError()).isEmpty + assertThat(unwrapWebhookEvent.uploadPreTransformSuccess()).isEmpty + assertThat(unwrapWebhookEvent.uploadPreTransformError()).isEmpty + assertThat(unwrapWebhookEvent.uploadPostTransformSuccess()).isEmpty + assertThat(unwrapWebhookEvent.uploadPostTransformError()).contains(uploadPostTransformError) + } + + @Test + fun ofUploadPostTransformErrorRoundtrip() { + val jsonMapper = jsonMapper() + val unwrapWebhookEvent = + UnwrapWebhookEvent.ofUploadPostTransformError( + UploadPostTransformErrorEvent.builder() + .id("id") + .type("upload.post-transform.error") + .createdAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .data( + UploadPostTransformErrorEvent.Data.builder() + .fileId("fileId") + .name("name") + .path("path") + .transformation( + UploadPostTransformErrorEvent.Data.Transformation.builder() + .error( + UploadPostTransformErrorEvent.Data.Transformation.Error + .builder() + .reason("encoding_failed") + .build() + ) + .build() + ) + .url("https://example.com") + .build() + ) + .request( + UploadPostTransformErrorEvent.Request.builder() + .transformation( + UploadPostTransformErrorEvent.Request.Transformation.builder() + .type( + UploadPostTransformErrorEvent.Request.Transformation.Type + .TRANSFORMATION + ) + .protocol( + UploadPostTransformErrorEvent.Request.Transformation + .Protocol + .HLS + ) + .value("value") + .build() + ) + .xRequestId("x_request_id") + .build() + ) + .build() + ) + + val roundtrippedUnwrapWebhookEvent = + jsonMapper.readValue( + jsonMapper.writeValueAsString(unwrapWebhookEvent), + jacksonTypeRef(), + ) + + assertThat(roundtrippedUnwrapWebhookEvent).isEqualTo(unwrapWebhookEvent) + } + + enum class IncompatibleJsonShapeTestCase(val value: JsonValue) { + BOOLEAN(JsonValue.from(false)), + STRING(JsonValue.from("invalid")), + INTEGER(JsonValue.from(-1)), + FLOAT(JsonValue.from(3.14)), + ARRAY(JsonValue.from(listOf("invalid", "array"))), + } + + @ParameterizedTest + @EnumSource + fun incompatibleJsonShapeDeserializesToUnknown(testCase: IncompatibleJsonShapeTestCase) { + val unwrapWebhookEvent = + jsonMapper().convertValue(testCase.value, jacksonTypeRef()) + + val e = assertThrows { unwrapWebhookEvent.validate() } + assertThat(e).hasMessageStartingWith("Unknown ") + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/webhooks/UploadPostTransformErrorEventTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/webhooks/UploadPostTransformErrorEventTest.kt new file mode 100644 index 0000000..ce99a9c --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/webhooks/UploadPostTransformErrorEventTest.kt @@ -0,0 +1,155 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.webhooks + +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.imagekit.api.core.jsonMapper +import java.time.OffsetDateTime +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class UploadPostTransformErrorEventTest { + + @Test + fun create() { + val uploadPostTransformErrorEvent = + UploadPostTransformErrorEvent.builder() + .id("id") + .type("upload.post-transform.error") + .createdAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .data( + UploadPostTransformErrorEvent.Data.builder() + .fileId("fileId") + .name("name") + .path("path") + .transformation( + UploadPostTransformErrorEvent.Data.Transformation.builder() + .error( + UploadPostTransformErrorEvent.Data.Transformation.Error + .builder() + .reason("encoding_failed") + .build() + ) + .build() + ) + .url("https://example.com") + .build() + ) + .request( + UploadPostTransformErrorEvent.Request.builder() + .transformation( + UploadPostTransformErrorEvent.Request.Transformation.builder() + .type( + UploadPostTransformErrorEvent.Request.Transformation.Type + .TRANSFORMATION + ) + .protocol( + UploadPostTransformErrorEvent.Request.Transformation.Protocol + .HLS + ) + .value("value") + .build() + ) + .xRequestId("x_request_id") + .build() + ) + .build() + + assertThat(uploadPostTransformErrorEvent.id()).isEqualTo("id") + assertThat(uploadPostTransformErrorEvent.type()).isEqualTo("upload.post-transform.error") + assertThat(uploadPostTransformErrorEvent.createdAt()) + .isEqualTo(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + assertThat(uploadPostTransformErrorEvent.data()) + .isEqualTo( + UploadPostTransformErrorEvent.Data.builder() + .fileId("fileId") + .name("name") + .path("path") + .transformation( + UploadPostTransformErrorEvent.Data.Transformation.builder() + .error( + UploadPostTransformErrorEvent.Data.Transformation.Error.builder() + .reason("encoding_failed") + .build() + ) + .build() + ) + .url("https://example.com") + .build() + ) + assertThat(uploadPostTransformErrorEvent.request()) + .isEqualTo( + UploadPostTransformErrorEvent.Request.builder() + .transformation( + UploadPostTransformErrorEvent.Request.Transformation.builder() + .type( + UploadPostTransformErrorEvent.Request.Transformation.Type + .TRANSFORMATION + ) + .protocol( + UploadPostTransformErrorEvent.Request.Transformation.Protocol.HLS + ) + .value("value") + .build() + ) + .xRequestId("x_request_id") + .build() + ) + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val uploadPostTransformErrorEvent = + UploadPostTransformErrorEvent.builder() + .id("id") + .type("upload.post-transform.error") + .createdAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .data( + UploadPostTransformErrorEvent.Data.builder() + .fileId("fileId") + .name("name") + .path("path") + .transformation( + UploadPostTransformErrorEvent.Data.Transformation.builder() + .error( + UploadPostTransformErrorEvent.Data.Transformation.Error + .builder() + .reason("encoding_failed") + .build() + ) + .build() + ) + .url("https://example.com") + .build() + ) + .request( + UploadPostTransformErrorEvent.Request.builder() + .transformation( + UploadPostTransformErrorEvent.Request.Transformation.builder() + .type( + UploadPostTransformErrorEvent.Request.Transformation.Type + .TRANSFORMATION + ) + .protocol( + UploadPostTransformErrorEvent.Request.Transformation.Protocol + .HLS + ) + .value("value") + .build() + ) + .xRequestId("x_request_id") + .build() + ) + .build() + + val roundtrippedUploadPostTransformErrorEvent = + jsonMapper.readValue( + jsonMapper.writeValueAsString(uploadPostTransformErrorEvent), + jacksonTypeRef(), + ) + + assertThat(roundtrippedUploadPostTransformErrorEvent) + .isEqualTo(uploadPostTransformErrorEvent) + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/webhooks/UploadPostTransformSuccessEventTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/webhooks/UploadPostTransformSuccessEventTest.kt new file mode 100644 index 0000000..ded4c11 --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/webhooks/UploadPostTransformSuccessEventTest.kt @@ -0,0 +1,124 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.webhooks + +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.imagekit.api.core.jsonMapper +import java.time.OffsetDateTime +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class UploadPostTransformSuccessEventTest { + + @Test + fun create() { + val uploadPostTransformSuccessEvent = + UploadPostTransformSuccessEvent.builder() + .id("id") + .type("upload.post-transform.success") + .createdAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .data( + UploadPostTransformSuccessEvent.Data.builder() + .fileId("fileId") + .name("name") + .url("https://example.com") + .build() + ) + .request( + UploadPostTransformSuccessEvent.Request.builder() + .transformation( + UploadPostTransformSuccessEvent.Request.Transformation.builder() + .type( + UploadPostTransformSuccessEvent.Request.Transformation.Type + .TRANSFORMATION + ) + .protocol( + UploadPostTransformSuccessEvent.Request.Transformation.Protocol + .HLS + ) + .value("value") + .build() + ) + .xRequestId("x_request_id") + .build() + ) + .build() + + assertThat(uploadPostTransformSuccessEvent.id()).isEqualTo("id") + assertThat(uploadPostTransformSuccessEvent.type()) + .isEqualTo("upload.post-transform.success") + assertThat(uploadPostTransformSuccessEvent.createdAt()) + .isEqualTo(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + assertThat(uploadPostTransformSuccessEvent.data()) + .isEqualTo( + UploadPostTransformSuccessEvent.Data.builder() + .fileId("fileId") + .name("name") + .url("https://example.com") + .build() + ) + assertThat(uploadPostTransformSuccessEvent.request()) + .isEqualTo( + UploadPostTransformSuccessEvent.Request.builder() + .transformation( + UploadPostTransformSuccessEvent.Request.Transformation.builder() + .type( + UploadPostTransformSuccessEvent.Request.Transformation.Type + .TRANSFORMATION + ) + .protocol( + UploadPostTransformSuccessEvent.Request.Transformation.Protocol.HLS + ) + .value("value") + .build() + ) + .xRequestId("x_request_id") + .build() + ) + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val uploadPostTransformSuccessEvent = + UploadPostTransformSuccessEvent.builder() + .id("id") + .type("upload.post-transform.success") + .createdAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .data( + UploadPostTransformSuccessEvent.Data.builder() + .fileId("fileId") + .name("name") + .url("https://example.com") + .build() + ) + .request( + UploadPostTransformSuccessEvent.Request.builder() + .transformation( + UploadPostTransformSuccessEvent.Request.Transformation.builder() + .type( + UploadPostTransformSuccessEvent.Request.Transformation.Type + .TRANSFORMATION + ) + .protocol( + UploadPostTransformSuccessEvent.Request.Transformation.Protocol + .HLS + ) + .value("value") + .build() + ) + .xRequestId("x_request_id") + .build() + ) + .build() + + val roundtrippedUploadPostTransformSuccessEvent = + jsonMapper.readValue( + jsonMapper.writeValueAsString(uploadPostTransformSuccessEvent), + jacksonTypeRef(), + ) + + assertThat(roundtrippedUploadPostTransformSuccessEvent) + .isEqualTo(uploadPostTransformSuccessEvent) + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/webhooks/UploadPreTransformErrorEventTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/webhooks/UploadPreTransformErrorEventTest.kt new file mode 100644 index 0000000..e02922a --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/webhooks/UploadPreTransformErrorEventTest.kt @@ -0,0 +1,111 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.webhooks + +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.imagekit.api.core.jsonMapper +import java.time.OffsetDateTime +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class UploadPreTransformErrorEventTest { + + @Test + fun create() { + val uploadPreTransformErrorEvent = + UploadPreTransformErrorEvent.builder() + .id("id") + .type("upload.pre-transform.error") + .createdAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .data( + UploadPreTransformErrorEvent.Data.builder() + .name("name") + .path("path") + .transformation( + UploadPreTransformErrorEvent.Data.Transformation.builder() + .error( + UploadPreTransformErrorEvent.Data.Transformation.Error.builder() + .reason("encoding_failed") + .build() + ) + .build() + ) + .build() + ) + .request( + UploadPreTransformErrorEvent.Request.builder() + .transformation("transformation") + .xRequestId("x_request_id") + .build() + ) + .build() + + assertThat(uploadPreTransformErrorEvent.id()).isEqualTo("id") + assertThat(uploadPreTransformErrorEvent.type()).isEqualTo("upload.pre-transform.error") + assertThat(uploadPreTransformErrorEvent.createdAt()) + .isEqualTo(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + assertThat(uploadPreTransformErrorEvent.data()) + .isEqualTo( + UploadPreTransformErrorEvent.Data.builder() + .name("name") + .path("path") + .transformation( + UploadPreTransformErrorEvent.Data.Transformation.builder() + .error( + UploadPreTransformErrorEvent.Data.Transformation.Error.builder() + .reason("encoding_failed") + .build() + ) + .build() + ) + .build() + ) + assertThat(uploadPreTransformErrorEvent.request()) + .isEqualTo( + UploadPreTransformErrorEvent.Request.builder() + .transformation("transformation") + .xRequestId("x_request_id") + .build() + ) + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val uploadPreTransformErrorEvent = + UploadPreTransformErrorEvent.builder() + .id("id") + .type("upload.pre-transform.error") + .createdAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .data( + UploadPreTransformErrorEvent.Data.builder() + .name("name") + .path("path") + .transformation( + UploadPreTransformErrorEvent.Data.Transformation.builder() + .error( + UploadPreTransformErrorEvent.Data.Transformation.Error.builder() + .reason("encoding_failed") + .build() + ) + .build() + ) + .build() + ) + .request( + UploadPreTransformErrorEvent.Request.builder() + .transformation("transformation") + .xRequestId("x_request_id") + .build() + ) + .build() + + val roundtrippedUploadPreTransformErrorEvent = + jsonMapper.readValue( + jsonMapper.writeValueAsString(uploadPreTransformErrorEvent), + jacksonTypeRef(), + ) + + assertThat(roundtrippedUploadPreTransformErrorEvent).isEqualTo(uploadPreTransformErrorEvent) + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/webhooks/UploadPreTransformSuccessEventTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/webhooks/UploadPreTransformSuccessEventTest.kt new file mode 100644 index 0000000..241d7ac --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/webhooks/UploadPreTransformSuccessEventTest.kt @@ -0,0 +1,539 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.webhooks + +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.imagekit.api.core.JsonValue +import com.imagekit.api.core.jsonMapper +import com.imagekit.api.models.files.Metadata +import java.time.OffsetDateTime +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class UploadPreTransformSuccessEventTest { + + @Test + fun create() { + val uploadPreTransformSuccessEvent = + UploadPreTransformSuccessEvent.builder() + .id("id") + .type("upload.pre-transform.success") + .createdAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .data( + UploadPreTransformSuccessEvent.Data.builder() + .addAiTag( + UploadPreTransformSuccessEvent.Data.AiTag.builder() + .confidence(0.0) + .name("name") + .source("source") + .build() + ) + .audioCodec("audioCodec") + .bitRate(0L) + .customCoordinates("customCoordinates") + .customMetadata( + UploadPreTransformSuccessEvent.Data.CustomMetadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .description("description") + .duration(0L) + .embeddedMetadata( + UploadPreTransformSuccessEvent.Data.EmbeddedMetadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .extensionStatus( + UploadPreTransformSuccessEvent.Data.ExtensionStatus.builder() + .aiAutoDescription( + UploadPreTransformSuccessEvent.Data.ExtensionStatus + .AiAutoDescription + .SUCCESS + ) + .awsAutoTagging( + UploadPreTransformSuccessEvent.Data.ExtensionStatus + .AwsAutoTagging + .SUCCESS + ) + .googleAutoTagging( + UploadPreTransformSuccessEvent.Data.ExtensionStatus + .GoogleAutoTagging + .SUCCESS + ) + .removeBg( + UploadPreTransformSuccessEvent.Data.ExtensionStatus.RemoveBg + .SUCCESS + ) + .build() + ) + .fileId("fileId") + .filePath("filePath") + .fileType("fileType") + .height(0.0) + .isPrivateFile(true) + .isPublished(true) + .metadata( + Metadata.builder() + .audioCodec("audioCodec") + .bitRate(0L) + .density(0L) + .duration(0L) + .exif( + Metadata.Exif.builder() + .exif( + Metadata.Exif.InnerExif.builder() + .apertureValue(0.0) + .colorSpace(0L) + .createDate("CreateDate") + .customRendered(0L) + .dateTimeOriginal("DateTimeOriginal") + .exifImageHeight(0L) + .exifImageWidth(0L) + .exifVersion("ExifVersion") + .exposureCompensation(0.0) + .exposureMode(0L) + .exposureProgram(0L) + .exposureTime(0.0) + .flash(0L) + .flashpixVersion("FlashpixVersion") + .fNumber(0.0) + .focalLength(0L) + .focalPlaneResolutionUnit(0L) + .focalPlaneXResolution(0.0) + .focalPlaneYResolution(0.0) + .interopOffset(0L) + .iso(0L) + .meteringMode(0L) + .sceneCaptureType(0L) + .shutterSpeedValue(0.0) + .subSecTime("SubSecTime") + .whiteBalance(0L) + .build() + ) + .gps( + Metadata.Exif.Gps.builder().addGpsVersionId(0L).build() + ) + .image( + Metadata.Exif.Image.builder() + .exifOffset(0L) + .gpsInfo(0L) + .make("Make") + .model("Model") + .modifyDate("ModifyDate") + .orientation(0L) + .resolutionUnit(0L) + .software("Software") + .xResolution(0L) + .yCbCrPositioning(0L) + .yResolution(0L) + .build() + ) + .interoperability( + Metadata.Exif.Interoperability.builder() + .interopIndex("InteropIndex") + .interopVersion("InteropVersion") + .build() + ) + .makernote( + Metadata.Exif.Makernote.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .thumbnail( + Metadata.Exif.Thumbnail.builder() + .compression(0L) + .resolutionUnit(0L) + .thumbnailLength(0L) + .thumbnailOffset(0L) + .xResolution(0L) + .yResolution(0L) + .build() + ) + .build() + ) + .format("format") + .hasColorProfile(true) + .hasTransparency(true) + .height(0L) + .pHash("pHash") + .quality(0L) + .size(0L) + .videoCodec("videoCodec") + .width(0L) + .build() + ) + .name("name") + .size(0.0) + .addTag("string") + .thumbnailUrl("thumbnailUrl") + .url("url") + .versionInfo( + UploadPreTransformSuccessEvent.Data.VersionInfo.builder() + .id("id") + .name("name") + .build() + ) + .videoCodec("videoCodec") + .width(0.0) + .build() + ) + .request( + UploadPreTransformSuccessEvent.Request.builder() + .transformation("transformation") + .xRequestId("x_request_id") + .build() + ) + .build() + + assertThat(uploadPreTransformSuccessEvent.id()).isEqualTo("id") + assertThat(uploadPreTransformSuccessEvent.type()).isEqualTo("upload.pre-transform.success") + assertThat(uploadPreTransformSuccessEvent.createdAt()) + .isEqualTo(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + assertThat(uploadPreTransformSuccessEvent.data()) + .isEqualTo( + UploadPreTransformSuccessEvent.Data.builder() + .addAiTag( + UploadPreTransformSuccessEvent.Data.AiTag.builder() + .confidence(0.0) + .name("name") + .source("source") + .build() + ) + .audioCodec("audioCodec") + .bitRate(0L) + .customCoordinates("customCoordinates") + .customMetadata( + UploadPreTransformSuccessEvent.Data.CustomMetadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .description("description") + .duration(0L) + .embeddedMetadata( + UploadPreTransformSuccessEvent.Data.EmbeddedMetadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .extensionStatus( + UploadPreTransformSuccessEvent.Data.ExtensionStatus.builder() + .aiAutoDescription( + UploadPreTransformSuccessEvent.Data.ExtensionStatus + .AiAutoDescription + .SUCCESS + ) + .awsAutoTagging( + UploadPreTransformSuccessEvent.Data.ExtensionStatus.AwsAutoTagging + .SUCCESS + ) + .googleAutoTagging( + UploadPreTransformSuccessEvent.Data.ExtensionStatus + .GoogleAutoTagging + .SUCCESS + ) + .removeBg( + UploadPreTransformSuccessEvent.Data.ExtensionStatus.RemoveBg.SUCCESS + ) + .build() + ) + .fileId("fileId") + .filePath("filePath") + .fileType("fileType") + .height(0.0) + .isPrivateFile(true) + .isPublished(true) + .metadata( + Metadata.builder() + .audioCodec("audioCodec") + .bitRate(0L) + .density(0L) + .duration(0L) + .exif( + Metadata.Exif.builder() + .exif( + Metadata.Exif.InnerExif.builder() + .apertureValue(0.0) + .colorSpace(0L) + .createDate("CreateDate") + .customRendered(0L) + .dateTimeOriginal("DateTimeOriginal") + .exifImageHeight(0L) + .exifImageWidth(0L) + .exifVersion("ExifVersion") + .exposureCompensation(0.0) + .exposureMode(0L) + .exposureProgram(0L) + .exposureTime(0.0) + .flash(0L) + .flashpixVersion("FlashpixVersion") + .fNumber(0.0) + .focalLength(0L) + .focalPlaneResolutionUnit(0L) + .focalPlaneXResolution(0.0) + .focalPlaneYResolution(0.0) + .interopOffset(0L) + .iso(0L) + .meteringMode(0L) + .sceneCaptureType(0L) + .shutterSpeedValue(0.0) + .subSecTime("SubSecTime") + .whiteBalance(0L) + .build() + ) + .gps(Metadata.Exif.Gps.builder().addGpsVersionId(0L).build()) + .image( + Metadata.Exif.Image.builder() + .exifOffset(0L) + .gpsInfo(0L) + .make("Make") + .model("Model") + .modifyDate("ModifyDate") + .orientation(0L) + .resolutionUnit(0L) + .software("Software") + .xResolution(0L) + .yCbCrPositioning(0L) + .yResolution(0L) + .build() + ) + .interoperability( + Metadata.Exif.Interoperability.builder() + .interopIndex("InteropIndex") + .interopVersion("InteropVersion") + .build() + ) + .makernote( + Metadata.Exif.Makernote.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .thumbnail( + Metadata.Exif.Thumbnail.builder() + .compression(0L) + .resolutionUnit(0L) + .thumbnailLength(0L) + .thumbnailOffset(0L) + .xResolution(0L) + .yResolution(0L) + .build() + ) + .build() + ) + .format("format") + .hasColorProfile(true) + .hasTransparency(true) + .height(0L) + .pHash("pHash") + .quality(0L) + .size(0L) + .videoCodec("videoCodec") + .width(0L) + .build() + ) + .name("name") + .size(0.0) + .addTag("string") + .thumbnailUrl("thumbnailUrl") + .url("url") + .versionInfo( + UploadPreTransformSuccessEvent.Data.VersionInfo.builder() + .id("id") + .name("name") + .build() + ) + .videoCodec("videoCodec") + .width(0.0) + .build() + ) + assertThat(uploadPreTransformSuccessEvent.request()) + .isEqualTo( + UploadPreTransformSuccessEvent.Request.builder() + .transformation("transformation") + .xRequestId("x_request_id") + .build() + ) + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val uploadPreTransformSuccessEvent = + UploadPreTransformSuccessEvent.builder() + .id("id") + .type("upload.pre-transform.success") + .createdAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .data( + UploadPreTransformSuccessEvent.Data.builder() + .addAiTag( + UploadPreTransformSuccessEvent.Data.AiTag.builder() + .confidence(0.0) + .name("name") + .source("source") + .build() + ) + .audioCodec("audioCodec") + .bitRate(0L) + .customCoordinates("customCoordinates") + .customMetadata( + UploadPreTransformSuccessEvent.Data.CustomMetadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .description("description") + .duration(0L) + .embeddedMetadata( + UploadPreTransformSuccessEvent.Data.EmbeddedMetadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .extensionStatus( + UploadPreTransformSuccessEvent.Data.ExtensionStatus.builder() + .aiAutoDescription( + UploadPreTransformSuccessEvent.Data.ExtensionStatus + .AiAutoDescription + .SUCCESS + ) + .awsAutoTagging( + UploadPreTransformSuccessEvent.Data.ExtensionStatus + .AwsAutoTagging + .SUCCESS + ) + .googleAutoTagging( + UploadPreTransformSuccessEvent.Data.ExtensionStatus + .GoogleAutoTagging + .SUCCESS + ) + .removeBg( + UploadPreTransformSuccessEvent.Data.ExtensionStatus.RemoveBg + .SUCCESS + ) + .build() + ) + .fileId("fileId") + .filePath("filePath") + .fileType("fileType") + .height(0.0) + .isPrivateFile(true) + .isPublished(true) + .metadata( + Metadata.builder() + .audioCodec("audioCodec") + .bitRate(0L) + .density(0L) + .duration(0L) + .exif( + Metadata.Exif.builder() + .exif( + Metadata.Exif.InnerExif.builder() + .apertureValue(0.0) + .colorSpace(0L) + .createDate("CreateDate") + .customRendered(0L) + .dateTimeOriginal("DateTimeOriginal") + .exifImageHeight(0L) + .exifImageWidth(0L) + .exifVersion("ExifVersion") + .exposureCompensation(0.0) + .exposureMode(0L) + .exposureProgram(0L) + .exposureTime(0.0) + .flash(0L) + .flashpixVersion("FlashpixVersion") + .fNumber(0.0) + .focalLength(0L) + .focalPlaneResolutionUnit(0L) + .focalPlaneXResolution(0.0) + .focalPlaneYResolution(0.0) + .interopOffset(0L) + .iso(0L) + .meteringMode(0L) + .sceneCaptureType(0L) + .shutterSpeedValue(0.0) + .subSecTime("SubSecTime") + .whiteBalance(0L) + .build() + ) + .gps( + Metadata.Exif.Gps.builder().addGpsVersionId(0L).build() + ) + .image( + Metadata.Exif.Image.builder() + .exifOffset(0L) + .gpsInfo(0L) + .make("Make") + .model("Model") + .modifyDate("ModifyDate") + .orientation(0L) + .resolutionUnit(0L) + .software("Software") + .xResolution(0L) + .yCbCrPositioning(0L) + .yResolution(0L) + .build() + ) + .interoperability( + Metadata.Exif.Interoperability.builder() + .interopIndex("InteropIndex") + .interopVersion("InteropVersion") + .build() + ) + .makernote( + Metadata.Exif.Makernote.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .thumbnail( + Metadata.Exif.Thumbnail.builder() + .compression(0L) + .resolutionUnit(0L) + .thumbnailLength(0L) + .thumbnailOffset(0L) + .xResolution(0L) + .yResolution(0L) + .build() + ) + .build() + ) + .format("format") + .hasColorProfile(true) + .hasTransparency(true) + .height(0L) + .pHash("pHash") + .quality(0L) + .size(0L) + .videoCodec("videoCodec") + .width(0L) + .build() + ) + .name("name") + .size(0.0) + .addTag("string") + .thumbnailUrl("thumbnailUrl") + .url("url") + .versionInfo( + UploadPreTransformSuccessEvent.Data.VersionInfo.builder() + .id("id") + .name("name") + .build() + ) + .videoCodec("videoCodec") + .width(0.0) + .build() + ) + .request( + UploadPreTransformSuccessEvent.Request.builder() + .transformation("transformation") + .xRequestId("x_request_id") + .build() + ) + .build() + + val roundtrippedUploadPreTransformSuccessEvent = + jsonMapper.readValue( + jsonMapper.writeValueAsString(uploadPreTransformSuccessEvent), + jacksonTypeRef(), + ) + + assertThat(roundtrippedUploadPreTransformSuccessEvent) + .isEqualTo(uploadPreTransformSuccessEvent) + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/webhooks/VideoTransformationAcceptedEventTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/webhooks/VideoTransformationAcceptedEventTest.kt new file mode 100644 index 0000000..3ae8d59 --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/webhooks/VideoTransformationAcceptedEventTest.kt @@ -0,0 +1,214 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.webhooks + +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.imagekit.api.core.jsonMapper +import java.time.OffsetDateTime +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class VideoTransformationAcceptedEventTest { + + @Test + fun create() { + val videoTransformationAcceptedEvent = + VideoTransformationAcceptedEvent.builder() + .id("id") + .type("video.transformation.accepted") + .createdAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .data( + VideoTransformationAcceptedEvent.Data.builder() + .asset( + VideoTransformationAcceptedEvent.Data.Asset.builder() + .url("https://example.com") + .build() + ) + .transformation( + VideoTransformationAcceptedEvent.Data.Transformation.builder() + .type( + VideoTransformationAcceptedEvent.Data.Transformation.Type + .VIDEO_TRANSFORMATION + ) + .options( + VideoTransformationAcceptedEvent.Data.Transformation.Options + .builder() + .audioCodec( + VideoTransformationAcceptedEvent.Data.Transformation + .Options + .AudioCodec + .AAC + ) + .autoRotate(true) + .format( + VideoTransformationAcceptedEvent.Data.Transformation + .Options + .Format + .MP4 + ) + .quality(0L) + .streamProtocol( + VideoTransformationAcceptedEvent.Data.Transformation + .Options + .StreamProtocol + .HLS + ) + .addVariant("string") + .videoCodec( + VideoTransformationAcceptedEvent.Data.Transformation + .Options + .VideoCodec + .H264 + ) + .build() + ) + .build() + ) + .build() + ) + .request( + VideoTransformationAcceptedEvent.Request.builder() + .url("https://example.com") + .xRequestId("x_request_id") + .userAgent("user_agent") + .build() + ) + .build() + + assertThat(videoTransformationAcceptedEvent.id()).isEqualTo("id") + assertThat(videoTransformationAcceptedEvent.type()) + .isEqualTo("video.transformation.accepted") + assertThat(videoTransformationAcceptedEvent.createdAt()) + .isEqualTo(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + assertThat(videoTransformationAcceptedEvent.data()) + .isEqualTo( + VideoTransformationAcceptedEvent.Data.builder() + .asset( + VideoTransformationAcceptedEvent.Data.Asset.builder() + .url("https://example.com") + .build() + ) + .transformation( + VideoTransformationAcceptedEvent.Data.Transformation.builder() + .type( + VideoTransformationAcceptedEvent.Data.Transformation.Type + .VIDEO_TRANSFORMATION + ) + .options( + VideoTransformationAcceptedEvent.Data.Transformation.Options + .builder() + .audioCodec( + VideoTransformationAcceptedEvent.Data.Transformation.Options + .AudioCodec + .AAC + ) + .autoRotate(true) + .format( + VideoTransformationAcceptedEvent.Data.Transformation.Options + .Format + .MP4 + ) + .quality(0L) + .streamProtocol( + VideoTransformationAcceptedEvent.Data.Transformation.Options + .StreamProtocol + .HLS + ) + .addVariant("string") + .videoCodec( + VideoTransformationAcceptedEvent.Data.Transformation.Options + .VideoCodec + .H264 + ) + .build() + ) + .build() + ) + .build() + ) + assertThat(videoTransformationAcceptedEvent.request()) + .isEqualTo( + VideoTransformationAcceptedEvent.Request.builder() + .url("https://example.com") + .xRequestId("x_request_id") + .userAgent("user_agent") + .build() + ) + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val videoTransformationAcceptedEvent = + VideoTransformationAcceptedEvent.builder() + .id("id") + .type("video.transformation.accepted") + .createdAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .data( + VideoTransformationAcceptedEvent.Data.builder() + .asset( + VideoTransformationAcceptedEvent.Data.Asset.builder() + .url("https://example.com") + .build() + ) + .transformation( + VideoTransformationAcceptedEvent.Data.Transformation.builder() + .type( + VideoTransformationAcceptedEvent.Data.Transformation.Type + .VIDEO_TRANSFORMATION + ) + .options( + VideoTransformationAcceptedEvent.Data.Transformation.Options + .builder() + .audioCodec( + VideoTransformationAcceptedEvent.Data.Transformation + .Options + .AudioCodec + .AAC + ) + .autoRotate(true) + .format( + VideoTransformationAcceptedEvent.Data.Transformation + .Options + .Format + .MP4 + ) + .quality(0L) + .streamProtocol( + VideoTransformationAcceptedEvent.Data.Transformation + .Options + .StreamProtocol + .HLS + ) + .addVariant("string") + .videoCodec( + VideoTransformationAcceptedEvent.Data.Transformation + .Options + .VideoCodec + .H264 + ) + .build() + ) + .build() + ) + .build() + ) + .request( + VideoTransformationAcceptedEvent.Request.builder() + .url("https://example.com") + .xRequestId("x_request_id") + .userAgent("user_agent") + .build() + ) + .build() + + val roundtrippedVideoTransformationAcceptedEvent = + jsonMapper.readValue( + jsonMapper.writeValueAsString(videoTransformationAcceptedEvent), + jacksonTypeRef(), + ) + + assertThat(roundtrippedVideoTransformationAcceptedEvent) + .isEqualTo(videoTransformationAcceptedEvent) + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/webhooks/VideoTransformationErrorEventTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/webhooks/VideoTransformationErrorEventTest.kt new file mode 100644 index 0000000..f03c9e2 --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/webhooks/VideoTransformationErrorEventTest.kt @@ -0,0 +1,241 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.webhooks + +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.imagekit.api.core.jsonMapper +import java.time.OffsetDateTime +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class VideoTransformationErrorEventTest { + + @Test + fun create() { + val videoTransformationErrorEvent = + VideoTransformationErrorEvent.builder() + .id("id") + .type("video.transformation.error") + .createdAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .data( + VideoTransformationErrorEvent.Data.builder() + .asset( + VideoTransformationErrorEvent.Data.Asset.builder() + .url("https://example.com") + .build() + ) + .transformation( + VideoTransformationErrorEvent.Data.Transformation.builder() + .type( + VideoTransformationErrorEvent.Data.Transformation.Type + .VIDEO_TRANSFORMATION + ) + .error( + VideoTransformationErrorEvent.Data.Transformation.Error + .builder() + .reason( + VideoTransformationErrorEvent.Data.Transformation.Error + .Reason + .ENCODING_FAILED + ) + .build() + ) + .options( + VideoTransformationErrorEvent.Data.Transformation.Options + .builder() + .audioCodec( + VideoTransformationErrorEvent.Data.Transformation + .Options + .AudioCodec + .AAC + ) + .autoRotate(true) + .format( + VideoTransformationErrorEvent.Data.Transformation + .Options + .Format + .MP4 + ) + .quality(0L) + .streamProtocol( + VideoTransformationErrorEvent.Data.Transformation + .Options + .StreamProtocol + .HLS + ) + .addVariant("string") + .videoCodec( + VideoTransformationErrorEvent.Data.Transformation + .Options + .VideoCodec + .H264 + ) + .build() + ) + .build() + ) + .build() + ) + .request( + VideoTransformationErrorEvent.Request.builder() + .url("https://example.com") + .xRequestId("x_request_id") + .userAgent("user_agent") + .build() + ) + .build() + + assertThat(videoTransformationErrorEvent.id()).isEqualTo("id") + assertThat(videoTransformationErrorEvent.type()).isEqualTo("video.transformation.error") + assertThat(videoTransformationErrorEvent.createdAt()) + .isEqualTo(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + assertThat(videoTransformationErrorEvent.data()) + .isEqualTo( + VideoTransformationErrorEvent.Data.builder() + .asset( + VideoTransformationErrorEvent.Data.Asset.builder() + .url("https://example.com") + .build() + ) + .transformation( + VideoTransformationErrorEvent.Data.Transformation.builder() + .type( + VideoTransformationErrorEvent.Data.Transformation.Type + .VIDEO_TRANSFORMATION + ) + .error( + VideoTransformationErrorEvent.Data.Transformation.Error.builder() + .reason( + VideoTransformationErrorEvent.Data.Transformation.Error + .Reason + .ENCODING_FAILED + ) + .build() + ) + .options( + VideoTransformationErrorEvent.Data.Transformation.Options.builder() + .audioCodec( + VideoTransformationErrorEvent.Data.Transformation.Options + .AudioCodec + .AAC + ) + .autoRotate(true) + .format( + VideoTransformationErrorEvent.Data.Transformation.Options + .Format + .MP4 + ) + .quality(0L) + .streamProtocol( + VideoTransformationErrorEvent.Data.Transformation.Options + .StreamProtocol + .HLS + ) + .addVariant("string") + .videoCodec( + VideoTransformationErrorEvent.Data.Transformation.Options + .VideoCodec + .H264 + ) + .build() + ) + .build() + ) + .build() + ) + assertThat(videoTransformationErrorEvent.request()) + .isEqualTo( + VideoTransformationErrorEvent.Request.builder() + .url("https://example.com") + .xRequestId("x_request_id") + .userAgent("user_agent") + .build() + ) + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val videoTransformationErrorEvent = + VideoTransformationErrorEvent.builder() + .id("id") + .type("video.transformation.error") + .createdAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .data( + VideoTransformationErrorEvent.Data.builder() + .asset( + VideoTransformationErrorEvent.Data.Asset.builder() + .url("https://example.com") + .build() + ) + .transformation( + VideoTransformationErrorEvent.Data.Transformation.builder() + .type( + VideoTransformationErrorEvent.Data.Transformation.Type + .VIDEO_TRANSFORMATION + ) + .error( + VideoTransformationErrorEvent.Data.Transformation.Error + .builder() + .reason( + VideoTransformationErrorEvent.Data.Transformation.Error + .Reason + .ENCODING_FAILED + ) + .build() + ) + .options( + VideoTransformationErrorEvent.Data.Transformation.Options + .builder() + .audioCodec( + VideoTransformationErrorEvent.Data.Transformation + .Options + .AudioCodec + .AAC + ) + .autoRotate(true) + .format( + VideoTransformationErrorEvent.Data.Transformation + .Options + .Format + .MP4 + ) + .quality(0L) + .streamProtocol( + VideoTransformationErrorEvent.Data.Transformation + .Options + .StreamProtocol + .HLS + ) + .addVariant("string") + .videoCodec( + VideoTransformationErrorEvent.Data.Transformation + .Options + .VideoCodec + .H264 + ) + .build() + ) + .build() + ) + .build() + ) + .request( + VideoTransformationErrorEvent.Request.builder() + .url("https://example.com") + .xRequestId("x_request_id") + .userAgent("user_agent") + .build() + ) + .build() + + val roundtrippedVideoTransformationErrorEvent = + jsonMapper.readValue( + jsonMapper.writeValueAsString(videoTransformationErrorEvent), + jacksonTypeRef(), + ) + + assertThat(roundtrippedVideoTransformationErrorEvent) + .isEqualTo(videoTransformationErrorEvent) + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/webhooks/VideoTransformationReadyEventTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/webhooks/VideoTransformationReadyEventTest.kt new file mode 100644 index 0000000..a65e2a1 --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/models/webhooks/VideoTransformationReadyEventTest.kt @@ -0,0 +1,278 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.models.webhooks + +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.imagekit.api.core.jsonMapper +import java.time.OffsetDateTime +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class VideoTransformationReadyEventTest { + + @Test + fun create() { + val videoTransformationReadyEvent = + VideoTransformationReadyEvent.builder() + .id("id") + .type("video.transformation.ready") + .createdAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .data( + VideoTransformationReadyEvent.Data.builder() + .asset( + VideoTransformationReadyEvent.Data.Asset.builder() + .url("https://example.com") + .build() + ) + .transformation( + VideoTransformationReadyEvent.Data.Transformation.builder() + .type( + VideoTransformationReadyEvent.Data.Transformation.Type + .VIDEO_TRANSFORMATION + ) + .options( + VideoTransformationReadyEvent.Data.Transformation.Options + .builder() + .audioCodec( + VideoTransformationReadyEvent.Data.Transformation + .Options + .AudioCodec + .AAC + ) + .autoRotate(true) + .format( + VideoTransformationReadyEvent.Data.Transformation + .Options + .Format + .MP4 + ) + .quality(0L) + .streamProtocol( + VideoTransformationReadyEvent.Data.Transformation + .Options + .StreamProtocol + .HLS + ) + .addVariant("string") + .videoCodec( + VideoTransformationReadyEvent.Data.Transformation + .Options + .VideoCodec + .H264 + ) + .build() + ) + .output( + VideoTransformationReadyEvent.Data.Transformation.Output + .builder() + .url("https://example.com") + .videoMetadata( + VideoTransformationReadyEvent.Data.Transformation.Output + .VideoMetadata + .builder() + .bitrate(0L) + .duration(0.0) + .height(0L) + .width(0L) + .build() + ) + .build() + ) + .build() + ) + .build() + ) + .request( + VideoTransformationReadyEvent.Request.builder() + .url("https://example.com") + .xRequestId("x_request_id") + .userAgent("user_agent") + .build() + ) + .timings( + VideoTransformationReadyEvent.Timings.builder() + .downloadDuration(0L) + .encodingDuration(0L) + .build() + ) + .build() + + assertThat(videoTransformationReadyEvent.id()).isEqualTo("id") + assertThat(videoTransformationReadyEvent.type()).isEqualTo("video.transformation.ready") + assertThat(videoTransformationReadyEvent.createdAt()) + .isEqualTo(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + assertThat(videoTransformationReadyEvent.data()) + .isEqualTo( + VideoTransformationReadyEvent.Data.builder() + .asset( + VideoTransformationReadyEvent.Data.Asset.builder() + .url("https://example.com") + .build() + ) + .transformation( + VideoTransformationReadyEvent.Data.Transformation.builder() + .type( + VideoTransformationReadyEvent.Data.Transformation.Type + .VIDEO_TRANSFORMATION + ) + .options( + VideoTransformationReadyEvent.Data.Transformation.Options.builder() + .audioCodec( + VideoTransformationReadyEvent.Data.Transformation.Options + .AudioCodec + .AAC + ) + .autoRotate(true) + .format( + VideoTransformationReadyEvent.Data.Transformation.Options + .Format + .MP4 + ) + .quality(0L) + .streamProtocol( + VideoTransformationReadyEvent.Data.Transformation.Options + .StreamProtocol + .HLS + ) + .addVariant("string") + .videoCodec( + VideoTransformationReadyEvent.Data.Transformation.Options + .VideoCodec + .H264 + ) + .build() + ) + .output( + VideoTransformationReadyEvent.Data.Transformation.Output.builder() + .url("https://example.com") + .videoMetadata( + VideoTransformationReadyEvent.Data.Transformation.Output + .VideoMetadata + .builder() + .bitrate(0L) + .duration(0.0) + .height(0L) + .width(0L) + .build() + ) + .build() + ) + .build() + ) + .build() + ) + assertThat(videoTransformationReadyEvent.request()) + .isEqualTo( + VideoTransformationReadyEvent.Request.builder() + .url("https://example.com") + .xRequestId("x_request_id") + .userAgent("user_agent") + .build() + ) + assertThat(videoTransformationReadyEvent.timings()) + .contains( + VideoTransformationReadyEvent.Timings.builder() + .downloadDuration(0L) + .encodingDuration(0L) + .build() + ) + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val videoTransformationReadyEvent = + VideoTransformationReadyEvent.builder() + .id("id") + .type("video.transformation.ready") + .createdAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .data( + VideoTransformationReadyEvent.Data.builder() + .asset( + VideoTransformationReadyEvent.Data.Asset.builder() + .url("https://example.com") + .build() + ) + .transformation( + VideoTransformationReadyEvent.Data.Transformation.builder() + .type( + VideoTransformationReadyEvent.Data.Transformation.Type + .VIDEO_TRANSFORMATION + ) + .options( + VideoTransformationReadyEvent.Data.Transformation.Options + .builder() + .audioCodec( + VideoTransformationReadyEvent.Data.Transformation + .Options + .AudioCodec + .AAC + ) + .autoRotate(true) + .format( + VideoTransformationReadyEvent.Data.Transformation + .Options + .Format + .MP4 + ) + .quality(0L) + .streamProtocol( + VideoTransformationReadyEvent.Data.Transformation + .Options + .StreamProtocol + .HLS + ) + .addVariant("string") + .videoCodec( + VideoTransformationReadyEvent.Data.Transformation + .Options + .VideoCodec + .H264 + ) + .build() + ) + .output( + VideoTransformationReadyEvent.Data.Transformation.Output + .builder() + .url("https://example.com") + .videoMetadata( + VideoTransformationReadyEvent.Data.Transformation.Output + .VideoMetadata + .builder() + .bitrate(0L) + .duration(0.0) + .height(0L) + .width(0L) + .build() + ) + .build() + ) + .build() + ) + .build() + ) + .request( + VideoTransformationReadyEvent.Request.builder() + .url("https://example.com") + .xRequestId("x_request_id") + .userAgent("user_agent") + .build() + ) + .timings( + VideoTransformationReadyEvent.Timings.builder() + .downloadDuration(0L) + .encodingDuration(0L) + .build() + ) + .build() + + val roundtrippedVideoTransformationReadyEvent = + jsonMapper.readValue( + jsonMapper.writeValueAsString(videoTransformationReadyEvent), + jacksonTypeRef(), + ) + + assertThat(roundtrippedVideoTransformationReadyEvent) + .isEqualTo(videoTransformationReadyEvent) + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/services/ErrorHandlingTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/services/ErrorHandlingTest.kt new file mode 100644 index 0000000..00dad8c --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/services/ErrorHandlingTest.kt @@ -0,0 +1,1763 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services + +import com.github.tomakehurst.wiremock.client.WireMock.anyUrl +import com.github.tomakehurst.wiremock.client.WireMock.post +import com.github.tomakehurst.wiremock.client.WireMock.status +import com.github.tomakehurst.wiremock.client.WireMock.stubFor +import com.github.tomakehurst.wiremock.junit5.WireMockRuntimeInfo +import com.github.tomakehurst.wiremock.junit5.WireMockTest +import com.imagekit.api.client.ImageKitClient +import com.imagekit.api.client.okhttp.ImageKitOkHttpClient +import com.imagekit.api.core.JsonValue +import com.imagekit.api.core.http.Headers +import com.imagekit.api.core.jsonMapper +import com.imagekit.api.errors.BadRequestException +import com.imagekit.api.errors.ImageKitException +import com.imagekit.api.errors.InternalServerException +import com.imagekit.api.errors.NotFoundException +import com.imagekit.api.errors.PermissionDeniedException +import com.imagekit.api.errors.RateLimitException +import com.imagekit.api.errors.UnauthorizedException +import com.imagekit.api.errors.UnexpectedStatusCodeException +import com.imagekit.api.errors.UnprocessableEntityException +import com.imagekit.api.models.UnnamedSchemaWithArrayParent3 +import com.imagekit.api.models.files.FileUploadParams +import org.assertj.core.api.Assertions.assertThat +import org.assertj.core.api.Assertions.entry +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.assertThrows +import org.junit.jupiter.api.parallel.ResourceLock + +@WireMockTest +@ResourceLock("https://github.com/wiremock/wiremock/issues/169") +internal class ErrorHandlingTest { + + companion object { + + private val ERROR_JSON: JsonValue = JsonValue.from(mapOf("errorProperty" to "42")) + + private val ERROR_JSON_BYTES: ByteArray = jsonMapper().writeValueAsBytes(ERROR_JSON) + + private const val HEADER_NAME: String = "Error-Header" + + private const val HEADER_VALUE: String = "42" + + private const val NOT_JSON: String = "Not JSON" + } + + private lateinit var client: ImageKitClient + + @BeforeEach + fun beforeEach(wmRuntimeInfo: WireMockRuntimeInfo) { + client = + ImageKitOkHttpClient.builder() + .baseUrl(wmRuntimeInfo.httpBaseUrl) + .privateApiKey("My Private API Key") + .password("My Password") + .build() + } + + @Test + fun filesUpload400() { + val fileService = client.files() + stubFor( + post(anyUrl()) + .willReturn( + status(400).withHeader(HEADER_NAME, HEADER_VALUE).withBody(ERROR_JSON_BYTES) + ) + ) + + val e = + assertThrows { + fileService.upload( + FileUploadParams.builder() + .file("some content".byteInputStream()) + .fileName("fileName") + .token("token") + .checks("\"request.folder\" : \"marketing/\"\n") + .customCoordinates("customCoordinates") + .customMetadata( + FileUploadParams.CustomMetadata.builder() + .putAdditionalProperty("brand", JsonValue.from("bar")) + .putAdditionalProperty("color", JsonValue.from("bar")) + .build() + ) + .description("Running shoes") + .expire(0L) + .extensions( + listOf( + UnnamedSchemaWithArrayParent3.ofRemoveBg( + UnnamedSchemaWithArrayParent3.RemoveBg.builder() + .options( + UnnamedSchemaWithArrayParent3.RemoveBg.Options.builder() + .addShadow(true) + .bgColor("bg_color") + .bgImageUrl("bg_image_url") + .semitransparency(true) + .build() + ) + .build() + ), + UnnamedSchemaWithArrayParent3.ofAutoTaggingExtension( + UnnamedSchemaWithArrayParent3.AutoTaggingExtension.builder() + .maxTags(5L) + .minConfidence(95L) + .name( + UnnamedSchemaWithArrayParent3.AutoTaggingExtension.Name + .GOOGLE_AUTO_TAGGING + ) + .build() + ), + UnnamedSchemaWithArrayParent3.ofAiAutoDescription(), + ) + ) + .folder("folder") + .isPrivateFile(true) + .isPublished(true) + .overwriteAiTags(true) + .overwriteCustomMetadata(true) + .overwriteFile(true) + .overwriteTags(true) + .publicKey("publicKey") + .responseFields( + listOf( + FileUploadParams.ResponseField.TAGS, + FileUploadParams.ResponseField.CUSTOM_COORDINATES, + FileUploadParams.ResponseField.IS_PRIVATE_FILE, + ) + ) + .signature("signature") + .tags(listOf("t-shirt", "round-neck", "men")) + .transformation( + FileUploadParams.Transformation.builder() + .addPost( + FileUploadParams.Transformation.Post.Thumbnail.builder() + .value("w-150,h-150") + .build() + ) + .addPost( + FileUploadParams.Transformation.Post.Abs.builder() + .protocol( + FileUploadParams.Transformation.Post.Abs.Protocol.DASH + ) + .value("sr-240_360_480_720_1080") + .build() + ) + .pre("w-300,h-300,q-80") + .build() + ) + .useUniqueFileName(true) + .webhookUrl("https://example.com") + .build() + ) + } + + assertThat(e.statusCode()).isEqualTo(400) + assertThat(e.headers().toMap()).contains(entry(HEADER_NAME, listOf(HEADER_VALUE))) + assertThat(e.body()).isEqualTo(ERROR_JSON) + } + + @Test + fun filesUpload400WithRawResponse() { + val fileService = client.files().withRawResponse() + stubFor( + post(anyUrl()) + .willReturn( + status(400).withHeader(HEADER_NAME, HEADER_VALUE).withBody(ERROR_JSON_BYTES) + ) + ) + + val e = + assertThrows { + fileService.upload( + FileUploadParams.builder() + .file("some content".byteInputStream()) + .fileName("fileName") + .token("token") + .checks("\"request.folder\" : \"marketing/\"\n") + .customCoordinates("customCoordinates") + .customMetadata( + FileUploadParams.CustomMetadata.builder() + .putAdditionalProperty("brand", JsonValue.from("bar")) + .putAdditionalProperty("color", JsonValue.from("bar")) + .build() + ) + .description("Running shoes") + .expire(0L) + .extensions( + listOf( + UnnamedSchemaWithArrayParent3.ofRemoveBg( + UnnamedSchemaWithArrayParent3.RemoveBg.builder() + .options( + UnnamedSchemaWithArrayParent3.RemoveBg.Options.builder() + .addShadow(true) + .bgColor("bg_color") + .bgImageUrl("bg_image_url") + .semitransparency(true) + .build() + ) + .build() + ), + UnnamedSchemaWithArrayParent3.ofAutoTaggingExtension( + UnnamedSchemaWithArrayParent3.AutoTaggingExtension.builder() + .maxTags(5L) + .minConfidence(95L) + .name( + UnnamedSchemaWithArrayParent3.AutoTaggingExtension.Name + .GOOGLE_AUTO_TAGGING + ) + .build() + ), + UnnamedSchemaWithArrayParent3.ofAiAutoDescription(), + ) + ) + .folder("folder") + .isPrivateFile(true) + .isPublished(true) + .overwriteAiTags(true) + .overwriteCustomMetadata(true) + .overwriteFile(true) + .overwriteTags(true) + .publicKey("publicKey") + .responseFields( + listOf( + FileUploadParams.ResponseField.TAGS, + FileUploadParams.ResponseField.CUSTOM_COORDINATES, + FileUploadParams.ResponseField.IS_PRIVATE_FILE, + ) + ) + .signature("signature") + .tags(listOf("t-shirt", "round-neck", "men")) + .transformation( + FileUploadParams.Transformation.builder() + .addPost( + FileUploadParams.Transformation.Post.Thumbnail.builder() + .value("w-150,h-150") + .build() + ) + .addPost( + FileUploadParams.Transformation.Post.Abs.builder() + .protocol( + FileUploadParams.Transformation.Post.Abs.Protocol.DASH + ) + .value("sr-240_360_480_720_1080") + .build() + ) + .pre("w-300,h-300,q-80") + .build() + ) + .useUniqueFileName(true) + .webhookUrl("https://example.com") + .build() + ) + } + + assertThat(e.statusCode()).isEqualTo(400) + assertThat(e.headers().toMap()).contains(entry(HEADER_NAME, listOf(HEADER_VALUE))) + assertThat(e.body()).isEqualTo(ERROR_JSON) + } + + @Test + fun filesUpload401() { + val fileService = client.files() + stubFor( + post(anyUrl()) + .willReturn( + status(401).withHeader(HEADER_NAME, HEADER_VALUE).withBody(ERROR_JSON_BYTES) + ) + ) + + val e = + assertThrows { + fileService.upload( + FileUploadParams.builder() + .file("some content".byteInputStream()) + .fileName("fileName") + .token("token") + .checks("\"request.folder\" : \"marketing/\"\n") + .customCoordinates("customCoordinates") + .customMetadata( + FileUploadParams.CustomMetadata.builder() + .putAdditionalProperty("brand", JsonValue.from("bar")) + .putAdditionalProperty("color", JsonValue.from("bar")) + .build() + ) + .description("Running shoes") + .expire(0L) + .extensions( + listOf( + UnnamedSchemaWithArrayParent3.ofRemoveBg( + UnnamedSchemaWithArrayParent3.RemoveBg.builder() + .options( + UnnamedSchemaWithArrayParent3.RemoveBg.Options.builder() + .addShadow(true) + .bgColor("bg_color") + .bgImageUrl("bg_image_url") + .semitransparency(true) + .build() + ) + .build() + ), + UnnamedSchemaWithArrayParent3.ofAutoTaggingExtension( + UnnamedSchemaWithArrayParent3.AutoTaggingExtension.builder() + .maxTags(5L) + .minConfidence(95L) + .name( + UnnamedSchemaWithArrayParent3.AutoTaggingExtension.Name + .GOOGLE_AUTO_TAGGING + ) + .build() + ), + UnnamedSchemaWithArrayParent3.ofAiAutoDescription(), + ) + ) + .folder("folder") + .isPrivateFile(true) + .isPublished(true) + .overwriteAiTags(true) + .overwriteCustomMetadata(true) + .overwriteFile(true) + .overwriteTags(true) + .publicKey("publicKey") + .responseFields( + listOf( + FileUploadParams.ResponseField.TAGS, + FileUploadParams.ResponseField.CUSTOM_COORDINATES, + FileUploadParams.ResponseField.IS_PRIVATE_FILE, + ) + ) + .signature("signature") + .tags(listOf("t-shirt", "round-neck", "men")) + .transformation( + FileUploadParams.Transformation.builder() + .addPost( + FileUploadParams.Transformation.Post.Thumbnail.builder() + .value("w-150,h-150") + .build() + ) + .addPost( + FileUploadParams.Transformation.Post.Abs.builder() + .protocol( + FileUploadParams.Transformation.Post.Abs.Protocol.DASH + ) + .value("sr-240_360_480_720_1080") + .build() + ) + .pre("w-300,h-300,q-80") + .build() + ) + .useUniqueFileName(true) + .webhookUrl("https://example.com") + .build() + ) + } + + assertThat(e.statusCode()).isEqualTo(401) + assertThat(e.headers().toMap()).contains(entry(HEADER_NAME, listOf(HEADER_VALUE))) + assertThat(e.body()).isEqualTo(ERROR_JSON) + } + + @Test + fun filesUpload401WithRawResponse() { + val fileService = client.files().withRawResponse() + stubFor( + post(anyUrl()) + .willReturn( + status(401).withHeader(HEADER_NAME, HEADER_VALUE).withBody(ERROR_JSON_BYTES) + ) + ) + + val e = + assertThrows { + fileService.upload( + FileUploadParams.builder() + .file("some content".byteInputStream()) + .fileName("fileName") + .token("token") + .checks("\"request.folder\" : \"marketing/\"\n") + .customCoordinates("customCoordinates") + .customMetadata( + FileUploadParams.CustomMetadata.builder() + .putAdditionalProperty("brand", JsonValue.from("bar")) + .putAdditionalProperty("color", JsonValue.from("bar")) + .build() + ) + .description("Running shoes") + .expire(0L) + .extensions( + listOf( + UnnamedSchemaWithArrayParent3.ofRemoveBg( + UnnamedSchemaWithArrayParent3.RemoveBg.builder() + .options( + UnnamedSchemaWithArrayParent3.RemoveBg.Options.builder() + .addShadow(true) + .bgColor("bg_color") + .bgImageUrl("bg_image_url") + .semitransparency(true) + .build() + ) + .build() + ), + UnnamedSchemaWithArrayParent3.ofAutoTaggingExtension( + UnnamedSchemaWithArrayParent3.AutoTaggingExtension.builder() + .maxTags(5L) + .minConfidence(95L) + .name( + UnnamedSchemaWithArrayParent3.AutoTaggingExtension.Name + .GOOGLE_AUTO_TAGGING + ) + .build() + ), + UnnamedSchemaWithArrayParent3.ofAiAutoDescription(), + ) + ) + .folder("folder") + .isPrivateFile(true) + .isPublished(true) + .overwriteAiTags(true) + .overwriteCustomMetadata(true) + .overwriteFile(true) + .overwriteTags(true) + .publicKey("publicKey") + .responseFields( + listOf( + FileUploadParams.ResponseField.TAGS, + FileUploadParams.ResponseField.CUSTOM_COORDINATES, + FileUploadParams.ResponseField.IS_PRIVATE_FILE, + ) + ) + .signature("signature") + .tags(listOf("t-shirt", "round-neck", "men")) + .transformation( + FileUploadParams.Transformation.builder() + .addPost( + FileUploadParams.Transformation.Post.Thumbnail.builder() + .value("w-150,h-150") + .build() + ) + .addPost( + FileUploadParams.Transformation.Post.Abs.builder() + .protocol( + FileUploadParams.Transformation.Post.Abs.Protocol.DASH + ) + .value("sr-240_360_480_720_1080") + .build() + ) + .pre("w-300,h-300,q-80") + .build() + ) + .useUniqueFileName(true) + .webhookUrl("https://example.com") + .build() + ) + } + + assertThat(e.statusCode()).isEqualTo(401) + assertThat(e.headers().toMap()).contains(entry(HEADER_NAME, listOf(HEADER_VALUE))) + assertThat(e.body()).isEqualTo(ERROR_JSON) + } + + @Test + fun filesUpload403() { + val fileService = client.files() + stubFor( + post(anyUrl()) + .willReturn( + status(403).withHeader(HEADER_NAME, HEADER_VALUE).withBody(ERROR_JSON_BYTES) + ) + ) + + val e = + assertThrows { + fileService.upload( + FileUploadParams.builder() + .file("some content".byteInputStream()) + .fileName("fileName") + .token("token") + .checks("\"request.folder\" : \"marketing/\"\n") + .customCoordinates("customCoordinates") + .customMetadata( + FileUploadParams.CustomMetadata.builder() + .putAdditionalProperty("brand", JsonValue.from("bar")) + .putAdditionalProperty("color", JsonValue.from("bar")) + .build() + ) + .description("Running shoes") + .expire(0L) + .extensions( + listOf( + UnnamedSchemaWithArrayParent3.ofRemoveBg( + UnnamedSchemaWithArrayParent3.RemoveBg.builder() + .options( + UnnamedSchemaWithArrayParent3.RemoveBg.Options.builder() + .addShadow(true) + .bgColor("bg_color") + .bgImageUrl("bg_image_url") + .semitransparency(true) + .build() + ) + .build() + ), + UnnamedSchemaWithArrayParent3.ofAutoTaggingExtension( + UnnamedSchemaWithArrayParent3.AutoTaggingExtension.builder() + .maxTags(5L) + .minConfidence(95L) + .name( + UnnamedSchemaWithArrayParent3.AutoTaggingExtension.Name + .GOOGLE_AUTO_TAGGING + ) + .build() + ), + UnnamedSchemaWithArrayParent3.ofAiAutoDescription(), + ) + ) + .folder("folder") + .isPrivateFile(true) + .isPublished(true) + .overwriteAiTags(true) + .overwriteCustomMetadata(true) + .overwriteFile(true) + .overwriteTags(true) + .publicKey("publicKey") + .responseFields( + listOf( + FileUploadParams.ResponseField.TAGS, + FileUploadParams.ResponseField.CUSTOM_COORDINATES, + FileUploadParams.ResponseField.IS_PRIVATE_FILE, + ) + ) + .signature("signature") + .tags(listOf("t-shirt", "round-neck", "men")) + .transformation( + FileUploadParams.Transformation.builder() + .addPost( + FileUploadParams.Transformation.Post.Thumbnail.builder() + .value("w-150,h-150") + .build() + ) + .addPost( + FileUploadParams.Transformation.Post.Abs.builder() + .protocol( + FileUploadParams.Transformation.Post.Abs.Protocol.DASH + ) + .value("sr-240_360_480_720_1080") + .build() + ) + .pre("w-300,h-300,q-80") + .build() + ) + .useUniqueFileName(true) + .webhookUrl("https://example.com") + .build() + ) + } + + assertThat(e.statusCode()).isEqualTo(403) + assertThat(e.headers().toMap()).contains(entry(HEADER_NAME, listOf(HEADER_VALUE))) + assertThat(e.body()).isEqualTo(ERROR_JSON) + } + + @Test + fun filesUpload403WithRawResponse() { + val fileService = client.files().withRawResponse() + stubFor( + post(anyUrl()) + .willReturn( + status(403).withHeader(HEADER_NAME, HEADER_VALUE).withBody(ERROR_JSON_BYTES) + ) + ) + + val e = + assertThrows { + fileService.upload( + FileUploadParams.builder() + .file("some content".byteInputStream()) + .fileName("fileName") + .token("token") + .checks("\"request.folder\" : \"marketing/\"\n") + .customCoordinates("customCoordinates") + .customMetadata( + FileUploadParams.CustomMetadata.builder() + .putAdditionalProperty("brand", JsonValue.from("bar")) + .putAdditionalProperty("color", JsonValue.from("bar")) + .build() + ) + .description("Running shoes") + .expire(0L) + .extensions( + listOf( + UnnamedSchemaWithArrayParent3.ofRemoveBg( + UnnamedSchemaWithArrayParent3.RemoveBg.builder() + .options( + UnnamedSchemaWithArrayParent3.RemoveBg.Options.builder() + .addShadow(true) + .bgColor("bg_color") + .bgImageUrl("bg_image_url") + .semitransparency(true) + .build() + ) + .build() + ), + UnnamedSchemaWithArrayParent3.ofAutoTaggingExtension( + UnnamedSchemaWithArrayParent3.AutoTaggingExtension.builder() + .maxTags(5L) + .minConfidence(95L) + .name( + UnnamedSchemaWithArrayParent3.AutoTaggingExtension.Name + .GOOGLE_AUTO_TAGGING + ) + .build() + ), + UnnamedSchemaWithArrayParent3.ofAiAutoDescription(), + ) + ) + .folder("folder") + .isPrivateFile(true) + .isPublished(true) + .overwriteAiTags(true) + .overwriteCustomMetadata(true) + .overwriteFile(true) + .overwriteTags(true) + .publicKey("publicKey") + .responseFields( + listOf( + FileUploadParams.ResponseField.TAGS, + FileUploadParams.ResponseField.CUSTOM_COORDINATES, + FileUploadParams.ResponseField.IS_PRIVATE_FILE, + ) + ) + .signature("signature") + .tags(listOf("t-shirt", "round-neck", "men")) + .transformation( + FileUploadParams.Transformation.builder() + .addPost( + FileUploadParams.Transformation.Post.Thumbnail.builder() + .value("w-150,h-150") + .build() + ) + .addPost( + FileUploadParams.Transformation.Post.Abs.builder() + .protocol( + FileUploadParams.Transformation.Post.Abs.Protocol.DASH + ) + .value("sr-240_360_480_720_1080") + .build() + ) + .pre("w-300,h-300,q-80") + .build() + ) + .useUniqueFileName(true) + .webhookUrl("https://example.com") + .build() + ) + } + + assertThat(e.statusCode()).isEqualTo(403) + assertThat(e.headers().toMap()).contains(entry(HEADER_NAME, listOf(HEADER_VALUE))) + assertThat(e.body()).isEqualTo(ERROR_JSON) + } + + @Test + fun filesUpload404() { + val fileService = client.files() + stubFor( + post(anyUrl()) + .willReturn( + status(404).withHeader(HEADER_NAME, HEADER_VALUE).withBody(ERROR_JSON_BYTES) + ) + ) + + val e = + assertThrows { + fileService.upload( + FileUploadParams.builder() + .file("some content".byteInputStream()) + .fileName("fileName") + .token("token") + .checks("\"request.folder\" : \"marketing/\"\n") + .customCoordinates("customCoordinates") + .customMetadata( + FileUploadParams.CustomMetadata.builder() + .putAdditionalProperty("brand", JsonValue.from("bar")) + .putAdditionalProperty("color", JsonValue.from("bar")) + .build() + ) + .description("Running shoes") + .expire(0L) + .extensions( + listOf( + UnnamedSchemaWithArrayParent3.ofRemoveBg( + UnnamedSchemaWithArrayParent3.RemoveBg.builder() + .options( + UnnamedSchemaWithArrayParent3.RemoveBg.Options.builder() + .addShadow(true) + .bgColor("bg_color") + .bgImageUrl("bg_image_url") + .semitransparency(true) + .build() + ) + .build() + ), + UnnamedSchemaWithArrayParent3.ofAutoTaggingExtension( + UnnamedSchemaWithArrayParent3.AutoTaggingExtension.builder() + .maxTags(5L) + .minConfidence(95L) + .name( + UnnamedSchemaWithArrayParent3.AutoTaggingExtension.Name + .GOOGLE_AUTO_TAGGING + ) + .build() + ), + UnnamedSchemaWithArrayParent3.ofAiAutoDescription(), + ) + ) + .folder("folder") + .isPrivateFile(true) + .isPublished(true) + .overwriteAiTags(true) + .overwriteCustomMetadata(true) + .overwriteFile(true) + .overwriteTags(true) + .publicKey("publicKey") + .responseFields( + listOf( + FileUploadParams.ResponseField.TAGS, + FileUploadParams.ResponseField.CUSTOM_COORDINATES, + FileUploadParams.ResponseField.IS_PRIVATE_FILE, + ) + ) + .signature("signature") + .tags(listOf("t-shirt", "round-neck", "men")) + .transformation( + FileUploadParams.Transformation.builder() + .addPost( + FileUploadParams.Transformation.Post.Thumbnail.builder() + .value("w-150,h-150") + .build() + ) + .addPost( + FileUploadParams.Transformation.Post.Abs.builder() + .protocol( + FileUploadParams.Transformation.Post.Abs.Protocol.DASH + ) + .value("sr-240_360_480_720_1080") + .build() + ) + .pre("w-300,h-300,q-80") + .build() + ) + .useUniqueFileName(true) + .webhookUrl("https://example.com") + .build() + ) + } + + assertThat(e.statusCode()).isEqualTo(404) + assertThat(e.headers().toMap()).contains(entry(HEADER_NAME, listOf(HEADER_VALUE))) + assertThat(e.body()).isEqualTo(ERROR_JSON) + } + + @Test + fun filesUpload404WithRawResponse() { + val fileService = client.files().withRawResponse() + stubFor( + post(anyUrl()) + .willReturn( + status(404).withHeader(HEADER_NAME, HEADER_VALUE).withBody(ERROR_JSON_BYTES) + ) + ) + + val e = + assertThrows { + fileService.upload( + FileUploadParams.builder() + .file("some content".byteInputStream()) + .fileName("fileName") + .token("token") + .checks("\"request.folder\" : \"marketing/\"\n") + .customCoordinates("customCoordinates") + .customMetadata( + FileUploadParams.CustomMetadata.builder() + .putAdditionalProperty("brand", JsonValue.from("bar")) + .putAdditionalProperty("color", JsonValue.from("bar")) + .build() + ) + .description("Running shoes") + .expire(0L) + .extensions( + listOf( + UnnamedSchemaWithArrayParent3.ofRemoveBg( + UnnamedSchemaWithArrayParent3.RemoveBg.builder() + .options( + UnnamedSchemaWithArrayParent3.RemoveBg.Options.builder() + .addShadow(true) + .bgColor("bg_color") + .bgImageUrl("bg_image_url") + .semitransparency(true) + .build() + ) + .build() + ), + UnnamedSchemaWithArrayParent3.ofAutoTaggingExtension( + UnnamedSchemaWithArrayParent3.AutoTaggingExtension.builder() + .maxTags(5L) + .minConfidence(95L) + .name( + UnnamedSchemaWithArrayParent3.AutoTaggingExtension.Name + .GOOGLE_AUTO_TAGGING + ) + .build() + ), + UnnamedSchemaWithArrayParent3.ofAiAutoDescription(), + ) + ) + .folder("folder") + .isPrivateFile(true) + .isPublished(true) + .overwriteAiTags(true) + .overwriteCustomMetadata(true) + .overwriteFile(true) + .overwriteTags(true) + .publicKey("publicKey") + .responseFields( + listOf( + FileUploadParams.ResponseField.TAGS, + FileUploadParams.ResponseField.CUSTOM_COORDINATES, + FileUploadParams.ResponseField.IS_PRIVATE_FILE, + ) + ) + .signature("signature") + .tags(listOf("t-shirt", "round-neck", "men")) + .transformation( + FileUploadParams.Transformation.builder() + .addPost( + FileUploadParams.Transformation.Post.Thumbnail.builder() + .value("w-150,h-150") + .build() + ) + .addPost( + FileUploadParams.Transformation.Post.Abs.builder() + .protocol( + FileUploadParams.Transformation.Post.Abs.Protocol.DASH + ) + .value("sr-240_360_480_720_1080") + .build() + ) + .pre("w-300,h-300,q-80") + .build() + ) + .useUniqueFileName(true) + .webhookUrl("https://example.com") + .build() + ) + } + + assertThat(e.statusCode()).isEqualTo(404) + assertThat(e.headers().toMap()).contains(entry(HEADER_NAME, listOf(HEADER_VALUE))) + assertThat(e.body()).isEqualTo(ERROR_JSON) + } + + @Test + fun filesUpload422() { + val fileService = client.files() + stubFor( + post(anyUrl()) + .willReturn( + status(422).withHeader(HEADER_NAME, HEADER_VALUE).withBody(ERROR_JSON_BYTES) + ) + ) + + val e = + assertThrows { + fileService.upload( + FileUploadParams.builder() + .file("some content".byteInputStream()) + .fileName("fileName") + .token("token") + .checks("\"request.folder\" : \"marketing/\"\n") + .customCoordinates("customCoordinates") + .customMetadata( + FileUploadParams.CustomMetadata.builder() + .putAdditionalProperty("brand", JsonValue.from("bar")) + .putAdditionalProperty("color", JsonValue.from("bar")) + .build() + ) + .description("Running shoes") + .expire(0L) + .extensions( + listOf( + UnnamedSchemaWithArrayParent3.ofRemoveBg( + UnnamedSchemaWithArrayParent3.RemoveBg.builder() + .options( + UnnamedSchemaWithArrayParent3.RemoveBg.Options.builder() + .addShadow(true) + .bgColor("bg_color") + .bgImageUrl("bg_image_url") + .semitransparency(true) + .build() + ) + .build() + ), + UnnamedSchemaWithArrayParent3.ofAutoTaggingExtension( + UnnamedSchemaWithArrayParent3.AutoTaggingExtension.builder() + .maxTags(5L) + .minConfidence(95L) + .name( + UnnamedSchemaWithArrayParent3.AutoTaggingExtension.Name + .GOOGLE_AUTO_TAGGING + ) + .build() + ), + UnnamedSchemaWithArrayParent3.ofAiAutoDescription(), + ) + ) + .folder("folder") + .isPrivateFile(true) + .isPublished(true) + .overwriteAiTags(true) + .overwriteCustomMetadata(true) + .overwriteFile(true) + .overwriteTags(true) + .publicKey("publicKey") + .responseFields( + listOf( + FileUploadParams.ResponseField.TAGS, + FileUploadParams.ResponseField.CUSTOM_COORDINATES, + FileUploadParams.ResponseField.IS_PRIVATE_FILE, + ) + ) + .signature("signature") + .tags(listOf("t-shirt", "round-neck", "men")) + .transformation( + FileUploadParams.Transformation.builder() + .addPost( + FileUploadParams.Transformation.Post.Thumbnail.builder() + .value("w-150,h-150") + .build() + ) + .addPost( + FileUploadParams.Transformation.Post.Abs.builder() + .protocol( + FileUploadParams.Transformation.Post.Abs.Protocol.DASH + ) + .value("sr-240_360_480_720_1080") + .build() + ) + .pre("w-300,h-300,q-80") + .build() + ) + .useUniqueFileName(true) + .webhookUrl("https://example.com") + .build() + ) + } + + assertThat(e.statusCode()).isEqualTo(422) + assertThat(e.headers().toMap()).contains(entry(HEADER_NAME, listOf(HEADER_VALUE))) + assertThat(e.body()).isEqualTo(ERROR_JSON) + } + + @Test + fun filesUpload422WithRawResponse() { + val fileService = client.files().withRawResponse() + stubFor( + post(anyUrl()) + .willReturn( + status(422).withHeader(HEADER_NAME, HEADER_VALUE).withBody(ERROR_JSON_BYTES) + ) + ) + + val e = + assertThrows { + fileService.upload( + FileUploadParams.builder() + .file("some content".byteInputStream()) + .fileName("fileName") + .token("token") + .checks("\"request.folder\" : \"marketing/\"\n") + .customCoordinates("customCoordinates") + .customMetadata( + FileUploadParams.CustomMetadata.builder() + .putAdditionalProperty("brand", JsonValue.from("bar")) + .putAdditionalProperty("color", JsonValue.from("bar")) + .build() + ) + .description("Running shoes") + .expire(0L) + .extensions( + listOf( + UnnamedSchemaWithArrayParent3.ofRemoveBg( + UnnamedSchemaWithArrayParent3.RemoveBg.builder() + .options( + UnnamedSchemaWithArrayParent3.RemoveBg.Options.builder() + .addShadow(true) + .bgColor("bg_color") + .bgImageUrl("bg_image_url") + .semitransparency(true) + .build() + ) + .build() + ), + UnnamedSchemaWithArrayParent3.ofAutoTaggingExtension( + UnnamedSchemaWithArrayParent3.AutoTaggingExtension.builder() + .maxTags(5L) + .minConfidence(95L) + .name( + UnnamedSchemaWithArrayParent3.AutoTaggingExtension.Name + .GOOGLE_AUTO_TAGGING + ) + .build() + ), + UnnamedSchemaWithArrayParent3.ofAiAutoDescription(), + ) + ) + .folder("folder") + .isPrivateFile(true) + .isPublished(true) + .overwriteAiTags(true) + .overwriteCustomMetadata(true) + .overwriteFile(true) + .overwriteTags(true) + .publicKey("publicKey") + .responseFields( + listOf( + FileUploadParams.ResponseField.TAGS, + FileUploadParams.ResponseField.CUSTOM_COORDINATES, + FileUploadParams.ResponseField.IS_PRIVATE_FILE, + ) + ) + .signature("signature") + .tags(listOf("t-shirt", "round-neck", "men")) + .transformation( + FileUploadParams.Transformation.builder() + .addPost( + FileUploadParams.Transformation.Post.Thumbnail.builder() + .value("w-150,h-150") + .build() + ) + .addPost( + FileUploadParams.Transformation.Post.Abs.builder() + .protocol( + FileUploadParams.Transformation.Post.Abs.Protocol.DASH + ) + .value("sr-240_360_480_720_1080") + .build() + ) + .pre("w-300,h-300,q-80") + .build() + ) + .useUniqueFileName(true) + .webhookUrl("https://example.com") + .build() + ) + } + + assertThat(e.statusCode()).isEqualTo(422) + assertThat(e.headers().toMap()).contains(entry(HEADER_NAME, listOf(HEADER_VALUE))) + assertThat(e.body()).isEqualTo(ERROR_JSON) + } + + @Test + fun filesUpload429() { + val fileService = client.files() + stubFor( + post(anyUrl()) + .willReturn( + status(429).withHeader(HEADER_NAME, HEADER_VALUE).withBody(ERROR_JSON_BYTES) + ) + ) + + val e = + assertThrows { + fileService.upload( + FileUploadParams.builder() + .file("some content".byteInputStream()) + .fileName("fileName") + .token("token") + .checks("\"request.folder\" : \"marketing/\"\n") + .customCoordinates("customCoordinates") + .customMetadata( + FileUploadParams.CustomMetadata.builder() + .putAdditionalProperty("brand", JsonValue.from("bar")) + .putAdditionalProperty("color", JsonValue.from("bar")) + .build() + ) + .description("Running shoes") + .expire(0L) + .extensions( + listOf( + UnnamedSchemaWithArrayParent3.ofRemoveBg( + UnnamedSchemaWithArrayParent3.RemoveBg.builder() + .options( + UnnamedSchemaWithArrayParent3.RemoveBg.Options.builder() + .addShadow(true) + .bgColor("bg_color") + .bgImageUrl("bg_image_url") + .semitransparency(true) + .build() + ) + .build() + ), + UnnamedSchemaWithArrayParent3.ofAutoTaggingExtension( + UnnamedSchemaWithArrayParent3.AutoTaggingExtension.builder() + .maxTags(5L) + .minConfidence(95L) + .name( + UnnamedSchemaWithArrayParent3.AutoTaggingExtension.Name + .GOOGLE_AUTO_TAGGING + ) + .build() + ), + UnnamedSchemaWithArrayParent3.ofAiAutoDescription(), + ) + ) + .folder("folder") + .isPrivateFile(true) + .isPublished(true) + .overwriteAiTags(true) + .overwriteCustomMetadata(true) + .overwriteFile(true) + .overwriteTags(true) + .publicKey("publicKey") + .responseFields( + listOf( + FileUploadParams.ResponseField.TAGS, + FileUploadParams.ResponseField.CUSTOM_COORDINATES, + FileUploadParams.ResponseField.IS_PRIVATE_FILE, + ) + ) + .signature("signature") + .tags(listOf("t-shirt", "round-neck", "men")) + .transformation( + FileUploadParams.Transformation.builder() + .addPost( + FileUploadParams.Transformation.Post.Thumbnail.builder() + .value("w-150,h-150") + .build() + ) + .addPost( + FileUploadParams.Transformation.Post.Abs.builder() + .protocol( + FileUploadParams.Transformation.Post.Abs.Protocol.DASH + ) + .value("sr-240_360_480_720_1080") + .build() + ) + .pre("w-300,h-300,q-80") + .build() + ) + .useUniqueFileName(true) + .webhookUrl("https://example.com") + .build() + ) + } + + assertThat(e.statusCode()).isEqualTo(429) + assertThat(e.headers().toMap()).contains(entry(HEADER_NAME, listOf(HEADER_VALUE))) + assertThat(e.body()).isEqualTo(ERROR_JSON) + } + + @Test + fun filesUpload429WithRawResponse() { + val fileService = client.files().withRawResponse() + stubFor( + post(anyUrl()) + .willReturn( + status(429).withHeader(HEADER_NAME, HEADER_VALUE).withBody(ERROR_JSON_BYTES) + ) + ) + + val e = + assertThrows { + fileService.upload( + FileUploadParams.builder() + .file("some content".byteInputStream()) + .fileName("fileName") + .token("token") + .checks("\"request.folder\" : \"marketing/\"\n") + .customCoordinates("customCoordinates") + .customMetadata( + FileUploadParams.CustomMetadata.builder() + .putAdditionalProperty("brand", JsonValue.from("bar")) + .putAdditionalProperty("color", JsonValue.from("bar")) + .build() + ) + .description("Running shoes") + .expire(0L) + .extensions( + listOf( + UnnamedSchemaWithArrayParent3.ofRemoveBg( + UnnamedSchemaWithArrayParent3.RemoveBg.builder() + .options( + UnnamedSchemaWithArrayParent3.RemoveBg.Options.builder() + .addShadow(true) + .bgColor("bg_color") + .bgImageUrl("bg_image_url") + .semitransparency(true) + .build() + ) + .build() + ), + UnnamedSchemaWithArrayParent3.ofAutoTaggingExtension( + UnnamedSchemaWithArrayParent3.AutoTaggingExtension.builder() + .maxTags(5L) + .minConfidence(95L) + .name( + UnnamedSchemaWithArrayParent3.AutoTaggingExtension.Name + .GOOGLE_AUTO_TAGGING + ) + .build() + ), + UnnamedSchemaWithArrayParent3.ofAiAutoDescription(), + ) + ) + .folder("folder") + .isPrivateFile(true) + .isPublished(true) + .overwriteAiTags(true) + .overwriteCustomMetadata(true) + .overwriteFile(true) + .overwriteTags(true) + .publicKey("publicKey") + .responseFields( + listOf( + FileUploadParams.ResponseField.TAGS, + FileUploadParams.ResponseField.CUSTOM_COORDINATES, + FileUploadParams.ResponseField.IS_PRIVATE_FILE, + ) + ) + .signature("signature") + .tags(listOf("t-shirt", "round-neck", "men")) + .transformation( + FileUploadParams.Transformation.builder() + .addPost( + FileUploadParams.Transformation.Post.Thumbnail.builder() + .value("w-150,h-150") + .build() + ) + .addPost( + FileUploadParams.Transformation.Post.Abs.builder() + .protocol( + FileUploadParams.Transformation.Post.Abs.Protocol.DASH + ) + .value("sr-240_360_480_720_1080") + .build() + ) + .pre("w-300,h-300,q-80") + .build() + ) + .useUniqueFileName(true) + .webhookUrl("https://example.com") + .build() + ) + } + + assertThat(e.statusCode()).isEqualTo(429) + assertThat(e.headers().toMap()).contains(entry(HEADER_NAME, listOf(HEADER_VALUE))) + assertThat(e.body()).isEqualTo(ERROR_JSON) + } + + @Test + fun filesUpload500() { + val fileService = client.files() + stubFor( + post(anyUrl()) + .willReturn( + status(500).withHeader(HEADER_NAME, HEADER_VALUE).withBody(ERROR_JSON_BYTES) + ) + ) + + val e = + assertThrows { + fileService.upload( + FileUploadParams.builder() + .file("some content".byteInputStream()) + .fileName("fileName") + .token("token") + .checks("\"request.folder\" : \"marketing/\"\n") + .customCoordinates("customCoordinates") + .customMetadata( + FileUploadParams.CustomMetadata.builder() + .putAdditionalProperty("brand", JsonValue.from("bar")) + .putAdditionalProperty("color", JsonValue.from("bar")) + .build() + ) + .description("Running shoes") + .expire(0L) + .extensions( + listOf( + UnnamedSchemaWithArrayParent3.ofRemoveBg( + UnnamedSchemaWithArrayParent3.RemoveBg.builder() + .options( + UnnamedSchemaWithArrayParent3.RemoveBg.Options.builder() + .addShadow(true) + .bgColor("bg_color") + .bgImageUrl("bg_image_url") + .semitransparency(true) + .build() + ) + .build() + ), + UnnamedSchemaWithArrayParent3.ofAutoTaggingExtension( + UnnamedSchemaWithArrayParent3.AutoTaggingExtension.builder() + .maxTags(5L) + .minConfidence(95L) + .name( + UnnamedSchemaWithArrayParent3.AutoTaggingExtension.Name + .GOOGLE_AUTO_TAGGING + ) + .build() + ), + UnnamedSchemaWithArrayParent3.ofAiAutoDescription(), + ) + ) + .folder("folder") + .isPrivateFile(true) + .isPublished(true) + .overwriteAiTags(true) + .overwriteCustomMetadata(true) + .overwriteFile(true) + .overwriteTags(true) + .publicKey("publicKey") + .responseFields( + listOf( + FileUploadParams.ResponseField.TAGS, + FileUploadParams.ResponseField.CUSTOM_COORDINATES, + FileUploadParams.ResponseField.IS_PRIVATE_FILE, + ) + ) + .signature("signature") + .tags(listOf("t-shirt", "round-neck", "men")) + .transformation( + FileUploadParams.Transformation.builder() + .addPost( + FileUploadParams.Transformation.Post.Thumbnail.builder() + .value("w-150,h-150") + .build() + ) + .addPost( + FileUploadParams.Transformation.Post.Abs.builder() + .protocol( + FileUploadParams.Transformation.Post.Abs.Protocol.DASH + ) + .value("sr-240_360_480_720_1080") + .build() + ) + .pre("w-300,h-300,q-80") + .build() + ) + .useUniqueFileName(true) + .webhookUrl("https://example.com") + .build() + ) + } + + assertThat(e.statusCode()).isEqualTo(500) + assertThat(e.headers().toMap()).contains(entry(HEADER_NAME, listOf(HEADER_VALUE))) + assertThat(e.body()).isEqualTo(ERROR_JSON) + } + + @Test + fun filesUpload500WithRawResponse() { + val fileService = client.files().withRawResponse() + stubFor( + post(anyUrl()) + .willReturn( + status(500).withHeader(HEADER_NAME, HEADER_VALUE).withBody(ERROR_JSON_BYTES) + ) + ) + + val e = + assertThrows { + fileService.upload( + FileUploadParams.builder() + .file("some content".byteInputStream()) + .fileName("fileName") + .token("token") + .checks("\"request.folder\" : \"marketing/\"\n") + .customCoordinates("customCoordinates") + .customMetadata( + FileUploadParams.CustomMetadata.builder() + .putAdditionalProperty("brand", JsonValue.from("bar")) + .putAdditionalProperty("color", JsonValue.from("bar")) + .build() + ) + .description("Running shoes") + .expire(0L) + .extensions( + listOf( + UnnamedSchemaWithArrayParent3.ofRemoveBg( + UnnamedSchemaWithArrayParent3.RemoveBg.builder() + .options( + UnnamedSchemaWithArrayParent3.RemoveBg.Options.builder() + .addShadow(true) + .bgColor("bg_color") + .bgImageUrl("bg_image_url") + .semitransparency(true) + .build() + ) + .build() + ), + UnnamedSchemaWithArrayParent3.ofAutoTaggingExtension( + UnnamedSchemaWithArrayParent3.AutoTaggingExtension.builder() + .maxTags(5L) + .minConfidence(95L) + .name( + UnnamedSchemaWithArrayParent3.AutoTaggingExtension.Name + .GOOGLE_AUTO_TAGGING + ) + .build() + ), + UnnamedSchemaWithArrayParent3.ofAiAutoDescription(), + ) + ) + .folder("folder") + .isPrivateFile(true) + .isPublished(true) + .overwriteAiTags(true) + .overwriteCustomMetadata(true) + .overwriteFile(true) + .overwriteTags(true) + .publicKey("publicKey") + .responseFields( + listOf( + FileUploadParams.ResponseField.TAGS, + FileUploadParams.ResponseField.CUSTOM_COORDINATES, + FileUploadParams.ResponseField.IS_PRIVATE_FILE, + ) + ) + .signature("signature") + .tags(listOf("t-shirt", "round-neck", "men")) + .transformation( + FileUploadParams.Transformation.builder() + .addPost( + FileUploadParams.Transformation.Post.Thumbnail.builder() + .value("w-150,h-150") + .build() + ) + .addPost( + FileUploadParams.Transformation.Post.Abs.builder() + .protocol( + FileUploadParams.Transformation.Post.Abs.Protocol.DASH + ) + .value("sr-240_360_480_720_1080") + .build() + ) + .pre("w-300,h-300,q-80") + .build() + ) + .useUniqueFileName(true) + .webhookUrl("https://example.com") + .build() + ) + } + + assertThat(e.statusCode()).isEqualTo(500) + assertThat(e.headers().toMap()).contains(entry(HEADER_NAME, listOf(HEADER_VALUE))) + assertThat(e.body()).isEqualTo(ERROR_JSON) + } + + @Test + fun filesUpload999() { + val fileService = client.files() + stubFor( + post(anyUrl()) + .willReturn( + status(999).withHeader(HEADER_NAME, HEADER_VALUE).withBody(ERROR_JSON_BYTES) + ) + ) + + val e = + assertThrows { + fileService.upload( + FileUploadParams.builder() + .file("some content".byteInputStream()) + .fileName("fileName") + .token("token") + .checks("\"request.folder\" : \"marketing/\"\n") + .customCoordinates("customCoordinates") + .customMetadata( + FileUploadParams.CustomMetadata.builder() + .putAdditionalProperty("brand", JsonValue.from("bar")) + .putAdditionalProperty("color", JsonValue.from("bar")) + .build() + ) + .description("Running shoes") + .expire(0L) + .extensions( + listOf( + UnnamedSchemaWithArrayParent3.ofRemoveBg( + UnnamedSchemaWithArrayParent3.RemoveBg.builder() + .options( + UnnamedSchemaWithArrayParent3.RemoveBg.Options.builder() + .addShadow(true) + .bgColor("bg_color") + .bgImageUrl("bg_image_url") + .semitransparency(true) + .build() + ) + .build() + ), + UnnamedSchemaWithArrayParent3.ofAutoTaggingExtension( + UnnamedSchemaWithArrayParent3.AutoTaggingExtension.builder() + .maxTags(5L) + .minConfidence(95L) + .name( + UnnamedSchemaWithArrayParent3.AutoTaggingExtension.Name + .GOOGLE_AUTO_TAGGING + ) + .build() + ), + UnnamedSchemaWithArrayParent3.ofAiAutoDescription(), + ) + ) + .folder("folder") + .isPrivateFile(true) + .isPublished(true) + .overwriteAiTags(true) + .overwriteCustomMetadata(true) + .overwriteFile(true) + .overwriteTags(true) + .publicKey("publicKey") + .responseFields( + listOf( + FileUploadParams.ResponseField.TAGS, + FileUploadParams.ResponseField.CUSTOM_COORDINATES, + FileUploadParams.ResponseField.IS_PRIVATE_FILE, + ) + ) + .signature("signature") + .tags(listOf("t-shirt", "round-neck", "men")) + .transformation( + FileUploadParams.Transformation.builder() + .addPost( + FileUploadParams.Transformation.Post.Thumbnail.builder() + .value("w-150,h-150") + .build() + ) + .addPost( + FileUploadParams.Transformation.Post.Abs.builder() + .protocol( + FileUploadParams.Transformation.Post.Abs.Protocol.DASH + ) + .value("sr-240_360_480_720_1080") + .build() + ) + .pre("w-300,h-300,q-80") + .build() + ) + .useUniqueFileName(true) + .webhookUrl("https://example.com") + .build() + ) + } + + assertThat(e.statusCode()).isEqualTo(999) + assertThat(e.headers().toMap()).contains(entry(HEADER_NAME, listOf(HEADER_VALUE))) + assertThat(e.body()).isEqualTo(ERROR_JSON) + } + + @Test + fun filesUpload999WithRawResponse() { + val fileService = client.files().withRawResponse() + stubFor( + post(anyUrl()) + .willReturn( + status(999).withHeader(HEADER_NAME, HEADER_VALUE).withBody(ERROR_JSON_BYTES) + ) + ) + + val e = + assertThrows { + fileService.upload( + FileUploadParams.builder() + .file("some content".byteInputStream()) + .fileName("fileName") + .token("token") + .checks("\"request.folder\" : \"marketing/\"\n") + .customCoordinates("customCoordinates") + .customMetadata( + FileUploadParams.CustomMetadata.builder() + .putAdditionalProperty("brand", JsonValue.from("bar")) + .putAdditionalProperty("color", JsonValue.from("bar")) + .build() + ) + .description("Running shoes") + .expire(0L) + .extensions( + listOf( + UnnamedSchemaWithArrayParent3.ofRemoveBg( + UnnamedSchemaWithArrayParent3.RemoveBg.builder() + .options( + UnnamedSchemaWithArrayParent3.RemoveBg.Options.builder() + .addShadow(true) + .bgColor("bg_color") + .bgImageUrl("bg_image_url") + .semitransparency(true) + .build() + ) + .build() + ), + UnnamedSchemaWithArrayParent3.ofAutoTaggingExtension( + UnnamedSchemaWithArrayParent3.AutoTaggingExtension.builder() + .maxTags(5L) + .minConfidence(95L) + .name( + UnnamedSchemaWithArrayParent3.AutoTaggingExtension.Name + .GOOGLE_AUTO_TAGGING + ) + .build() + ), + UnnamedSchemaWithArrayParent3.ofAiAutoDescription(), + ) + ) + .folder("folder") + .isPrivateFile(true) + .isPublished(true) + .overwriteAiTags(true) + .overwriteCustomMetadata(true) + .overwriteFile(true) + .overwriteTags(true) + .publicKey("publicKey") + .responseFields( + listOf( + FileUploadParams.ResponseField.TAGS, + FileUploadParams.ResponseField.CUSTOM_COORDINATES, + FileUploadParams.ResponseField.IS_PRIVATE_FILE, + ) + ) + .signature("signature") + .tags(listOf("t-shirt", "round-neck", "men")) + .transformation( + FileUploadParams.Transformation.builder() + .addPost( + FileUploadParams.Transformation.Post.Thumbnail.builder() + .value("w-150,h-150") + .build() + ) + .addPost( + FileUploadParams.Transformation.Post.Abs.builder() + .protocol( + FileUploadParams.Transformation.Post.Abs.Protocol.DASH + ) + .value("sr-240_360_480_720_1080") + .build() + ) + .pre("w-300,h-300,q-80") + .build() + ) + .useUniqueFileName(true) + .webhookUrl("https://example.com") + .build() + ) + } + + assertThat(e.statusCode()).isEqualTo(999) + assertThat(e.headers().toMap()).contains(entry(HEADER_NAME, listOf(HEADER_VALUE))) + assertThat(e.body()).isEqualTo(ERROR_JSON) + } + + @Test + fun filesUploadInvalidJsonBody() { + val fileService = client.files() + stubFor( + post(anyUrl()) + .willReturn(status(200).withHeader(HEADER_NAME, HEADER_VALUE).withBody(NOT_JSON)) + ) + + val e = + assertThrows { + fileService.upload( + FileUploadParams.builder() + .file("some content".byteInputStream()) + .fileName("fileName") + .token("token") + .checks("\"request.folder\" : \"marketing/\"\n") + .customCoordinates("customCoordinates") + .customMetadata( + FileUploadParams.CustomMetadata.builder() + .putAdditionalProperty("brand", JsonValue.from("bar")) + .putAdditionalProperty("color", JsonValue.from("bar")) + .build() + ) + .description("Running shoes") + .expire(0L) + .extensions( + listOf( + UnnamedSchemaWithArrayParent3.ofRemoveBg( + UnnamedSchemaWithArrayParent3.RemoveBg.builder() + .options( + UnnamedSchemaWithArrayParent3.RemoveBg.Options.builder() + .addShadow(true) + .bgColor("bg_color") + .bgImageUrl("bg_image_url") + .semitransparency(true) + .build() + ) + .build() + ), + UnnamedSchemaWithArrayParent3.ofAutoTaggingExtension( + UnnamedSchemaWithArrayParent3.AutoTaggingExtension.builder() + .maxTags(5L) + .minConfidence(95L) + .name( + UnnamedSchemaWithArrayParent3.AutoTaggingExtension.Name + .GOOGLE_AUTO_TAGGING + ) + .build() + ), + UnnamedSchemaWithArrayParent3.ofAiAutoDescription(), + ) + ) + .folder("folder") + .isPrivateFile(true) + .isPublished(true) + .overwriteAiTags(true) + .overwriteCustomMetadata(true) + .overwriteFile(true) + .overwriteTags(true) + .publicKey("publicKey") + .responseFields( + listOf( + FileUploadParams.ResponseField.TAGS, + FileUploadParams.ResponseField.CUSTOM_COORDINATES, + FileUploadParams.ResponseField.IS_PRIVATE_FILE, + ) + ) + .signature("signature") + .tags(listOf("t-shirt", "round-neck", "men")) + .transformation( + FileUploadParams.Transformation.builder() + .addPost( + FileUploadParams.Transformation.Post.Thumbnail.builder() + .value("w-150,h-150") + .build() + ) + .addPost( + FileUploadParams.Transformation.Post.Abs.builder() + .protocol( + FileUploadParams.Transformation.Post.Abs.Protocol.DASH + ) + .value("sr-240_360_480_720_1080") + .build() + ) + .pre("w-300,h-300,q-80") + .build() + ) + .useUniqueFileName(true) + .webhookUrl("https://example.com") + .build() + ) + } + + assertThat(e).hasMessage("Error reading response") + } + + private fun Headers.toMap(): Map> = + mutableMapOf>().also { map -> + names().forEach { map[it] = values(it) } + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/services/ServiceParamsTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/services/ServiceParamsTest.kt new file mode 100644 index 0000000..b6f83f9 --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/services/ServiceParamsTest.kt @@ -0,0 +1,137 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services + +import com.github.tomakehurst.wiremock.client.WireMock.anyUrl +import com.github.tomakehurst.wiremock.client.WireMock.equalTo +import com.github.tomakehurst.wiremock.client.WireMock.matchingJsonPath +import com.github.tomakehurst.wiremock.client.WireMock.ok +import com.github.tomakehurst.wiremock.client.WireMock.post +import com.github.tomakehurst.wiremock.client.WireMock.postRequestedFor +import com.github.tomakehurst.wiremock.client.WireMock.stubFor +import com.github.tomakehurst.wiremock.client.WireMock.verify +import com.github.tomakehurst.wiremock.junit5.WireMockRuntimeInfo +import com.github.tomakehurst.wiremock.junit5.WireMockTest +import com.imagekit.api.client.ImageKitClient +import com.imagekit.api.client.okhttp.ImageKitOkHttpClient +import com.imagekit.api.core.JsonValue +import com.imagekit.api.models.UnnamedSchemaWithArrayParent3 +import com.imagekit.api.models.files.FileUploadParams +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Disabled +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.parallel.ResourceLock + +@WireMockTest +@ResourceLock("https://github.com/wiremock/wiremock/issues/169") +internal class ServiceParamsTest { + + private lateinit var client: ImageKitClient + + @BeforeEach + fun beforeEach(wmRuntimeInfo: WireMockRuntimeInfo) { + client = + ImageKitOkHttpClient.builder() + .baseUrl(wmRuntimeInfo.httpBaseUrl) + .privateApiKey("My Private API Key") + .password("My Password") + .build() + } + + @Disabled("Prism tests are disabled") + @Test + fun upload() { + val fileService = client.files() + stubFor(post(anyUrl()).willReturn(ok("{}"))) + + fileService.upload( + FileUploadParams.builder() + .file("some content".byteInputStream()) + .fileName("fileName") + .token("token") + .checks("\"request.folder\" : \"marketing/\"\n") + .customCoordinates("customCoordinates") + .customMetadata( + FileUploadParams.CustomMetadata.builder() + .putAdditionalProperty("brand", JsonValue.from("bar")) + .putAdditionalProperty("color", JsonValue.from("bar")) + .build() + ) + .description("Running shoes") + .expire(0L) + .extensions( + listOf( + UnnamedSchemaWithArrayParent3.ofRemoveBg( + UnnamedSchemaWithArrayParent3.RemoveBg.builder() + .options( + UnnamedSchemaWithArrayParent3.RemoveBg.Options.builder() + .addShadow(true) + .bgColor("bg_color") + .bgImageUrl("bg_image_url") + .semitransparency(true) + .build() + ) + .build() + ), + UnnamedSchemaWithArrayParent3.ofAutoTaggingExtension( + UnnamedSchemaWithArrayParent3.AutoTaggingExtension.builder() + .maxTags(5L) + .minConfidence(95L) + .name( + UnnamedSchemaWithArrayParent3.AutoTaggingExtension.Name + .GOOGLE_AUTO_TAGGING + ) + .build() + ), + UnnamedSchemaWithArrayParent3.ofAiAutoDescription(), + ) + ) + .folder("folder") + .isPrivateFile(true) + .isPublished(true) + .overwriteAiTags(true) + .overwriteCustomMetadata(true) + .overwriteFile(true) + .overwriteTags(true) + .publicKey("publicKey") + .responseFields( + listOf( + FileUploadParams.ResponseField.TAGS, + FileUploadParams.ResponseField.CUSTOM_COORDINATES, + FileUploadParams.ResponseField.IS_PRIVATE_FILE, + ) + ) + .signature("signature") + .tags(listOf("t-shirt", "round-neck", "men")) + .transformation( + FileUploadParams.Transformation.builder() + .addPost( + FileUploadParams.Transformation.Post.Thumbnail.builder() + .value("w-150,h-150") + .build() + ) + .addPost( + FileUploadParams.Transformation.Post.Abs.builder() + .protocol(FileUploadParams.Transformation.Post.Abs.Protocol.DASH) + .value("sr-240_360_480_720_1080") + .build() + ) + .pre("w-300,h-300,q-80") + .build() + ) + .useUniqueFileName(true) + .webhookUrl("https://example.com") + .putAdditionalHeader("Secret-Header", "42") + .putAdditionalQueryParam("secret_query_param", "42") + .putAdditionalBodyProperty("secretProperty", JsonValue.from("42")) + .build() + ) + + verify( + postRequestedFor(anyUrl()) + .withHeader("Secret-Header", equalTo("42")) + .withQueryParam("secret_query_param", equalTo("42")) + .withRequestBody(matchingJsonPath("$.secretProperty", equalTo("42"))) + ) + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/services/async/AssetServiceAsyncTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/services/async/AssetServiceAsyncTest.kt new file mode 100644 index 0000000..322f6ce --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/services/async/AssetServiceAsyncTest.kt @@ -0,0 +1,42 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.async + +import com.imagekit.api.TestServerExtension +import com.imagekit.api.client.okhttp.ImageKitOkHttpClientAsync +import com.imagekit.api.models.assets.AssetListParams +import org.junit.jupiter.api.Disabled +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith + +@ExtendWith(TestServerExtension::class) +internal class AssetServiceAsyncTest { + + @Disabled("Prism tests are disabled") + @Test + fun list() { + val client = + ImageKitOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .privateApiKey("My Private API Key") + .password("My Password") + .build() + val assetServiceAsync = client.assets() + + val assetsFuture = + assetServiceAsync.list( + AssetListParams.builder() + .fileType(AssetListParams.FileType.ALL) + .limit(1L) + .path("path") + .searchQuery("searchQuery") + .skip(0L) + .sort(AssetListParams.Sort.ASC_NAME) + .type(AssetListParams.Type.FILE) + .build() + ) + + val assets = assetsFuture.get() + assets.forEach { it.validate() } + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/services/async/CustomMetadataFieldServiceAsyncTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/services/async/CustomMetadataFieldServiceAsyncTest.kt new file mode 100644 index 0000000..bb8af98 --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/services/async/CustomMetadataFieldServiceAsyncTest.kt @@ -0,0 +1,160 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.async + +import com.imagekit.api.TestServerExtension +import com.imagekit.api.client.okhttp.ImageKitOkHttpClientAsync +import com.imagekit.api.models.custommetadatafields.CustomMetadataFieldCreateParams +import com.imagekit.api.models.custommetadatafields.CustomMetadataFieldListParams +import com.imagekit.api.models.custommetadatafields.CustomMetadataFieldUpdateParams +import org.junit.jupiter.api.Disabled +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith + +@ExtendWith(TestServerExtension::class) +internal class CustomMetadataFieldServiceAsyncTest { + + @Disabled("Prism tests are disabled") + @Test + fun create() { + val client = + ImageKitOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .privateApiKey("My Private API Key") + .password("My Password") + .build() + val customMetadataFieldServiceAsync = client.customMetadataFields() + + val customMetadataFieldFuture = + customMetadataFieldServiceAsync.create( + CustomMetadataFieldCreateParams.builder() + .label("price") + .name("price") + .schema( + CustomMetadataFieldCreateParams.Schema.builder() + .type(CustomMetadataFieldCreateParams.Schema.Type.NUMBER) + .defaultValue("string") + .isValueRequired(true) + .maxLength(0.0) + .maxValue(3000.0) + .minLength(0.0) + .minValue(1000.0) + .selectOptions( + listOf( + CustomMetadataFieldCreateParams.Schema.SelectOption.ofString( + "small" + ), + CustomMetadataFieldCreateParams.Schema.SelectOption.ofString( + "medium" + ), + CustomMetadataFieldCreateParams.Schema.SelectOption.ofString( + "large" + ), + CustomMetadataFieldCreateParams.Schema.SelectOption.ofNumber( + 30.0 + ), + CustomMetadataFieldCreateParams.Schema.SelectOption.ofNumber( + 40.0 + ), + CustomMetadataFieldCreateParams.Schema.SelectOption.ofBool(true), + ) + ) + .build() + ) + .build() + ) + + val customMetadataField = customMetadataFieldFuture.get() + customMetadataField.validate() + } + + @Disabled("Prism tests are disabled") + @Test + fun update() { + val client = + ImageKitOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .privateApiKey("My Private API Key") + .password("My Password") + .build() + val customMetadataFieldServiceAsync = client.customMetadataFields() + + val customMetadataFieldFuture = + customMetadataFieldServiceAsync.update( + CustomMetadataFieldUpdateParams.builder() + .id("id") + .label("price") + .schema( + CustomMetadataFieldUpdateParams.Schema.builder() + .defaultValue("string") + .isValueRequired(true) + .maxLength(0.0) + .maxValue(3000.0) + .minLength(0.0) + .minValue(1000.0) + .selectOptions( + listOf( + CustomMetadataFieldUpdateParams.Schema.SelectOption.ofString( + "small" + ), + CustomMetadataFieldUpdateParams.Schema.SelectOption.ofString( + "medium" + ), + CustomMetadataFieldUpdateParams.Schema.SelectOption.ofString( + "large" + ), + CustomMetadataFieldUpdateParams.Schema.SelectOption.ofNumber( + 30.0 + ), + CustomMetadataFieldUpdateParams.Schema.SelectOption.ofNumber( + 40.0 + ), + CustomMetadataFieldUpdateParams.Schema.SelectOption.ofBool(true), + ) + ) + .build() + ) + .build() + ) + + val customMetadataField = customMetadataFieldFuture.get() + customMetadataField.validate() + } + + @Disabled("Prism tests are disabled") + @Test + fun list() { + val client = + ImageKitOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .privateApiKey("My Private API Key") + .password("My Password") + .build() + val customMetadataFieldServiceAsync = client.customMetadataFields() + + val customMetadataFieldsFuture = + customMetadataFieldServiceAsync.list( + CustomMetadataFieldListParams.builder().includeDeleted(true).build() + ) + + val customMetadataFields = customMetadataFieldsFuture.get() + customMetadataFields.forEach { it.validate() } + } + + @Disabled("Prism tests are disabled") + @Test + fun delete() { + val client = + ImageKitOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .privateApiKey("My Private API Key") + .password("My Password") + .build() + val customMetadataFieldServiceAsync = client.customMetadataFields() + + val customMetadataFieldFuture = customMetadataFieldServiceAsync.delete("id") + + val customMetadataField = customMetadataFieldFuture.get() + customMetadataField.validate() + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/services/async/FileServiceAsyncTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/services/async/FileServiceAsyncTest.kt new file mode 100644 index 0000000..971b081 --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/services/async/FileServiceAsyncTest.kt @@ -0,0 +1,300 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.async + +import com.imagekit.api.TestServerExtension +import com.imagekit.api.client.okhttp.ImageKitOkHttpClientAsync +import com.imagekit.api.core.JsonValue +import com.imagekit.api.models.UnnamedSchemaWithArrayParent3 +import com.imagekit.api.models.files.FileCopyParams +import com.imagekit.api.models.files.FileMoveParams +import com.imagekit.api.models.files.FileRenameParams +import com.imagekit.api.models.files.FileUpdateParams +import com.imagekit.api.models.files.FileUploadParams +import org.junit.jupiter.api.Disabled +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith + +@ExtendWith(TestServerExtension::class) +internal class FileServiceAsyncTest { + + @Disabled("Prism tests are disabled") + @Test + fun update() { + val client = + ImageKitOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .privateApiKey("My Private API Key") + .password("My Password") + .build() + val fileServiceAsync = client.files() + + val fileFuture = + fileServiceAsync.update( + FileUpdateParams.builder() + .fileId("fileId") + .body( + FileUpdateParams.Body.UpdateFileDetails.builder() + .customCoordinates("10,10,100,100") + .customMetadata( + FileUpdateParams.Body.UpdateFileDetails.CustomMetadata.builder() + .putAdditionalProperty("brand", JsonValue.from("bar")) + .putAdditionalProperty("color", JsonValue.from("bar")) + .build() + ) + .description("description") + .extensions( + listOf( + UnnamedSchemaWithArrayParent3.ofRemoveBg( + UnnamedSchemaWithArrayParent3.RemoveBg.builder() + .options( + UnnamedSchemaWithArrayParent3.RemoveBg.Options + .builder() + .addShadow(true) + .bgColor("bg_color") + .bgImageUrl("bg_image_url") + .semitransparency(true) + .build() + ) + .build() + ), + UnnamedSchemaWithArrayParent3.ofAutoTaggingExtension( + UnnamedSchemaWithArrayParent3.AutoTaggingExtension.builder() + .maxTags(10L) + .minConfidence(80L) + .name( + UnnamedSchemaWithArrayParent3.AutoTaggingExtension + .Name + .GOOGLE_AUTO_TAGGING + ) + .build() + ), + UnnamedSchemaWithArrayParent3.ofAutoTaggingExtension( + UnnamedSchemaWithArrayParent3.AutoTaggingExtension.builder() + .maxTags(10L) + .minConfidence(80L) + .name( + UnnamedSchemaWithArrayParent3.AutoTaggingExtension + .Name + .AWS_AUTO_TAGGING + ) + .build() + ), + UnnamedSchemaWithArrayParent3.ofAiAutoDescription(), + ) + ) + .removeAiTagsOfStrings(listOf("car", "vehicle", "motorsports")) + .addTag("tag1") + .addTag("tag2") + .webhookUrl("https://webhook.site/0d6b6c7a-8e5a-4b3a-8b7c-0d6b6c7a8e5a") + .build() + ) + .build() + ) + + val file = fileFuture.get() + file.validate() + } + + @Disabled("Prism tests are disabled") + @Test + fun delete() { + val client = + ImageKitOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .privateApiKey("My Private API Key") + .password("My Password") + .build() + val fileServiceAsync = client.files() + + val future = fileServiceAsync.delete("fileId") + + val response = future.get() + } + + @Disabled("Prism tests are disabled") + @Test + fun copy() { + val client = + ImageKitOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .privateApiKey("My Private API Key") + .password("My Password") + .build() + val fileServiceAsync = client.files() + + val responseFuture = + fileServiceAsync.copy( + FileCopyParams.builder() + .destinationPath("/folder/to/copy/into/") + .sourceFilePath("/path/to/file.jpg") + .includeFileVersions(false) + .build() + ) + + val response = responseFuture.get() + response.validate() + } + + @Disabled("Prism tests are disabled") + @Test + fun get() { + val client = + ImageKitOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .privateApiKey("My Private API Key") + .password("My Password") + .build() + val fileServiceAsync = client.files() + + val fileFuture = fileServiceAsync.get("fileId") + + val file = fileFuture.get() + file.validate() + } + + @Disabled("Prism tests are disabled") + @Test + fun move() { + val client = + ImageKitOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .privateApiKey("My Private API Key") + .password("My Password") + .build() + val fileServiceAsync = client.files() + + val responseFuture = + fileServiceAsync.move( + FileMoveParams.builder() + .destinationPath("/folder/to/move/into/") + .sourceFilePath("/path/to/file.jpg") + .build() + ) + + val response = responseFuture.get() + response.validate() + } + + @Disabled("Prism tests are disabled") + @Test + fun rename() { + val client = + ImageKitOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .privateApiKey("My Private API Key") + .password("My Password") + .build() + val fileServiceAsync = client.files() + + val responseFuture = + fileServiceAsync.rename( + FileRenameParams.builder() + .filePath("/path/to/file.jpg") + .newFileName("newFileName.jpg") + .purgeCache(true) + .build() + ) + + val response = responseFuture.get() + response.validate() + } + + @Disabled("Prism tests are disabled") + @Test + fun upload() { + val client = + ImageKitOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .privateApiKey("My Private API Key") + .password("My Password") + .build() + val fileServiceAsync = client.files() + + val responseFuture = + fileServiceAsync.upload( + FileUploadParams.builder() + .file("some content".byteInputStream()) + .fileName("fileName") + .token("token") + .checks("\"request.folder\" : \"marketing/\"\n") + .customCoordinates("customCoordinates") + .customMetadata( + FileUploadParams.CustomMetadata.builder() + .putAdditionalProperty("brand", JsonValue.from("bar")) + .putAdditionalProperty("color", JsonValue.from("bar")) + .build() + ) + .description("Running shoes") + .expire(0L) + .extensions( + listOf( + UnnamedSchemaWithArrayParent3.ofRemoveBg( + UnnamedSchemaWithArrayParent3.RemoveBg.builder() + .options( + UnnamedSchemaWithArrayParent3.RemoveBg.Options.builder() + .addShadow(true) + .bgColor("bg_color") + .bgImageUrl("bg_image_url") + .semitransparency(true) + .build() + ) + .build() + ), + UnnamedSchemaWithArrayParent3.ofAutoTaggingExtension( + UnnamedSchemaWithArrayParent3.AutoTaggingExtension.builder() + .maxTags(5L) + .minConfidence(95L) + .name( + UnnamedSchemaWithArrayParent3.AutoTaggingExtension.Name + .GOOGLE_AUTO_TAGGING + ) + .build() + ), + UnnamedSchemaWithArrayParent3.ofAiAutoDescription(), + ) + ) + .folder("folder") + .isPrivateFile(true) + .isPublished(true) + .overwriteAiTags(true) + .overwriteCustomMetadata(true) + .overwriteFile(true) + .overwriteTags(true) + .publicKey("publicKey") + .responseFields( + listOf( + FileUploadParams.ResponseField.TAGS, + FileUploadParams.ResponseField.CUSTOM_COORDINATES, + FileUploadParams.ResponseField.IS_PRIVATE_FILE, + ) + ) + .signature("signature") + .tags(listOf("t-shirt", "round-neck", "men")) + .transformation( + FileUploadParams.Transformation.builder() + .addPost( + FileUploadParams.Transformation.Post.Thumbnail.builder() + .value("w-150,h-150") + .build() + ) + .addPost( + FileUploadParams.Transformation.Post.Abs.builder() + .protocol( + FileUploadParams.Transformation.Post.Abs.Protocol.DASH + ) + .value("sr-240_360_480_720_1080") + .build() + ) + .pre("w-300,h-300,q-80") + .build() + ) + .useUniqueFileName(true) + .webhookUrl("https://example.com") + .build() + ) + + val response = responseFuture.get() + response.validate() + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/services/async/FolderServiceAsyncTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/services/async/FolderServiceAsyncTest.kt new file mode 100644 index 0000000..175c051 --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/services/async/FolderServiceAsyncTest.kt @@ -0,0 +1,132 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.async + +import com.imagekit.api.TestServerExtension +import com.imagekit.api.client.okhttp.ImageKitOkHttpClientAsync +import com.imagekit.api.models.folders.FolderCopyParams +import com.imagekit.api.models.folders.FolderCreateParams +import com.imagekit.api.models.folders.FolderDeleteParams +import com.imagekit.api.models.folders.FolderMoveParams +import com.imagekit.api.models.folders.FolderRenameParams +import org.junit.jupiter.api.Disabled +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith + +@ExtendWith(TestServerExtension::class) +internal class FolderServiceAsyncTest { + + @Disabled("Prism tests are disabled") + @Test + fun create() { + val client = + ImageKitOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .privateApiKey("My Private API Key") + .password("My Password") + .build() + val folderServiceAsync = client.folders() + + val folderFuture = + folderServiceAsync.create( + FolderCreateParams.builder() + .folderName("summer") + .parentFolderPath("/product/images/") + .build() + ) + + val folder = folderFuture.get() + folder.validate() + } + + @Disabled("Prism tests are disabled") + @Test + fun delete() { + val client = + ImageKitOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .privateApiKey("My Private API Key") + .password("My Password") + .build() + val folderServiceAsync = client.folders() + + val folderFuture = + folderServiceAsync.delete( + FolderDeleteParams.builder().folderPath("/folder/to/delete/").build() + ) + + val folder = folderFuture.get() + folder.validate() + } + + @Disabled("Prism tests are disabled") + @Test + fun copy() { + val client = + ImageKitOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .privateApiKey("My Private API Key") + .password("My Password") + .build() + val folderServiceAsync = client.folders() + + val responseFuture = + folderServiceAsync.copy( + FolderCopyParams.builder() + .destinationPath("/path/of/destination/folder") + .sourceFolderPath("/path/of/source/folder") + .includeVersions(true) + .build() + ) + + val response = responseFuture.get() + response.validate() + } + + @Disabled("Prism tests are disabled") + @Test + fun move() { + val client = + ImageKitOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .privateApiKey("My Private API Key") + .password("My Password") + .build() + val folderServiceAsync = client.folders() + + val responseFuture = + folderServiceAsync.move( + FolderMoveParams.builder() + .destinationPath("/path/of/destination/folder") + .sourceFolderPath("/path/of/source/folder") + .build() + ) + + val response = responseFuture.get() + response.validate() + } + + @Disabled("Prism tests are disabled") + @Test + fun rename() { + val client = + ImageKitOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .privateApiKey("My Private API Key") + .password("My Password") + .build() + val folderServiceAsync = client.folders() + + val responseFuture = + folderServiceAsync.rename( + FolderRenameParams.builder() + .folderPath("/path/of/folder") + .newFolderName("new-folder-name") + .purgeCache(true) + .build() + ) + + val response = responseFuture.get() + response.validate() + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/services/async/accounts/OriginServiceAsyncTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/services/async/accounts/OriginServiceAsyncTest.kt new file mode 100644 index 0000000..fb62ce1 --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/services/async/accounts/OriginServiceAsyncTest.kt @@ -0,0 +1,131 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.async.accounts + +import com.imagekit.api.TestServerExtension +import com.imagekit.api.client.okhttp.ImageKitOkHttpClientAsync +import com.imagekit.api.models.accounts.origins.OriginCreateParams +import com.imagekit.api.models.accounts.origins.OriginRequest +import com.imagekit.api.models.accounts.origins.OriginUpdateParams +import org.junit.jupiter.api.Disabled +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith + +@ExtendWith(TestServerExtension::class) +internal class OriginServiceAsyncTest { + + @Disabled("Prism tests are disabled") + @Test + fun create() { + val client = + ImageKitOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .privateApiKey("My Private API Key") + .password("My Password") + .build() + val originServiceAsync = client.accounts().origins() + + val originResponseFuture = + originServiceAsync.create( + OriginCreateParams.builder() + .originRequest( + OriginRequest.S3.builder() + .accessKey("AKIATEST123") + .bucket("test-bucket") + .name("My S3 Origin") + .secretKey("secrettest123") + .baseUrlForCanonicalHeader("https://cdn.example.com") + .includeCanonicalHeader(false) + .prefix("images") + .build() + ) + .build() + ) + + val originResponse = originResponseFuture.get() + originResponse.validate() + } + + @Disabled("Prism tests are disabled") + @Test + fun update() { + val client = + ImageKitOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .privateApiKey("My Private API Key") + .password("My Password") + .build() + val originServiceAsync = client.accounts().origins() + + val originResponseFuture = + originServiceAsync.update( + OriginUpdateParams.builder() + .id("id") + .originRequest( + OriginRequest.S3.builder() + .accessKey("AKIATEST123") + .bucket("test-bucket") + .name("My S3 Origin") + .secretKey("secrettest123") + .baseUrlForCanonicalHeader("https://cdn.example.com") + .includeCanonicalHeader(false) + .prefix("images") + .build() + ) + .build() + ) + + val originResponse = originResponseFuture.get() + originResponse.validate() + } + + @Disabled("Prism tests are disabled") + @Test + fun list() { + val client = + ImageKitOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .privateApiKey("My Private API Key") + .password("My Password") + .build() + val originServiceAsync = client.accounts().origins() + + val originResponsesFuture = originServiceAsync.list() + + val originResponses = originResponsesFuture.get() + originResponses.forEach { it.validate() } + } + + @Disabled("Prism tests are disabled") + @Test + fun delete() { + val client = + ImageKitOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .privateApiKey("My Private API Key") + .password("My Password") + .build() + val originServiceAsync = client.accounts().origins() + + val future = originServiceAsync.delete("id") + + val response = future.get() + } + + @Disabled("Prism tests are disabled") + @Test + fun get() { + val client = + ImageKitOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .privateApiKey("My Private API Key") + .password("My Password") + .build() + val originServiceAsync = client.accounts().origins() + + val originResponseFuture = originServiceAsync.get("id") + + val originResponse = originResponseFuture.get() + originResponse.validate() + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/services/async/accounts/UrlEndpointServiceAsyncTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/services/async/accounts/UrlEndpointServiceAsyncTest.kt new file mode 100644 index 0000000..e95e7e5 --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/services/async/accounts/UrlEndpointServiceAsyncTest.kt @@ -0,0 +1,133 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.async.accounts + +import com.imagekit.api.TestServerExtension +import com.imagekit.api.client.okhttp.ImageKitOkHttpClientAsync +import com.imagekit.api.models.accounts.urlendpoints.UrlEndpointCreateParams +import com.imagekit.api.models.accounts.urlendpoints.UrlEndpointRequest +import com.imagekit.api.models.accounts.urlendpoints.UrlEndpointUpdateParams +import org.junit.jupiter.api.Disabled +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith + +@ExtendWith(TestServerExtension::class) +internal class UrlEndpointServiceAsyncTest { + + @Disabled("Prism tests are disabled") + @Test + fun create() { + val client = + ImageKitOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .privateApiKey("My Private API Key") + .password("My Password") + .build() + val urlEndpointServiceAsync = client.accounts().urlEndpoints() + + val urlEndpointResponseFuture = + urlEndpointServiceAsync.create( + UrlEndpointCreateParams.builder() + .urlEndpointRequest( + UrlEndpointRequest.builder() + .description("My custom URL endpoint") + .addOrigin("origin-id-1") + .urlPrefix("product-images") + .urlRewriter( + UrlEndpointRequest.UrlRewriter.Cloudinary.builder() + .preserveAssetDeliveryTypes(true) + .build() + ) + .build() + ) + .build() + ) + + val urlEndpointResponse = urlEndpointResponseFuture.get() + urlEndpointResponse.validate() + } + + @Disabled("Prism tests are disabled") + @Test + fun update() { + val client = + ImageKitOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .privateApiKey("My Private API Key") + .password("My Password") + .build() + val urlEndpointServiceAsync = client.accounts().urlEndpoints() + + val urlEndpointResponseFuture = + urlEndpointServiceAsync.update( + UrlEndpointUpdateParams.builder() + .id("id") + .urlEndpointRequest( + UrlEndpointRequest.builder() + .description("My custom URL endpoint") + .addOrigin("origin-id-1") + .urlPrefix("product-images") + .urlRewriter( + UrlEndpointRequest.UrlRewriter.Cloudinary.builder() + .preserveAssetDeliveryTypes(true) + .build() + ) + .build() + ) + .build() + ) + + val urlEndpointResponse = urlEndpointResponseFuture.get() + urlEndpointResponse.validate() + } + + @Disabled("Prism tests are disabled") + @Test + fun list() { + val client = + ImageKitOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .privateApiKey("My Private API Key") + .password("My Password") + .build() + val urlEndpointServiceAsync = client.accounts().urlEndpoints() + + val urlEndpointResponsesFuture = urlEndpointServiceAsync.list() + + val urlEndpointResponses = urlEndpointResponsesFuture.get() + urlEndpointResponses.forEach { it.validate() } + } + + @Disabled("Prism tests are disabled") + @Test + fun delete() { + val client = + ImageKitOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .privateApiKey("My Private API Key") + .password("My Password") + .build() + val urlEndpointServiceAsync = client.accounts().urlEndpoints() + + val future = urlEndpointServiceAsync.delete("id") + + val response = future.get() + } + + @Disabled("Prism tests are disabled") + @Test + fun get() { + val client = + ImageKitOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .privateApiKey("My Private API Key") + .password("My Password") + .build() + val urlEndpointServiceAsync = client.accounts().urlEndpoints() + + val urlEndpointResponseFuture = urlEndpointServiceAsync.get("id") + + val urlEndpointResponse = urlEndpointResponseFuture.get() + urlEndpointResponse.validate() + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/services/async/accounts/UsageServiceAsyncTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/services/async/accounts/UsageServiceAsyncTest.kt new file mode 100644 index 0000000..08dd5a9 --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/services/async/accounts/UsageServiceAsyncTest.kt @@ -0,0 +1,38 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.async.accounts + +import com.imagekit.api.TestServerExtension +import com.imagekit.api.client.okhttp.ImageKitOkHttpClientAsync +import com.imagekit.api.models.accounts.usage.UsageGetParams +import java.time.LocalDate +import org.junit.jupiter.api.Disabled +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith + +@ExtendWith(TestServerExtension::class) +internal class UsageServiceAsyncTest { + + @Disabled("Prism tests are disabled") + @Test + fun get() { + val client = + ImageKitOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .privateApiKey("My Private API Key") + .password("My Password") + .build() + val usageServiceAsync = client.accounts().usage() + + val usageFuture = + usageServiceAsync.get( + UsageGetParams.builder() + .endDate(LocalDate.parse("2019-12-27")) + .startDate(LocalDate.parse("2019-12-27")) + .build() + ) + + val usage = usageFuture.get() + usage.validate() + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/services/async/beta/v2/FileServiceAsyncTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/services/async/beta/v2/FileServiceAsyncTest.kt new file mode 100644 index 0000000..b1fbb82 --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/services/async/beta/v2/FileServiceAsyncTest.kt @@ -0,0 +1,111 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.async.beta.v2 + +import com.imagekit.api.TestServerExtension +import com.imagekit.api.client.okhttp.ImageKitOkHttpClientAsync +import com.imagekit.api.core.JsonValue +import com.imagekit.api.models.UnnamedSchemaWithArrayParent3 +import com.imagekit.api.models.beta.v2.files.FileUploadParams +import org.junit.jupiter.api.Disabled +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith + +@ExtendWith(TestServerExtension::class) +internal class FileServiceAsyncTest { + + @Disabled("Prism tests are disabled") + @Test + fun upload() { + val client = + ImageKitOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .privateApiKey("My Private API Key") + .password("My Password") + .build() + val fileServiceAsync = client.beta().v2().files() + + val responseFuture = + fileServiceAsync.upload( + FileUploadParams.builder() + .file("some content".byteInputStream()) + .fileName("fileName") + .token("token") + .checks("\"request.folder\" : \"marketing/\"\n") + .customCoordinates("customCoordinates") + .customMetadata( + FileUploadParams.CustomMetadata.builder() + .putAdditionalProperty("brand", JsonValue.from("bar")) + .putAdditionalProperty("color", JsonValue.from("bar")) + .build() + ) + .description("Running shoes") + .extensions( + listOf( + UnnamedSchemaWithArrayParent3.ofRemoveBg( + UnnamedSchemaWithArrayParent3.RemoveBg.builder() + .options( + UnnamedSchemaWithArrayParent3.RemoveBg.Options.builder() + .addShadow(true) + .bgColor("bg_color") + .bgImageUrl("bg_image_url") + .semitransparency(true) + .build() + ) + .build() + ), + UnnamedSchemaWithArrayParent3.ofAutoTaggingExtension( + UnnamedSchemaWithArrayParent3.AutoTaggingExtension.builder() + .maxTags(5L) + .minConfidence(95L) + .name( + UnnamedSchemaWithArrayParent3.AutoTaggingExtension.Name + .GOOGLE_AUTO_TAGGING + ) + .build() + ), + UnnamedSchemaWithArrayParent3.ofAiAutoDescription(), + ) + ) + .folder("folder") + .isPrivateFile(true) + .isPublished(true) + .overwriteAiTags(true) + .overwriteCustomMetadata(true) + .overwriteFile(true) + .overwriteTags(true) + .responseFields( + listOf( + FileUploadParams.ResponseField.TAGS, + FileUploadParams.ResponseField.CUSTOM_COORDINATES, + FileUploadParams.ResponseField.IS_PRIVATE_FILE, + ) + ) + .tags(listOf("t-shirt", "round-neck", "men")) + .transformation( + FileUploadParams.Transformation.builder() + .addPost( + FileUploadParams.Transformation.Post.Thumbnail.builder() + .value("w-150,h-150") + .build() + ) + .addPost( + FileUploadParams.Transformation.Post.Abs.builder() + .protocol( + FileUploadParams.Transformation.Post.Abs.Protocol.DASH + ) + .value("sr-240_360_480_720_1080") + .build() + ) + .pre("w-300,h-300,q-80") + .build() + ) + .useUniqueFileName(true) + .webhookUrl("https://example.com") + .build() + ) + + val response = responseFuture.get() + response.validate() + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/services/async/cache/InvalidationServiceAsyncTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/services/async/cache/InvalidationServiceAsyncTest.kt new file mode 100644 index 0000000..547c8ca --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/services/async/cache/InvalidationServiceAsyncTest.kt @@ -0,0 +1,53 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.async.cache + +import com.imagekit.api.TestServerExtension +import com.imagekit.api.client.okhttp.ImageKitOkHttpClientAsync +import com.imagekit.api.models.cache.invalidation.InvalidationCreateParams +import org.junit.jupiter.api.Disabled +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith + +@ExtendWith(TestServerExtension::class) +internal class InvalidationServiceAsyncTest { + + @Disabled("Prism tests are disabled") + @Test + fun create() { + val client = + ImageKitOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .privateApiKey("My Private API Key") + .password("My Password") + .build() + val invalidationServiceAsync = client.cache().invalidation() + + val invalidationFuture = + invalidationServiceAsync.create( + InvalidationCreateParams.builder() + .url("https://ik.imagekit.io/your_imagekit_id/default-image.jpg") + .build() + ) + + val invalidation = invalidationFuture.get() + invalidation.validate() + } + + @Disabled("Prism tests are disabled") + @Test + fun get() { + val client = + ImageKitOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .privateApiKey("My Private API Key") + .password("My Password") + .build() + val invalidationServiceAsync = client.cache().invalidation() + + val invalidationFuture = invalidationServiceAsync.get("requestId") + + val invalidation = invalidationFuture.get() + invalidation.validate() + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/services/async/files/BulkServiceAsyncTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/services/async/files/BulkServiceAsyncTest.kt new file mode 100644 index 0000000..fd95a1e --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/services/async/files/BulkServiceAsyncTest.kt @@ -0,0 +1,112 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.async.files + +import com.imagekit.api.TestServerExtension +import com.imagekit.api.client.okhttp.ImageKitOkHttpClientAsync +import com.imagekit.api.models.files.bulk.BulkAddTagsParams +import com.imagekit.api.models.files.bulk.BulkDeleteParams +import com.imagekit.api.models.files.bulk.BulkRemoveAiTagsParams +import com.imagekit.api.models.files.bulk.BulkRemoveTagsParams +import org.junit.jupiter.api.Disabled +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith + +@ExtendWith(TestServerExtension::class) +internal class BulkServiceAsyncTest { + + @Disabled("Prism tests are disabled") + @Test + fun delete() { + val client = + ImageKitOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .privateApiKey("My Private API Key") + .password("My Password") + .build() + val bulkServiceAsync = client.files().bulk() + + val bulkFuture = + bulkServiceAsync.delete( + BulkDeleteParams.builder() + .addFileId("598821f949c0a938d57563bd") + .addFileId("598821f949c0a938d57563be") + .build() + ) + + val bulk = bulkFuture.get() + bulk.validate() + } + + @Disabled("Prism tests are disabled") + @Test + fun addTags() { + val client = + ImageKitOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .privateApiKey("My Private API Key") + .password("My Password") + .build() + val bulkServiceAsync = client.files().bulk() + + val responseFuture = + bulkServiceAsync.addTags( + BulkAddTagsParams.builder() + .addFileId("598821f949c0a938d57563bd") + .addFileId("598821f949c0a938d57563be") + .tags(listOf("t-shirt", "round-neck", "sale2019")) + .build() + ) + + val response = responseFuture.get() + response.validate() + } + + @Disabled("Prism tests are disabled") + @Test + fun removeAiTags() { + val client = + ImageKitOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .privateApiKey("My Private API Key") + .password("My Password") + .build() + val bulkServiceAsync = client.files().bulk() + + val responseFuture = + bulkServiceAsync.removeAiTags( + BulkRemoveAiTagsParams.builder() + .aiTags(listOf("t-shirt", "round-neck", "sale2019")) + .addFileId("598821f949c0a938d57563bd") + .addFileId("598821f949c0a938d57563be") + .build() + ) + + val response = responseFuture.get() + response.validate() + } + + @Disabled("Prism tests are disabled") + @Test + fun removeTags() { + val client = + ImageKitOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .privateApiKey("My Private API Key") + .password("My Password") + .build() + val bulkServiceAsync = client.files().bulk() + + val responseFuture = + bulkServiceAsync.removeTags( + BulkRemoveTagsParams.builder() + .addFileId("598821f949c0a938d57563bd") + .addFileId("598821f949c0a938d57563be") + .tags(listOf("t-shirt", "round-neck", "sale2019")) + .build() + ) + + val response = responseFuture.get() + response.validate() + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/services/async/files/MetadataServiceAsyncTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/services/async/files/MetadataServiceAsyncTest.kt new file mode 100644 index 0000000..827832b --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/services/async/files/MetadataServiceAsyncTest.kt @@ -0,0 +1,51 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.async.files + +import com.imagekit.api.TestServerExtension +import com.imagekit.api.client.okhttp.ImageKitOkHttpClientAsync +import com.imagekit.api.models.files.metadata.MetadataGetFromUrlParams +import org.junit.jupiter.api.Disabled +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith + +@ExtendWith(TestServerExtension::class) +internal class MetadataServiceAsyncTest { + + @Disabled("Prism tests are disabled") + @Test + fun get() { + val client = + ImageKitOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .privateApiKey("My Private API Key") + .password("My Password") + .build() + val metadataServiceAsync = client.files().metadata() + + val metadataFuture = metadataServiceAsync.get("fileId") + + val metadata = metadataFuture.get() + metadata.validate() + } + + @Disabled("Prism tests are disabled") + @Test + fun getFromUrl() { + val client = + ImageKitOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .privateApiKey("My Private API Key") + .password("My Password") + .build() + val metadataServiceAsync = client.files().metadata() + + val metadataFuture = + metadataServiceAsync.getFromUrl( + MetadataGetFromUrlParams.builder().url("https://example.com").build() + ) + + val metadata = metadataFuture.get() + metadata.validate() + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/services/async/files/VersionServiceAsyncTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/services/async/files/VersionServiceAsyncTest.kt new file mode 100644 index 0000000..afbefeb --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/services/async/files/VersionServiceAsyncTest.kt @@ -0,0 +1,93 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.async.files + +import com.imagekit.api.TestServerExtension +import com.imagekit.api.client.okhttp.ImageKitOkHttpClientAsync +import com.imagekit.api.models.files.versions.VersionDeleteParams +import com.imagekit.api.models.files.versions.VersionGetParams +import com.imagekit.api.models.files.versions.VersionRestoreParams +import org.junit.jupiter.api.Disabled +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith + +@ExtendWith(TestServerExtension::class) +internal class VersionServiceAsyncTest { + + @Disabled("Prism tests are disabled") + @Test + fun list() { + val client = + ImageKitOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .privateApiKey("My Private API Key") + .password("My Password") + .build() + val versionServiceAsync = client.files().versions() + + val filesFuture = versionServiceAsync.list("fileId") + + val files = filesFuture.get() + files.forEach { it.validate() } + } + + @Disabled("Prism tests are disabled") + @Test + fun delete() { + val client = + ImageKitOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .privateApiKey("My Private API Key") + .password("My Password") + .build() + val versionServiceAsync = client.files().versions() + + val versionFuture = + versionServiceAsync.delete( + VersionDeleteParams.builder().fileId("fileId").versionId("versionId").build() + ) + + val version = versionFuture.get() + version.validate() + } + + @Disabled("Prism tests are disabled") + @Test + fun get() { + val client = + ImageKitOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .privateApiKey("My Private API Key") + .password("My Password") + .build() + val versionServiceAsync = client.files().versions() + + val fileFuture = + versionServiceAsync.get( + VersionGetParams.builder().fileId("fileId").versionId("versionId").build() + ) + + val file = fileFuture.get() + file.validate() + } + + @Disabled("Prism tests are disabled") + @Test + fun restore() { + val client = + ImageKitOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .privateApiKey("My Private API Key") + .password("My Password") + .build() + val versionServiceAsync = client.files().versions() + + val fileFuture = + versionServiceAsync.restore( + VersionRestoreParams.builder().fileId("fileId").versionId("versionId").build() + ) + + val file = fileFuture.get() + file.validate() + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/services/async/folders/JobServiceAsyncTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/services/async/folders/JobServiceAsyncTest.kt new file mode 100644 index 0000000..db5b2d6 --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/services/async/folders/JobServiceAsyncTest.kt @@ -0,0 +1,30 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.async.folders + +import com.imagekit.api.TestServerExtension +import com.imagekit.api.client.okhttp.ImageKitOkHttpClientAsync +import org.junit.jupiter.api.Disabled +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith + +@ExtendWith(TestServerExtension::class) +internal class JobServiceAsyncTest { + + @Disabled("Prism tests are disabled") + @Test + fun get() { + val client = + ImageKitOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .privateApiKey("My Private API Key") + .password("My Password") + .build() + val jobServiceAsync = client.folders().job() + + val jobFuture = jobServiceAsync.get("jobId") + + val job = jobFuture.get() + job.validate() + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/services/blocking/AssetServiceTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/services/blocking/AssetServiceTest.kt new file mode 100644 index 0000000..50fc335 --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/services/blocking/AssetServiceTest.kt @@ -0,0 +1,41 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.blocking + +import com.imagekit.api.TestServerExtension +import com.imagekit.api.client.okhttp.ImageKitOkHttpClient +import com.imagekit.api.models.assets.AssetListParams +import org.junit.jupiter.api.Disabled +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith + +@ExtendWith(TestServerExtension::class) +internal class AssetServiceTest { + + @Disabled("Prism tests are disabled") + @Test + fun list() { + val client = + ImageKitOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .privateApiKey("My Private API Key") + .password("My Password") + .build() + val assetService = client.assets() + + val assets = + assetService.list( + AssetListParams.builder() + .fileType(AssetListParams.FileType.ALL) + .limit(1L) + .path("path") + .searchQuery("searchQuery") + .skip(0L) + .sort(AssetListParams.Sort.ASC_NAME) + .type(AssetListParams.Type.FILE) + .build() + ) + + assets.forEach { it.validate() } + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/services/blocking/CustomMetadataFieldServiceTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/services/blocking/CustomMetadataFieldServiceTest.kt new file mode 100644 index 0000000..be0a158 --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/services/blocking/CustomMetadataFieldServiceTest.kt @@ -0,0 +1,156 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.blocking + +import com.imagekit.api.TestServerExtension +import com.imagekit.api.client.okhttp.ImageKitOkHttpClient +import com.imagekit.api.models.custommetadatafields.CustomMetadataFieldCreateParams +import com.imagekit.api.models.custommetadatafields.CustomMetadataFieldListParams +import com.imagekit.api.models.custommetadatafields.CustomMetadataFieldUpdateParams +import org.junit.jupiter.api.Disabled +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith + +@ExtendWith(TestServerExtension::class) +internal class CustomMetadataFieldServiceTest { + + @Disabled("Prism tests are disabled") + @Test + fun create() { + val client = + ImageKitOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .privateApiKey("My Private API Key") + .password("My Password") + .build() + val customMetadataFieldService = client.customMetadataFields() + + val customMetadataField = + customMetadataFieldService.create( + CustomMetadataFieldCreateParams.builder() + .label("price") + .name("price") + .schema( + CustomMetadataFieldCreateParams.Schema.builder() + .type(CustomMetadataFieldCreateParams.Schema.Type.NUMBER) + .defaultValue("string") + .isValueRequired(true) + .maxLength(0.0) + .maxValue(3000.0) + .minLength(0.0) + .minValue(1000.0) + .selectOptions( + listOf( + CustomMetadataFieldCreateParams.Schema.SelectOption.ofString( + "small" + ), + CustomMetadataFieldCreateParams.Schema.SelectOption.ofString( + "medium" + ), + CustomMetadataFieldCreateParams.Schema.SelectOption.ofString( + "large" + ), + CustomMetadataFieldCreateParams.Schema.SelectOption.ofNumber( + 30.0 + ), + CustomMetadataFieldCreateParams.Schema.SelectOption.ofNumber( + 40.0 + ), + CustomMetadataFieldCreateParams.Schema.SelectOption.ofBool(true), + ) + ) + .build() + ) + .build() + ) + + customMetadataField.validate() + } + + @Disabled("Prism tests are disabled") + @Test + fun update() { + val client = + ImageKitOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .privateApiKey("My Private API Key") + .password("My Password") + .build() + val customMetadataFieldService = client.customMetadataFields() + + val customMetadataField = + customMetadataFieldService.update( + CustomMetadataFieldUpdateParams.builder() + .id("id") + .label("price") + .schema( + CustomMetadataFieldUpdateParams.Schema.builder() + .defaultValue("string") + .isValueRequired(true) + .maxLength(0.0) + .maxValue(3000.0) + .minLength(0.0) + .minValue(1000.0) + .selectOptions( + listOf( + CustomMetadataFieldUpdateParams.Schema.SelectOption.ofString( + "small" + ), + CustomMetadataFieldUpdateParams.Schema.SelectOption.ofString( + "medium" + ), + CustomMetadataFieldUpdateParams.Schema.SelectOption.ofString( + "large" + ), + CustomMetadataFieldUpdateParams.Schema.SelectOption.ofNumber( + 30.0 + ), + CustomMetadataFieldUpdateParams.Schema.SelectOption.ofNumber( + 40.0 + ), + CustomMetadataFieldUpdateParams.Schema.SelectOption.ofBool(true), + ) + ) + .build() + ) + .build() + ) + + customMetadataField.validate() + } + + @Disabled("Prism tests are disabled") + @Test + fun list() { + val client = + ImageKitOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .privateApiKey("My Private API Key") + .password("My Password") + .build() + val customMetadataFieldService = client.customMetadataFields() + + val customMetadataFields = + customMetadataFieldService.list( + CustomMetadataFieldListParams.builder().includeDeleted(true).build() + ) + + customMetadataFields.forEach { it.validate() } + } + + @Disabled("Prism tests are disabled") + @Test + fun delete() { + val client = + ImageKitOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .privateApiKey("My Private API Key") + .password("My Password") + .build() + val customMetadataFieldService = client.customMetadataFields() + + val customMetadataField = customMetadataFieldService.delete("id") + + customMetadataField.validate() + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/services/blocking/FileServiceTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/services/blocking/FileServiceTest.kt new file mode 100644 index 0000000..f9021b5 --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/services/blocking/FileServiceTest.kt @@ -0,0 +1,292 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.blocking + +import com.imagekit.api.TestServerExtension +import com.imagekit.api.client.okhttp.ImageKitOkHttpClient +import com.imagekit.api.core.JsonValue +import com.imagekit.api.models.UnnamedSchemaWithArrayParent3 +import com.imagekit.api.models.files.FileCopyParams +import com.imagekit.api.models.files.FileMoveParams +import com.imagekit.api.models.files.FileRenameParams +import com.imagekit.api.models.files.FileUpdateParams +import com.imagekit.api.models.files.FileUploadParams +import org.junit.jupiter.api.Disabled +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith + +@ExtendWith(TestServerExtension::class) +internal class FileServiceTest { + + @Disabled("Prism tests are disabled") + @Test + fun update() { + val client = + ImageKitOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .privateApiKey("My Private API Key") + .password("My Password") + .build() + val fileService = client.files() + + val file = + fileService.update( + FileUpdateParams.builder() + .fileId("fileId") + .body( + FileUpdateParams.Body.UpdateFileDetails.builder() + .customCoordinates("10,10,100,100") + .customMetadata( + FileUpdateParams.Body.UpdateFileDetails.CustomMetadata.builder() + .putAdditionalProperty("brand", JsonValue.from("bar")) + .putAdditionalProperty("color", JsonValue.from("bar")) + .build() + ) + .description("description") + .extensions( + listOf( + UnnamedSchemaWithArrayParent3.ofRemoveBg( + UnnamedSchemaWithArrayParent3.RemoveBg.builder() + .options( + UnnamedSchemaWithArrayParent3.RemoveBg.Options + .builder() + .addShadow(true) + .bgColor("bg_color") + .bgImageUrl("bg_image_url") + .semitransparency(true) + .build() + ) + .build() + ), + UnnamedSchemaWithArrayParent3.ofAutoTaggingExtension( + UnnamedSchemaWithArrayParent3.AutoTaggingExtension.builder() + .maxTags(10L) + .minConfidence(80L) + .name( + UnnamedSchemaWithArrayParent3.AutoTaggingExtension + .Name + .GOOGLE_AUTO_TAGGING + ) + .build() + ), + UnnamedSchemaWithArrayParent3.ofAutoTaggingExtension( + UnnamedSchemaWithArrayParent3.AutoTaggingExtension.builder() + .maxTags(10L) + .minConfidence(80L) + .name( + UnnamedSchemaWithArrayParent3.AutoTaggingExtension + .Name + .AWS_AUTO_TAGGING + ) + .build() + ), + UnnamedSchemaWithArrayParent3.ofAiAutoDescription(), + ) + ) + .removeAiTagsOfStrings(listOf("car", "vehicle", "motorsports")) + .addTag("tag1") + .addTag("tag2") + .webhookUrl("https://webhook.site/0d6b6c7a-8e5a-4b3a-8b7c-0d6b6c7a8e5a") + .build() + ) + .build() + ) + + file.validate() + } + + @Disabled("Prism tests are disabled") + @Test + fun delete() { + val client = + ImageKitOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .privateApiKey("My Private API Key") + .password("My Password") + .build() + val fileService = client.files() + + fileService.delete("fileId") + } + + @Disabled("Prism tests are disabled") + @Test + fun copy() { + val client = + ImageKitOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .privateApiKey("My Private API Key") + .password("My Password") + .build() + val fileService = client.files() + + val response = + fileService.copy( + FileCopyParams.builder() + .destinationPath("/folder/to/copy/into/") + .sourceFilePath("/path/to/file.jpg") + .includeFileVersions(false) + .build() + ) + + response.validate() + } + + @Disabled("Prism tests are disabled") + @Test + fun get() { + val client = + ImageKitOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .privateApiKey("My Private API Key") + .password("My Password") + .build() + val fileService = client.files() + + val file = fileService.get("fileId") + + file.validate() + } + + @Disabled("Prism tests are disabled") + @Test + fun move() { + val client = + ImageKitOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .privateApiKey("My Private API Key") + .password("My Password") + .build() + val fileService = client.files() + + val response = + fileService.move( + FileMoveParams.builder() + .destinationPath("/folder/to/move/into/") + .sourceFilePath("/path/to/file.jpg") + .build() + ) + + response.validate() + } + + @Disabled("Prism tests are disabled") + @Test + fun rename() { + val client = + ImageKitOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .privateApiKey("My Private API Key") + .password("My Password") + .build() + val fileService = client.files() + + val response = + fileService.rename( + FileRenameParams.builder() + .filePath("/path/to/file.jpg") + .newFileName("newFileName.jpg") + .purgeCache(true) + .build() + ) + + response.validate() + } + + @Disabled("Prism tests are disabled") + @Test + fun upload() { + val client = + ImageKitOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .privateApiKey("My Private API Key") + .password("My Password") + .build() + val fileService = client.files() + + val response = + fileService.upload( + FileUploadParams.builder() + .file("some content".byteInputStream()) + .fileName("fileName") + .token("token") + .checks("\"request.folder\" : \"marketing/\"\n") + .customCoordinates("customCoordinates") + .customMetadata( + FileUploadParams.CustomMetadata.builder() + .putAdditionalProperty("brand", JsonValue.from("bar")) + .putAdditionalProperty("color", JsonValue.from("bar")) + .build() + ) + .description("Running shoes") + .expire(0L) + .extensions( + listOf( + UnnamedSchemaWithArrayParent3.ofRemoveBg( + UnnamedSchemaWithArrayParent3.RemoveBg.builder() + .options( + UnnamedSchemaWithArrayParent3.RemoveBg.Options.builder() + .addShadow(true) + .bgColor("bg_color") + .bgImageUrl("bg_image_url") + .semitransparency(true) + .build() + ) + .build() + ), + UnnamedSchemaWithArrayParent3.ofAutoTaggingExtension( + UnnamedSchemaWithArrayParent3.AutoTaggingExtension.builder() + .maxTags(5L) + .minConfidence(95L) + .name( + UnnamedSchemaWithArrayParent3.AutoTaggingExtension.Name + .GOOGLE_AUTO_TAGGING + ) + .build() + ), + UnnamedSchemaWithArrayParent3.ofAiAutoDescription(), + ) + ) + .folder("folder") + .isPrivateFile(true) + .isPublished(true) + .overwriteAiTags(true) + .overwriteCustomMetadata(true) + .overwriteFile(true) + .overwriteTags(true) + .publicKey("publicKey") + .responseFields( + listOf( + FileUploadParams.ResponseField.TAGS, + FileUploadParams.ResponseField.CUSTOM_COORDINATES, + FileUploadParams.ResponseField.IS_PRIVATE_FILE, + ) + ) + .signature("signature") + .tags(listOf("t-shirt", "round-neck", "men")) + .transformation( + FileUploadParams.Transformation.builder() + .addPost( + FileUploadParams.Transformation.Post.Thumbnail.builder() + .value("w-150,h-150") + .build() + ) + .addPost( + FileUploadParams.Transformation.Post.Abs.builder() + .protocol( + FileUploadParams.Transformation.Post.Abs.Protocol.DASH + ) + .value("sr-240_360_480_720_1080") + .build() + ) + .pre("w-300,h-300,q-80") + .build() + ) + .useUniqueFileName(true) + .webhookUrl("https://example.com") + .build() + ) + + response.validate() + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/services/blocking/FolderServiceTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/services/blocking/FolderServiceTest.kt new file mode 100644 index 0000000..13026e9 --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/services/blocking/FolderServiceTest.kt @@ -0,0 +1,127 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.blocking + +import com.imagekit.api.TestServerExtension +import com.imagekit.api.client.okhttp.ImageKitOkHttpClient +import com.imagekit.api.models.folders.FolderCopyParams +import com.imagekit.api.models.folders.FolderCreateParams +import com.imagekit.api.models.folders.FolderDeleteParams +import com.imagekit.api.models.folders.FolderMoveParams +import com.imagekit.api.models.folders.FolderRenameParams +import org.junit.jupiter.api.Disabled +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith + +@ExtendWith(TestServerExtension::class) +internal class FolderServiceTest { + + @Disabled("Prism tests are disabled") + @Test + fun create() { + val client = + ImageKitOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .privateApiKey("My Private API Key") + .password("My Password") + .build() + val folderService = client.folders() + + val folder = + folderService.create( + FolderCreateParams.builder() + .folderName("summer") + .parentFolderPath("/product/images/") + .build() + ) + + folder.validate() + } + + @Disabled("Prism tests are disabled") + @Test + fun delete() { + val client = + ImageKitOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .privateApiKey("My Private API Key") + .password("My Password") + .build() + val folderService = client.folders() + + val folder = + folderService.delete( + FolderDeleteParams.builder().folderPath("/folder/to/delete/").build() + ) + + folder.validate() + } + + @Disabled("Prism tests are disabled") + @Test + fun copy() { + val client = + ImageKitOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .privateApiKey("My Private API Key") + .password("My Password") + .build() + val folderService = client.folders() + + val response = + folderService.copy( + FolderCopyParams.builder() + .destinationPath("/path/of/destination/folder") + .sourceFolderPath("/path/of/source/folder") + .includeVersions(true) + .build() + ) + + response.validate() + } + + @Disabled("Prism tests are disabled") + @Test + fun move() { + val client = + ImageKitOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .privateApiKey("My Private API Key") + .password("My Password") + .build() + val folderService = client.folders() + + val response = + folderService.move( + FolderMoveParams.builder() + .destinationPath("/path/of/destination/folder") + .sourceFolderPath("/path/of/source/folder") + .build() + ) + + response.validate() + } + + @Disabled("Prism tests are disabled") + @Test + fun rename() { + val client = + ImageKitOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .privateApiKey("My Private API Key") + .password("My Password") + .build() + val folderService = client.folders() + + val response = + folderService.rename( + FolderRenameParams.builder() + .folderPath("/path/of/folder") + .newFolderName("new-folder-name") + .purgeCache(true) + .build() + ) + + response.validate() + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/services/blocking/accounts/OriginServiceTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/services/blocking/accounts/OriginServiceTest.kt new file mode 100644 index 0000000..2e20139 --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/services/blocking/accounts/OriginServiceTest.kt @@ -0,0 +1,125 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.blocking.accounts + +import com.imagekit.api.TestServerExtension +import com.imagekit.api.client.okhttp.ImageKitOkHttpClient +import com.imagekit.api.models.accounts.origins.OriginCreateParams +import com.imagekit.api.models.accounts.origins.OriginRequest +import com.imagekit.api.models.accounts.origins.OriginUpdateParams +import org.junit.jupiter.api.Disabled +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith + +@ExtendWith(TestServerExtension::class) +internal class OriginServiceTest { + + @Disabled("Prism tests are disabled") + @Test + fun create() { + val client = + ImageKitOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .privateApiKey("My Private API Key") + .password("My Password") + .build() + val originService = client.accounts().origins() + + val originResponse = + originService.create( + OriginCreateParams.builder() + .originRequest( + OriginRequest.S3.builder() + .accessKey("AKIATEST123") + .bucket("test-bucket") + .name("My S3 Origin") + .secretKey("secrettest123") + .baseUrlForCanonicalHeader("https://cdn.example.com") + .includeCanonicalHeader(false) + .prefix("images") + .build() + ) + .build() + ) + + originResponse.validate() + } + + @Disabled("Prism tests are disabled") + @Test + fun update() { + val client = + ImageKitOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .privateApiKey("My Private API Key") + .password("My Password") + .build() + val originService = client.accounts().origins() + + val originResponse = + originService.update( + OriginUpdateParams.builder() + .id("id") + .originRequest( + OriginRequest.S3.builder() + .accessKey("AKIATEST123") + .bucket("test-bucket") + .name("My S3 Origin") + .secretKey("secrettest123") + .baseUrlForCanonicalHeader("https://cdn.example.com") + .includeCanonicalHeader(false) + .prefix("images") + .build() + ) + .build() + ) + + originResponse.validate() + } + + @Disabled("Prism tests are disabled") + @Test + fun list() { + val client = + ImageKitOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .privateApiKey("My Private API Key") + .password("My Password") + .build() + val originService = client.accounts().origins() + + val originResponses = originService.list() + + originResponses.forEach { it.validate() } + } + + @Disabled("Prism tests are disabled") + @Test + fun delete() { + val client = + ImageKitOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .privateApiKey("My Private API Key") + .password("My Password") + .build() + val originService = client.accounts().origins() + + originService.delete("id") + } + + @Disabled("Prism tests are disabled") + @Test + fun get() { + val client = + ImageKitOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .privateApiKey("My Private API Key") + .password("My Password") + .build() + val originService = client.accounts().origins() + + val originResponse = originService.get("id") + + originResponse.validate() + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/services/blocking/accounts/UrlEndpointServiceTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/services/blocking/accounts/UrlEndpointServiceTest.kt new file mode 100644 index 0000000..cdd0f58 --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/services/blocking/accounts/UrlEndpointServiceTest.kt @@ -0,0 +1,127 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.blocking.accounts + +import com.imagekit.api.TestServerExtension +import com.imagekit.api.client.okhttp.ImageKitOkHttpClient +import com.imagekit.api.models.accounts.urlendpoints.UrlEndpointCreateParams +import com.imagekit.api.models.accounts.urlendpoints.UrlEndpointRequest +import com.imagekit.api.models.accounts.urlendpoints.UrlEndpointUpdateParams +import org.junit.jupiter.api.Disabled +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith + +@ExtendWith(TestServerExtension::class) +internal class UrlEndpointServiceTest { + + @Disabled("Prism tests are disabled") + @Test + fun create() { + val client = + ImageKitOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .privateApiKey("My Private API Key") + .password("My Password") + .build() + val urlEndpointService = client.accounts().urlEndpoints() + + val urlEndpointResponse = + urlEndpointService.create( + UrlEndpointCreateParams.builder() + .urlEndpointRequest( + UrlEndpointRequest.builder() + .description("My custom URL endpoint") + .addOrigin("origin-id-1") + .urlPrefix("product-images") + .urlRewriter( + UrlEndpointRequest.UrlRewriter.Cloudinary.builder() + .preserveAssetDeliveryTypes(true) + .build() + ) + .build() + ) + .build() + ) + + urlEndpointResponse.validate() + } + + @Disabled("Prism tests are disabled") + @Test + fun update() { + val client = + ImageKitOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .privateApiKey("My Private API Key") + .password("My Password") + .build() + val urlEndpointService = client.accounts().urlEndpoints() + + val urlEndpointResponse = + urlEndpointService.update( + UrlEndpointUpdateParams.builder() + .id("id") + .urlEndpointRequest( + UrlEndpointRequest.builder() + .description("My custom URL endpoint") + .addOrigin("origin-id-1") + .urlPrefix("product-images") + .urlRewriter( + UrlEndpointRequest.UrlRewriter.Cloudinary.builder() + .preserveAssetDeliveryTypes(true) + .build() + ) + .build() + ) + .build() + ) + + urlEndpointResponse.validate() + } + + @Disabled("Prism tests are disabled") + @Test + fun list() { + val client = + ImageKitOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .privateApiKey("My Private API Key") + .password("My Password") + .build() + val urlEndpointService = client.accounts().urlEndpoints() + + val urlEndpointResponses = urlEndpointService.list() + + urlEndpointResponses.forEach { it.validate() } + } + + @Disabled("Prism tests are disabled") + @Test + fun delete() { + val client = + ImageKitOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .privateApiKey("My Private API Key") + .password("My Password") + .build() + val urlEndpointService = client.accounts().urlEndpoints() + + urlEndpointService.delete("id") + } + + @Disabled("Prism tests are disabled") + @Test + fun get() { + val client = + ImageKitOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .privateApiKey("My Private API Key") + .password("My Password") + .build() + val urlEndpointService = client.accounts().urlEndpoints() + + val urlEndpointResponse = urlEndpointService.get("id") + + urlEndpointResponse.validate() + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/services/blocking/accounts/UsageServiceTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/services/blocking/accounts/UsageServiceTest.kt new file mode 100644 index 0000000..b579bdf --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/services/blocking/accounts/UsageServiceTest.kt @@ -0,0 +1,37 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.blocking.accounts + +import com.imagekit.api.TestServerExtension +import com.imagekit.api.client.okhttp.ImageKitOkHttpClient +import com.imagekit.api.models.accounts.usage.UsageGetParams +import java.time.LocalDate +import org.junit.jupiter.api.Disabled +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith + +@ExtendWith(TestServerExtension::class) +internal class UsageServiceTest { + + @Disabled("Prism tests are disabled") + @Test + fun get() { + val client = + ImageKitOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .privateApiKey("My Private API Key") + .password("My Password") + .build() + val usageService = client.accounts().usage() + + val usage = + usageService.get( + UsageGetParams.builder() + .endDate(LocalDate.parse("2019-12-27")) + .startDate(LocalDate.parse("2019-12-27")) + .build() + ) + + usage.validate() + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/services/blocking/beta/v2/FileServiceTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/services/blocking/beta/v2/FileServiceTest.kt new file mode 100644 index 0000000..852adef --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/services/blocking/beta/v2/FileServiceTest.kt @@ -0,0 +1,110 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.blocking.beta.v2 + +import com.imagekit.api.TestServerExtension +import com.imagekit.api.client.okhttp.ImageKitOkHttpClient +import com.imagekit.api.core.JsonValue +import com.imagekit.api.models.UnnamedSchemaWithArrayParent3 +import com.imagekit.api.models.beta.v2.files.FileUploadParams +import org.junit.jupiter.api.Disabled +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith + +@ExtendWith(TestServerExtension::class) +internal class FileServiceTest { + + @Disabled("Prism tests are disabled") + @Test + fun upload() { + val client = + ImageKitOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .privateApiKey("My Private API Key") + .password("My Password") + .build() + val fileService = client.beta().v2().files() + + val response = + fileService.upload( + FileUploadParams.builder() + .file("some content".byteInputStream()) + .fileName("fileName") + .token("token") + .checks("\"request.folder\" : \"marketing/\"\n") + .customCoordinates("customCoordinates") + .customMetadata( + FileUploadParams.CustomMetadata.builder() + .putAdditionalProperty("brand", JsonValue.from("bar")) + .putAdditionalProperty("color", JsonValue.from("bar")) + .build() + ) + .description("Running shoes") + .extensions( + listOf( + UnnamedSchemaWithArrayParent3.ofRemoveBg( + UnnamedSchemaWithArrayParent3.RemoveBg.builder() + .options( + UnnamedSchemaWithArrayParent3.RemoveBg.Options.builder() + .addShadow(true) + .bgColor("bg_color") + .bgImageUrl("bg_image_url") + .semitransparency(true) + .build() + ) + .build() + ), + UnnamedSchemaWithArrayParent3.ofAutoTaggingExtension( + UnnamedSchemaWithArrayParent3.AutoTaggingExtension.builder() + .maxTags(5L) + .minConfidence(95L) + .name( + UnnamedSchemaWithArrayParent3.AutoTaggingExtension.Name + .GOOGLE_AUTO_TAGGING + ) + .build() + ), + UnnamedSchemaWithArrayParent3.ofAiAutoDescription(), + ) + ) + .folder("folder") + .isPrivateFile(true) + .isPublished(true) + .overwriteAiTags(true) + .overwriteCustomMetadata(true) + .overwriteFile(true) + .overwriteTags(true) + .responseFields( + listOf( + FileUploadParams.ResponseField.TAGS, + FileUploadParams.ResponseField.CUSTOM_COORDINATES, + FileUploadParams.ResponseField.IS_PRIVATE_FILE, + ) + ) + .tags(listOf("t-shirt", "round-neck", "men")) + .transformation( + FileUploadParams.Transformation.builder() + .addPost( + FileUploadParams.Transformation.Post.Thumbnail.builder() + .value("w-150,h-150") + .build() + ) + .addPost( + FileUploadParams.Transformation.Post.Abs.builder() + .protocol( + FileUploadParams.Transformation.Post.Abs.Protocol.DASH + ) + .value("sr-240_360_480_720_1080") + .build() + ) + .pre("w-300,h-300,q-80") + .build() + ) + .useUniqueFileName(true) + .webhookUrl("https://example.com") + .build() + ) + + response.validate() + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/services/blocking/cache/InvalidationServiceTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/services/blocking/cache/InvalidationServiceTest.kt new file mode 100644 index 0000000..819af01 --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/services/blocking/cache/InvalidationServiceTest.kt @@ -0,0 +1,51 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.blocking.cache + +import com.imagekit.api.TestServerExtension +import com.imagekit.api.client.okhttp.ImageKitOkHttpClient +import com.imagekit.api.models.cache.invalidation.InvalidationCreateParams +import org.junit.jupiter.api.Disabled +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith + +@ExtendWith(TestServerExtension::class) +internal class InvalidationServiceTest { + + @Disabled("Prism tests are disabled") + @Test + fun create() { + val client = + ImageKitOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .privateApiKey("My Private API Key") + .password("My Password") + .build() + val invalidationService = client.cache().invalidation() + + val invalidation = + invalidationService.create( + InvalidationCreateParams.builder() + .url("https://ik.imagekit.io/your_imagekit_id/default-image.jpg") + .build() + ) + + invalidation.validate() + } + + @Disabled("Prism tests are disabled") + @Test + fun get() { + val client = + ImageKitOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .privateApiKey("My Private API Key") + .password("My Password") + .build() + val invalidationService = client.cache().invalidation() + + val invalidation = invalidationService.get("requestId") + + invalidation.validate() + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/services/blocking/files/BulkServiceTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/services/blocking/files/BulkServiceTest.kt new file mode 100644 index 0000000..5523052 --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/services/blocking/files/BulkServiceTest.kt @@ -0,0 +1,108 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.blocking.files + +import com.imagekit.api.TestServerExtension +import com.imagekit.api.client.okhttp.ImageKitOkHttpClient +import com.imagekit.api.models.files.bulk.BulkAddTagsParams +import com.imagekit.api.models.files.bulk.BulkDeleteParams +import com.imagekit.api.models.files.bulk.BulkRemoveAiTagsParams +import com.imagekit.api.models.files.bulk.BulkRemoveTagsParams +import org.junit.jupiter.api.Disabled +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith + +@ExtendWith(TestServerExtension::class) +internal class BulkServiceTest { + + @Disabled("Prism tests are disabled") + @Test + fun delete() { + val client = + ImageKitOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .privateApiKey("My Private API Key") + .password("My Password") + .build() + val bulkService = client.files().bulk() + + val bulk = + bulkService.delete( + BulkDeleteParams.builder() + .addFileId("598821f949c0a938d57563bd") + .addFileId("598821f949c0a938d57563be") + .build() + ) + + bulk.validate() + } + + @Disabled("Prism tests are disabled") + @Test + fun addTags() { + val client = + ImageKitOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .privateApiKey("My Private API Key") + .password("My Password") + .build() + val bulkService = client.files().bulk() + + val response = + bulkService.addTags( + BulkAddTagsParams.builder() + .addFileId("598821f949c0a938d57563bd") + .addFileId("598821f949c0a938d57563be") + .tags(listOf("t-shirt", "round-neck", "sale2019")) + .build() + ) + + response.validate() + } + + @Disabled("Prism tests are disabled") + @Test + fun removeAiTags() { + val client = + ImageKitOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .privateApiKey("My Private API Key") + .password("My Password") + .build() + val bulkService = client.files().bulk() + + val response = + bulkService.removeAiTags( + BulkRemoveAiTagsParams.builder() + .aiTags(listOf("t-shirt", "round-neck", "sale2019")) + .addFileId("598821f949c0a938d57563bd") + .addFileId("598821f949c0a938d57563be") + .build() + ) + + response.validate() + } + + @Disabled("Prism tests are disabled") + @Test + fun removeTags() { + val client = + ImageKitOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .privateApiKey("My Private API Key") + .password("My Password") + .build() + val bulkService = client.files().bulk() + + val response = + bulkService.removeTags( + BulkRemoveTagsParams.builder() + .addFileId("598821f949c0a938d57563bd") + .addFileId("598821f949c0a938d57563be") + .tags(listOf("t-shirt", "round-neck", "sale2019")) + .build() + ) + + response.validate() + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/services/blocking/files/MetadataServiceTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/services/blocking/files/MetadataServiceTest.kt new file mode 100644 index 0000000..fcdef81 --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/services/blocking/files/MetadataServiceTest.kt @@ -0,0 +1,49 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.blocking.files + +import com.imagekit.api.TestServerExtension +import com.imagekit.api.client.okhttp.ImageKitOkHttpClient +import com.imagekit.api.models.files.metadata.MetadataGetFromUrlParams +import org.junit.jupiter.api.Disabled +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith + +@ExtendWith(TestServerExtension::class) +internal class MetadataServiceTest { + + @Disabled("Prism tests are disabled") + @Test + fun get() { + val client = + ImageKitOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .privateApiKey("My Private API Key") + .password("My Password") + .build() + val metadataService = client.files().metadata() + + val metadata = metadataService.get("fileId") + + metadata.validate() + } + + @Disabled("Prism tests are disabled") + @Test + fun getFromUrl() { + val client = + ImageKitOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .privateApiKey("My Private API Key") + .password("My Password") + .build() + val metadataService = client.files().metadata() + + val metadata = + metadataService.getFromUrl( + MetadataGetFromUrlParams.builder().url("https://example.com").build() + ) + + metadata.validate() + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/services/blocking/files/VersionServiceTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/services/blocking/files/VersionServiceTest.kt new file mode 100644 index 0000000..a8d311c --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/services/blocking/files/VersionServiceTest.kt @@ -0,0 +1,89 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.blocking.files + +import com.imagekit.api.TestServerExtension +import com.imagekit.api.client.okhttp.ImageKitOkHttpClient +import com.imagekit.api.models.files.versions.VersionDeleteParams +import com.imagekit.api.models.files.versions.VersionGetParams +import com.imagekit.api.models.files.versions.VersionRestoreParams +import org.junit.jupiter.api.Disabled +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith + +@ExtendWith(TestServerExtension::class) +internal class VersionServiceTest { + + @Disabled("Prism tests are disabled") + @Test + fun list() { + val client = + ImageKitOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .privateApiKey("My Private API Key") + .password("My Password") + .build() + val versionService = client.files().versions() + + val files = versionService.list("fileId") + + files.forEach { it.validate() } + } + + @Disabled("Prism tests are disabled") + @Test + fun delete() { + val client = + ImageKitOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .privateApiKey("My Private API Key") + .password("My Password") + .build() + val versionService = client.files().versions() + + val version = + versionService.delete( + VersionDeleteParams.builder().fileId("fileId").versionId("versionId").build() + ) + + version.validate() + } + + @Disabled("Prism tests are disabled") + @Test + fun get() { + val client = + ImageKitOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .privateApiKey("My Private API Key") + .password("My Password") + .build() + val versionService = client.files().versions() + + val file = + versionService.get( + VersionGetParams.builder().fileId("fileId").versionId("versionId").build() + ) + + file.validate() + } + + @Disabled("Prism tests are disabled") + @Test + fun restore() { + val client = + ImageKitOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .privateApiKey("My Private API Key") + .password("My Password") + .build() + val versionService = client.files().versions() + + val file = + versionService.restore( + VersionRestoreParams.builder().fileId("fileId").versionId("versionId").build() + ) + + file.validate() + } +} diff --git a/image-kit-java-core/src/test/kotlin/com/imagekit/api/services/blocking/folders/JobServiceTest.kt b/image-kit-java-core/src/test/kotlin/com/imagekit/api/services/blocking/folders/JobServiceTest.kt new file mode 100644 index 0000000..63455dd --- /dev/null +++ b/image-kit-java-core/src/test/kotlin/com/imagekit/api/services/blocking/folders/JobServiceTest.kt @@ -0,0 +1,29 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.services.blocking.folders + +import com.imagekit.api.TestServerExtension +import com.imagekit.api.client.okhttp.ImageKitOkHttpClient +import org.junit.jupiter.api.Disabled +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith + +@ExtendWith(TestServerExtension::class) +internal class JobServiceTest { + + @Disabled("Prism tests are disabled") + @Test + fun get() { + val client = + ImageKitOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .privateApiKey("My Private API Key") + .password("My Password") + .build() + val jobService = client.folders().job() + + val job = jobService.get("jobId") + + job.validate() + } +} diff --git a/image-kit-java-example/build.gradle.kts b/image-kit-java-example/build.gradle.kts new file mode 100644 index 0000000..f9f4b81 --- /dev/null +++ b/image-kit-java-example/build.gradle.kts @@ -0,0 +1,28 @@ +plugins { + id("image-kit.java") + application +} + +repositories { + mavenCentral() +} + +dependencies { + implementation(project(":image-kit-java")) +} + +tasks.withType().configureEach { + // Allow using more modern APIs, like `List.of` and `Map.of`, in examples. + options.release.set(9) +} + +application { + // Use `./gradlew :image-kit-java-example:run` to run `Main` + // Use `./gradlew :image-kit-java-example:run -Pexample=Something` to run `SomethingExample` + mainClass = "com.imagekit.api.example.${ + if (project.hasProperty("example")) + "${project.property("example")}Example" + else + "Main" + }" +} diff --git a/image-kit-java-lib/.keep b/image-kit-java-lib/.keep new file mode 100644 index 0000000..5e2c99f --- /dev/null +++ b/image-kit-java-lib/.keep @@ -0,0 +1,4 @@ +File generated from our OpenAPI spec by Stainless. + +This directory can be used to store custom files to expand the SDK. +It is ignored by Stainless code generation and its content (other than this keep file) won't be touched. \ No newline at end of file diff --git a/image-kit-java-proguard-test/build.gradle.kts b/image-kit-java-proguard-test/build.gradle.kts new file mode 100644 index 0000000..c541ddc --- /dev/null +++ b/image-kit-java-proguard-test/build.gradle.kts @@ -0,0 +1,101 @@ +plugins { + id("image-kit.kotlin") + id("com.gradleup.shadow") version "8.3.8" +} + +buildscript { + repositories { + google() + } + + dependencies { + classpath("com.guardsquare:proguard-gradle:7.4.2") + classpath("com.android.tools:r8:8.3.37") + } +} + +dependencies { + testImplementation(project(":image-kit-java")) + testImplementation(kotlin("test")) + testImplementation("org.junit.jupiter:junit-jupiter-api:5.9.3") + testImplementation("org.assertj:assertj-core:3.25.3") + testImplementation("com.fasterxml.jackson.module:jackson-module-kotlin:2.13.4") +} + +tasks.shadowJar { + from(sourceSets.test.get().output) + configurations = listOf(project.configurations.testRuntimeClasspath.get()) +} + +val proguardJarPath = "${layout.buildDirectory.get()}/libs/${project.name}-${project.version}-proguard.jar" +val proguardJar by tasks.registering(proguard.gradle.ProGuardTask::class) { + group = "verification" + dependsOn(tasks.shadowJar) + notCompatibleWithConfigurationCache("ProGuard") + + injars(tasks.shadowJar) + outjars(proguardJarPath) + printmapping("${layout.buildDirectory.get()}/proguard-mapping.txt") + + val javaHome = System.getProperty("java.home") + if (System.getProperty("java.version").startsWith("1.")) { + // Before Java 9, the runtime classes were packaged in a single jar file. + libraryjars("$javaHome/lib/rt.jar") + } else { + // As of Java 9, the runtime classes are packaged in modular jmod files. + libraryjars( + // Filters must be specified first, as a map. + mapOf("jarfilter" to "!**.jar", "filter" to "!module-info.class"), + "$javaHome/jmods/java.base.jmod" + ) + } + + configuration("./test.pro") + configuration("../image-kit-java-core/src/main/resources/META-INF/proguard/image-kit-java-core.pro") +} + +val testProGuard by tasks.registering(JavaExec::class) { + group = "verification" + dependsOn(proguardJar) + notCompatibleWithConfigurationCache("ProGuard") + + mainClass.set("com.imagekit.api.proguard.ProGuardCompatibilityTest") + classpath = files(proguardJarPath) +} + +val r8JarPath = "${layout.buildDirectory.get()}/libs/${project.name}-${project.version}-r8.jar" +val r8Jar by tasks.registering(JavaExec::class) { + group = "verification" + dependsOn(tasks.shadowJar) + notCompatibleWithConfigurationCache("R8") + + mainClass.set("com.android.tools.r8.R8") + classpath = buildscript.configurations["classpath"] + + args = listOf( + "--release", + "--classfile", + "--output", r8JarPath, + "--lib", System.getProperty("java.home"), + "--pg-conf", "./test.pro", + "--pg-conf", "../image-kit-java-core/src/main/resources/META-INF/proguard/image-kit-java-core.pro", + "--pg-map-output", "${layout.buildDirectory.get()}/r8-mapping.txt", + tasks.shadowJar.get().archiveFile.get().asFile.absolutePath, + ) +} + +val testR8 by tasks.registering(JavaExec::class) { + group = "verification" + dependsOn(r8Jar) + notCompatibleWithConfigurationCache("R8") + + mainClass.set("com.imagekit.api.proguard.ProGuardCompatibilityTest") + classpath = files(r8JarPath) +} + +tasks.test { + dependsOn(testProGuard) + dependsOn(testR8) + // We defer to the tests run via the ProGuard JAR. + enabled = false +} diff --git a/image-kit-java-proguard-test/src/test/kotlin/com/imagekit/api/proguard/ProGuardCompatibilityTest.kt b/image-kit-java-proguard-test/src/test/kotlin/com/imagekit/api/proguard/ProGuardCompatibilityTest.kt new file mode 100644 index 0000000..6b3c1c9 --- /dev/null +++ b/image-kit-java-proguard-test/src/test/kotlin/com/imagekit/api/proguard/ProGuardCompatibilityTest.kt @@ -0,0 +1,168 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.imagekit.api.proguard + +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.imagekit.api.client.okhttp.ImageKitOkHttpClient +import com.imagekit.api.core.JsonValue +import com.imagekit.api.core.jsonMapper +import com.imagekit.api.models.Overlay +import com.imagekit.api.models.OverlayPosition +import com.imagekit.api.models.OverlayTiming +import com.imagekit.api.models.StreamingResolution +import com.imagekit.api.models.TextOverlay +import com.imagekit.api.models.TextOverlayTransformation +import com.imagekit.api.models.files.File +import java.time.OffsetDateTime +import kotlin.reflect.full.memberFunctions +import kotlin.reflect.jvm.javaMethod +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class ProGuardCompatibilityTest { + + companion object { + + @JvmStatic + fun main(args: Array) { + // To debug that we're using the right JAR. + val jarPath = this::class.java.getProtectionDomain().codeSource.location + println("JAR being used: $jarPath") + + // We have to manually run the test methods instead of using the JUnit runner because it + // seems impossible to get working with R8. + val test = ProGuardCompatibilityTest() + test::class + .memberFunctions + .asSequence() + .filter { function -> + function.javaMethod?.isAnnotationPresent(Test::class.java) == true + } + .forEach { it.call(test) } + } + } + + @Test + fun proguardRules() { + val rulesFile = + javaClass.classLoader.getResourceAsStream("META-INF/proguard/image-kit-java-core.pro") + + assertThat(rulesFile).isNotNull() + } + + @Test + fun client() { + val client = + ImageKitOkHttpClient.builder() + .privateApiKey("My Private API Key") + .password("My Password") + .build() + + assertThat(client).isNotNull() + assertThat(client.customMetadataFields()).isNotNull() + assertThat(client.files()).isNotNull() + assertThat(client.assets()).isNotNull() + assertThat(client.cache()).isNotNull() + assertThat(client.folders()).isNotNull() + assertThat(client.accounts()).isNotNull() + assertThat(client.beta()).isNotNull() + assertThat(client.webhooks()).isNotNull() + } + + @Test + fun fileRoundtrip() { + val jsonMapper = jsonMapper() + val file = + File.builder() + .addAiTag( + File.AiTag.builder().confidence(0.0).name("name").source("source").build() + ) + .createdAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .customCoordinates("customCoordinates") + .customMetadata( + File.CustomMetadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .description("description") + .fileId("fileId") + .filePath("filePath") + .fileType("fileType") + .hasAlpha(true) + .height(0.0) + .isPrivateFile(true) + .isPublished(true) + .mime("mime") + .name("name") + .size(0.0) + .addTag("string") + .thumbnail("https://example.com") + .type(File.Type.FILE) + .updatedAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .url("https://example.com") + .versionInfo(File.VersionInfo.builder().id("id").name("name").build()) + .width(0.0) + .build() + + val roundtrippedFile = + jsonMapper.readValue(jsonMapper.writeValueAsString(file), jacksonTypeRef()) + + assertThat(roundtrippedFile).isEqualTo(file) + } + + @Test + fun overlayRoundtrip() { + val jsonMapper = jsonMapper() + val overlay = + Overlay.ofText( + TextOverlay.builder() + .position( + OverlayPosition.builder() + .focus(OverlayPosition.Focus.CENTER) + .x(0.0) + .y(0.0) + .build() + ) + .timing(OverlayTiming.builder().duration(0.0).end(0.0).start(0.0).build()) + .text("text") + .encoding(TextOverlay.Encoding.AUTO) + .addTransformation( + TextOverlayTransformation.builder() + .alpha(1.0) + .background("background") + .flip(TextOverlayTransformation.Flip.H) + .fontColor("fontColor") + .fontFamily("fontFamily") + .fontSize(0.0) + .innerAlignment(TextOverlayTransformation.InnerAlignment.LEFT) + .lineHeight(0.0) + .padding(0.0) + .radius(0.0) + .rotation(0.0) + .typography("typography") + .width(0.0) + .build() + ) + .build() + ) + + val roundtrippedOverlay = + jsonMapper.readValue(jsonMapper.writeValueAsString(overlay), jacksonTypeRef()) + + assertThat(roundtrippedOverlay).isEqualTo(overlay) + } + + @Test + fun streamingResolutionRoundtrip() { + val jsonMapper = jsonMapper() + val streamingResolution = StreamingResolution._240 + + val roundtrippedStreamingResolution = + jsonMapper.readValue( + jsonMapper.writeValueAsString(streamingResolution), + jacksonTypeRef(), + ) + + assertThat(roundtrippedStreamingResolution).isEqualTo(streamingResolution) + } +} diff --git a/image-kit-java-proguard-test/test.pro b/image-kit-java-proguard-test/test.pro new file mode 100644 index 0000000..64d7928 --- /dev/null +++ b/image-kit-java-proguard-test/test.pro @@ -0,0 +1,9 @@ +# Specify the entrypoint where ProGuard starts to determine what's reachable. +-keep class com.imagekit.api.proguard.** { *; } + +# For the testing framework. +-keep class org.junit.** { *; } + +# Many warnings don't apply for our testing purposes. +-dontnote +-dontwarn \ No newline at end of file diff --git a/image-kit-java/build.gradle.kts b/image-kit-java/build.gradle.kts new file mode 100644 index 0000000..7eaf9e4 --- /dev/null +++ b/image-kit-java/build.gradle.kts @@ -0,0 +1,29 @@ +plugins { + id("image-kit.kotlin") + id("image-kit.publish") +} + +dependencies { + api(project(":image-kit-java-client-okhttp")) +} + +// Redefine `dokkaJavadoc` to: +// - Depend on the root project's task for merging the docs of all the projects +// - Forward that task's output to this task's output +tasks.named("dokkaJavadoc").configure { + actions.clear() + + val dokkaJavadocCollector = rootProject.tasks["dokkaJavadocCollector"] + dependsOn(dokkaJavadocCollector) + + val outputDirectory = project.layout.buildDirectory.dir("dokka/javadoc") + doLast { + copy { + from(dokkaJavadocCollector.outputs.files) + into(outputDirectory) + duplicatesStrategy = DuplicatesStrategy.INCLUDE + } + } + + outputs.dir(outputDirectory) +} diff --git a/imagekit-sdk/build.gradle b/imagekit-sdk/build.gradle deleted file mode 100644 index ff248c8..0000000 --- a/imagekit-sdk/build.gradle +++ /dev/null @@ -1,28 +0,0 @@ -plugins { - id 'java' - id 'java-library' -} - -group 'io.imagekit.sdk' -version '2.0.1' - -sourceCompatibility = 1.8 - -repositories { - mavenCentral() -} - -test { - useJUnitPlatform() -} - -dependencies { - compile 'commons-codec:commons-codec:1.13' - implementation 'com.google.code.gson:gson:2.7' - implementation 'com.squareup.okhttp3:okhttp:3.10.0' - compile group: 'com.squareup.okio', name: 'okio', version: '1.14.0' - testCompile group: 'junit', name: 'junit', version: '4.12' - testRuntimeOnly("org.junit.vintage:junit-vintage-engine:5.8.2") - testCompile "org.mockito:mockito-all:2.+" - testImplementation 'com.squareup.okhttp3:mockwebserver:3.10.0' -} diff --git a/imagekit-sdk/src/main/java/io/imagekit/sdk/ImageKit.java b/imagekit-sdk/src/main/java/io/imagekit/sdk/ImageKit.java deleted file mode 100644 index 2cd8fa7..0000000 --- a/imagekit-sdk/src/main/java/io/imagekit/sdk/ImageKit.java +++ /dev/null @@ -1,437 +0,0 @@ -package io.imagekit.sdk; - -import io.imagekit.sdk.config.Configuration; -import io.imagekit.sdk.exceptions.BadRequestException; -import io.imagekit.sdk.exceptions.ConflictException; -import io.imagekit.sdk.exceptions.ForbiddenException; -import io.imagekit.sdk.exceptions.InternalServerException; -import io.imagekit.sdk.exceptions.NotFoundException; -import io.imagekit.sdk.exceptions.PartialSuccessException; -import io.imagekit.sdk.exceptions.TooManyRequestsException; -import io.imagekit.sdk.exceptions.UnauthorizedException; -import io.imagekit.sdk.exceptions.UnknownException; -import io.imagekit.sdk.models.*; -import io.imagekit.sdk.models.results.*; -import io.imagekit.sdk.tasks.Calculation; -import io.imagekit.sdk.tasks.RestClient; -import io.imagekit.sdk.tasks.UrlGen; - -import java.util.List; -import java.util.Map; - -public final class ImageKit { - private static ImageKit imageKit; - private Configuration configuration; - private RestClient restClient; - - private ImageKit() { - configuration = new Configuration(); - } - - /** - * getInstance() method will return single instance all over the application - * - * @return object ImageKit - */ - public static synchronized ImageKit getInstance() { - if (imageKit == null) { - imageKit = new ImageKit(); - imageKit.restClient = new RestClient(imageKit); - } - return imageKit; - } - - /** - * setRestClient(RestClient restClient) it takes object of RestClient class - * - * @param restClient to set restClient - */ - void setRestClient(RestClient restClient) { - this.restClient = restClient; - } - - /** - * setConfig(Configuration config) - * - * @param config will save new configuration - */ - public void setConfig(Configuration config) { - this.configuration = config; - } - - /** - * getConfig() - * - * @return it will return current configuration - */ - public Configuration getConfig() { - return configuration; - } - - /** - * - * @param options is a HashMap of Objects it can contains following keys - - * ["path","src","urlEndpoint","transformation", - * "transformationPosition","queryParameters", - * "signed","expireSeconds"] where transformation is an List of - * HashMap, signed is boolean and expireSeconds is integer. - * @return String new generated url - */ - - public String getUrl(Map options) { - return UrlGen.getUrl(options); - } - - /** - * - * @param fileCreateRequest is a object which contains file and other parameters - * @return object of Result class - */ - public Result upload(FileCreateRequest fileCreateRequest) throws InternalServerException, BadRequestException, - UnknownException, ForbiddenException, TooManyRequestsException, UnauthorizedException { - return restClient.upload(fileCreateRequest); - } - - /** - * - * @param fileUpdateRequest is a object which contains parameters and fileId - * @return object of Result class - */ - public Result updateFileDetail(FileUpdateRequest fileUpdateRequest) - throws ForbiddenException, TooManyRequestsException, InternalServerException, UnauthorizedException, - BadRequestException, UnknownException { - return restClient.updateFileDetail(fileUpdateRequest); - } - - /** - * - * @param getFileListRequest is an map it may contain keys [ "path", "fileType", "tags", - * "includeFolder", "name", "limit", "skip"] - * @return ResultList class that contains list of BaseFile - */ - public ResultList getFileList(GetFileListRequest getFileListRequest) throws ForbiddenException, TooManyRequestsException, - InternalServerException, UnauthorizedException, BadRequestException, UnknownException, IllegalAccessException, InstantiationException { - return restClient.getFileList(getFileListRequest); - } - - /** - * - * @param fileId is a unique file id - * @return Result class - */ - public Result getFileDetail(String fileId) throws ForbiddenException, TooManyRequestsException, - InternalServerException, UnauthorizedException, BadRequestException, UnknownException { - return restClient.getFileDetail(fileId); - } - - /** - * - * @param fileId is a unique file id - * @return ResultMetaData class - */ - public ResultMetaData getFileMetadata(String fileId) throws ForbiddenException, TooManyRequestsException, - InternalServerException, UnauthorizedException, BadRequestException, UnknownException { - return restClient.getFileMetaData(fileId); - } - - /** - * - * @param url is a remote image url - * @return ResultMetaData class - */ - public ResultMetaData getRemoteFileMetadata(String url) throws ForbiddenException, TooManyRequestsException, - InternalServerException, UnauthorizedException, BadRequestException, UnknownException { - return restClient.getRemoteFileMetaData(url); - } - - /** - * - * @param fileId is a unique file id - * @return Result class - */ - public Result deleteFile(String fileId) throws ForbiddenException, TooManyRequestsException, - InternalServerException, UnauthorizedException, BadRequestException, UnknownException { - return restClient.deleteFile(fileId); - } - - /** - * - * @param fileIds is a list of unique file id - * @return Result class - */ - public ResultFileDelete bulkDeleteFiles(List fileIds) - throws ForbiddenException, TooManyRequestsException, InternalServerException, PartialSuccessException, - UnauthorizedException, NotFoundException, BadRequestException, UnknownException { - return restClient.bulkDeleteFiles(fileIds); - } - - /** - * - * @param url is image url - * @return ResultCache class - */ - public ResultCache purgeCache(String url) throws ForbiddenException, TooManyRequestsException, - InternalServerException, UnauthorizedException, BadRequestException, UnknownException { - return restClient.purgeCache(url); - } - - /** - * - * @param requestId is cache request id - * @return ResultCacheStatus class - */ - public ResultCacheStatus getPurgeCacheStatus(String requestId) throws ForbiddenException, TooManyRequestsException, - InternalServerException, UnauthorizedException, BadRequestException, UnknownException { - return restClient.getPurgeCacheStatus(requestId); - } - - /** - * - * @return a map that contains token, expire and signature - */ - public Map getAuthenticationParameters() { - return Calculation.getAuthenticatedParams(null, 0, configuration.getPrivateKey()); - } - - /** - * - * @param token take as a argument - * @return a map that contains token, expire and signature - */ - public Map getAuthenticationParameters(String token) { - return Calculation.getAuthenticatedParams(token, 0, configuration.getPrivateKey()); - } - - /** - * - * @param token take as first argument - * @param expire is a Timestamp in milliseconds take as second argument - * @return a map that contains token, expire and signature - */ - public Map getAuthenticationParameters(String token, long expire) { - return Calculation.getAuthenticatedParams(token, expire, configuration.getPrivateKey()); - } - - /** - * firstHex and secondHex must have equal length - * - * @param firstHex take Hex as a String argument - * @param secondHex take Hex as a String argument - * @return it's distance - */ - public int pHashDistance(String firstHex, String secondHex) { - return Calculation.getHammingDistance(firstHex, secondHex); - } - - /** - * - * @param tagsRequest is a object which contains fileIds and tags as a - * parameters - * @return ArrayList of String - */ - public ResultTags addTags(TagsRequest tagsRequest) - throws NotFoundException, PartialSuccessException, BadRequestException, InternalServerException, - UnknownException, ForbiddenException, TooManyRequestsException, UnauthorizedException { - return restClient.manageTags(tagsRequest, "addTags"); - } - - /** - * - * @param aiTagsRequest is a object which contains fileIds and tags as a - * parameters - * @return ArrayList of String - */ - public ResultTags removeAITags(AITagsRequest aiTagsRequest) - throws PartialSuccessException, NotFoundException, BadRequestException, InternalServerException, - UnknownException, ForbiddenException, TooManyRequestsException, UnauthorizedException { - return restClient.removeAITags(aiTagsRequest); - } - - /** - * - * @param tagsRequest is a object which contains fileIds and tags as a - * parameters - * @return ArrayList of String - */ - public ResultTags removeTags(TagsRequest tagsRequest) - throws NotFoundException, PartialSuccessException, BadRequestException, InternalServerException, - UnknownException, ForbiddenException, TooManyRequestsException, UnauthorizedException { - return restClient.manageTags(tagsRequest, "removeTags"); - } - - /** - * - * @return a CustomMetaDataResultList that contains CustomMetaDataField's name, - * label, schema - */ - public ResultCustomMetaDataFieldList getCustomMetaDataFields(boolean includeDeleted) throws UnknownException { - return restClient.getCustomMetaDataFields(includeDeleted); - } - - /** - * - * @param customMetaDataFieldCreateRequest that contains CustomMetaDataField's - * name, label, schema with type, - * minLength, maxLength - * @return ResultCustomMetaData with ResultCustomMetaDataField - */ - public ResultCustomMetaDataField createCustomMetaDataFields( - CustomMetaDataFieldCreateRequest customMetaDataFieldCreateRequest) - throws BadRequestException, UnknownException { - return restClient.createCustomMetaDataFields(customMetaDataFieldCreateRequest); - } - - /** - * - * @param id is a id of customMetaDataFields - * @return Result class - */ - public ResultNoContent deleteCustomMetaDataField(String id) throws NotFoundException, UnknownException { - return restClient.deleteCustomMetaDataField(id); - } - - /** - * - * @param customMetaDataFieldUpdateRequest that contains CustomMetaDataField's - * id, schema with type, minLength, - * maxLength - * @return Result class - */ - public ResultCustomMetaDataField updateCustomMetaDataFields( - CustomMetaDataFieldUpdateRequest customMetaDataFieldUpdateRequest) - throws BadRequestException, NotFoundException, UnknownException { - return restClient.updateCustomMetaDataFields(customMetaDataFieldUpdateRequest); - } - - /** - * - * @param deleteFileVersionRequest class - * @return Result class - */ - public ResultNoContent deleteFileVersion(DeleteFileVersionRequest deleteFileVersionRequest) - throws BadRequestException, NotFoundException, InternalServerException, UnknownException, - ForbiddenException, TooManyRequestsException, UnauthorizedException { - return restClient.deleteFileVersion(deleteFileVersionRequest); - } - - /** - * - * @param copyFileRequest class - * @return Result class - */ - public ResultNoContent copyFile(CopyFileRequest copyFileRequest) - throws NotFoundException, BadRequestException, InternalServerException, UnknownException, - ForbiddenException, TooManyRequestsException, UnauthorizedException { - return restClient.copyFile(copyFileRequest); - } - - /** - * - * @param moveFileRequest class - * @return Result class - */ - public ResultNoContent moveFile(MoveFileRequest moveFileRequest) - throws NotFoundException, BadRequestException, InternalServerException, UnknownException, - ForbiddenException, TooManyRequestsException, UnauthorizedException { - return restClient.moveFile(moveFileRequest); - } - - /** - * - * @param renameFileRequest class - * @return Result class - */ - public ResultRenameFile renameFile(RenameFileRequest renameFileRequest) throws ConflictException, - PartialSuccessException, NotFoundException, BadRequestException, InternalServerException, UnknownException, - ForbiddenException, TooManyRequestsException, UnauthorizedException { - return restClient.renameFile(renameFileRequest); - } - - /** - * - * @param fileId & versionId - * @return a Result class - */ - public Result restoreFileVersion(String fileId, String versionId) - throws NotFoundException, BadRequestException, InternalServerException, UnknownException, - ForbiddenException, TooManyRequestsException, UnauthorizedException { - return restClient.restoreFileVersion(fileId, versionId); - } - - /** - * - * @param createFolderRequest which contains folderPath that is full path to the - * folder you want to delete - * @return Result class - */ - public ResultEmptyBlock createFolder(CreateFolderRequest createFolderRequest) throws UnknownException { - return restClient.createFolder(createFolderRequest); - } - - /** - * - * @param deleteFolderRequest which contains folderPath that is full path to the - * folder you want to delete - * @return Result class - */ - public ResultNoContent deleteFolder(DeleteFolderRequest deleteFolderRequest) - throws NotFoundException, BadRequestException, InternalServerException, UnknownException, - ForbiddenException, TooManyRequestsException, UnauthorizedException { - return restClient.deleteFolder(deleteFolderRequest); - } - - /** - * - * @param copyFolderRequest that contains sourceFolderPath, destinationPath, - * includeFileVersions - * @return Result class - */ - public ResultOfFolderActions copyFolder(CopyFolderRequest copyFolderRequest) - throws NotFoundException, BadRequestException, InternalServerException, UnknownException, - ForbiddenException, TooManyRequestsException, UnauthorizedException { - return restClient.copyFolder(copyFolderRequest); - } - - /** - * - * @param moveFolderRequest that contains sourceFolderPath, destinationPath - * @return Result class - */ - public ResultOfFolderActions moveFolder(MoveFolderRequest moveFolderRequest) - throws NotFoundException, BadRequestException, InternalServerException, UnknownException, - ForbiddenException, TooManyRequestsException, UnauthorizedException { - return restClient.moveFolder(moveFolderRequest); - } - - /** - * - * @param jobId - * @return a Result class - */ - public ResultBulkJobStatus getBulkJobStatus(String jobId) throws ForbiddenException, TooManyRequestsException, - InternalServerException, UnauthorizedException, BadRequestException, UnknownException { - return restClient.getBulkJobStatus(jobId); - } - - /** - * - * @param fileId - * @return a Result class - */ - public ResultFileVersions getFileVersions(String fileId) - throws NotFoundException, BadRequestException, InternalServerException, UnknownException, - ForbiddenException, TooManyRequestsException, UnauthorizedException { - return restClient.getFileVersions(fileId); - } - - /** - * - * @param fileId & versionId - * @return a Result class - */ - public ResultFileVersionDetails getFileVersionDetails(String fileId, String versionId) - throws NotFoundException, BadRequestException, InternalServerException, UnknownException, - ForbiddenException, TooManyRequestsException, UnauthorizedException { - return restClient.getFileVersionDetails(fileId, versionId); - } -} diff --git a/imagekit-sdk/src/main/java/io/imagekit/sdk/config/Configuration.java b/imagekit-sdk/src/main/java/io/imagekit/sdk/config/Configuration.java deleted file mode 100644 index 4ff6c7c..0000000 --- a/imagekit-sdk/src/main/java/io/imagekit/sdk/config/Configuration.java +++ /dev/null @@ -1,63 +0,0 @@ -package io.imagekit.sdk.config; - -/** - * Configuration class contains sdk configuration - */ -public class Configuration { - private String publicKey; - private String privateKey; - private String urlEndpoint; - - public Configuration() { - - } - - public Configuration(String publicKey, String privateKey, String urlEndpoint) { - this.publicKey = publicKey; - this.privateKey = privateKey; - this.urlEndpoint = urlEndpoint; - } - - public String getPublicKey() { - return publicKey; - } - - public void setPublicKey(String publicKey) { - this.publicKey = publicKey; - } - - public String getPrivateKey() { - return privateKey; - } - - public void setPrivateKey(String privateKey) { - this.privateKey = privateKey; - } - - public String getUrlEndpoint() { - return urlEndpoint; - } - - public void setUrlEndpoint(String urlEndpoint) { - this.urlEndpoint = urlEndpoint; - } - - @Override - public String toString() { - return "Configuration{" + "publicKey='" + publicKey + '\'' + ", privateKey='" + privateKey + '\'' - + ", urlEndpoint='" + urlEndpoint + '\'' + '}'; - } - - public boolean validate() { - if (urlEndpoint == null) { - throw new RuntimeException("UrlEndpoint not found in config.properties"); - } - if (privateKey == null) { - throw new RuntimeException("PrivateKey not found in config.properties"); - } - if (publicKey == null) { - throw new RuntimeException("PublicKey not found in config.properties"); - } - return true; - } -} diff --git a/imagekit-sdk/src/main/java/io/imagekit/sdk/constants/Transformer.java b/imagekit-sdk/src/main/java/io/imagekit/sdk/constants/Transformer.java deleted file mode 100644 index 6e1ebc5..0000000 --- a/imagekit-sdk/src/main/java/io/imagekit/sdk/constants/Transformer.java +++ /dev/null @@ -1,86 +0,0 @@ -package io.imagekit.sdk.constants; - -import java.util.HashMap; -import java.util.Map; - -public class Transformer { - - private Map trans = new HashMap<>(); - private static Transformer transformer; - - public static synchronized Transformer getInstance() { - if (null != transformer) { - return transformer; - } - transformer = new Transformer(); - - transformer.trans.put("height", "h"); - transformer.trans.put("width", "w"); - transformer.trans.put("aspectRatio", "ar"); - transformer.trans.put("quality", "q"); - transformer.trans.put("crop", "c"); - transformer.trans.put("cropMode", "cm"); - transformer.trans.put("x", "x"); - transformer.trans.put("y", "y"); - transformer.trans.put("focus", "fo"); - transformer.trans.put("format", "f"); - transformer.trans.put("radius", "r"); - transformer.trans.put("background", "bg"); - transformer.trans.put("border", "b"); - transformer.trans.put("rotation", "rt"); - transformer.trans.put("blur", "bl"); - transformer.trans.put("named", "n"); - transformer.trans.put("overlayX", "ox"); - transformer.trans.put("overlayY", "oy"); - transformer.trans.put("overlayFocus", "ofo"); - transformer.trans.put("overlayHeight", "oh"); - transformer.trans.put("overlayWidth", "ow"); - transformer.trans.put("overlayImage", "oi"); - transformer.trans.put("overlayImageTrim", "oit"); - transformer.trans.put("overlayImageAspectRatio", "oiar"); - transformer.trans.put("overlayImageBackground", "oibg"); - transformer.trans.put("overlayImageBorder", "oib"); - transformer.trans.put("overlayImageDPR", "oidpr"); - transformer.trans.put("overlayImageQuality", "oiq"); - transformer.trans.put("overlayImageCropping", "oic"); - transformer.trans.put("overlayImageFocus", "oifo"); - transformer.trans.put("overlayText", "ot"); - transformer.trans.put("overlayTextFontSize", "ots"); - transformer.trans.put("overlayTextFontFamily", "otf"); - transformer.trans.put("overlayTextColor", "otc"); - transformer.trans.put("overlayTextTransparency", "oa"); - transformer.trans.put("overlayAlpha", "oa"); - transformer.trans.put("overlayTextTypography", "ott"); - transformer.trans.put("overlayBackground", "obg"); - transformer.trans.put("overlayTextEncoded", "ote"); - transformer.trans.put("overlayTextWidth", "otw"); - transformer.trans.put("overlayTextBackground", "otbg"); - transformer.trans.put("overlayTextPadding", "otp"); - transformer.trans.put("overlayTextInnerAlignment", "otia"); - transformer.trans.put("overlayRadius", "or"); - transformer.trans.put("progressive", "pr"); - transformer.trans.put("lossless", "lo"); - transformer.trans.put("trim", "t"); - transformer.trans.put("metadata", "md"); - transformer.trans.put("colorProfile", "cp"); - transformer.trans.put("defaultImage", "di"); - transformer.trans.put("dpr", "dpr"); - transformer.trans.put("effectSharpen", "e-sharpen"); - transformer.trans.put("effectUSM", "e-usm"); - transformer.trans.put("effectContrast", "e-contrast"); - transformer.trans.put("effectGray", "e-grayscale"); - transformer.trans.put("original", "orig"); - transformer.trans.put("raw", "raw"); - - return transformer; - } - - private Transformer() { - - } - - public String transform(String key) { - return this.trans.get(key) != null ? this.trans.get(key) : key; - } - -} diff --git a/imagekit-sdk/src/main/java/io/imagekit/sdk/constants/Version.java b/imagekit-sdk/src/main/java/io/imagekit/sdk/constants/Version.java deleted file mode 100644 index 1a6cbcc..0000000 --- a/imagekit-sdk/src/main/java/io/imagekit/sdk/constants/Version.java +++ /dev/null @@ -1,5 +0,0 @@ -package io.imagekit.sdk.constants; - -public class Version { - public static final String VERSION_CODE="java-2.0.1"; -} diff --git a/imagekit-sdk/src/main/java/io/imagekit/sdk/exceptions/BadRequestException.java b/imagekit-sdk/src/main/java/io/imagekit/sdk/exceptions/BadRequestException.java deleted file mode 100644 index ccaa72d..0000000 --- a/imagekit-sdk/src/main/java/io/imagekit/sdk/exceptions/BadRequestException.java +++ /dev/null @@ -1,32 +0,0 @@ -package io.imagekit.sdk.exceptions; - -import io.imagekit.sdk.models.ResponseMetaData; - -public class BadRequestException extends Exception { - - private String message; - private String help; - private ResponseMetaData responseMetaData; - - public ResponseMetaData getResponseMetaData() { - return responseMetaData; - } - - public void setResponseMetaData(ResponseMetaData responseMetaData) { - this.responseMetaData = responseMetaData; - } - - public BadRequestException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace, - String message1, String help, ResponseMetaData responseMetaData) { - super(message, cause, enableSuppression, writableStackTrace); - this.message = message1; - this.help = help; - this.responseMetaData = responseMetaData; - } - - @Override - public String toString() { - return "BadRequestException{" + "message='" + message + '\'' + ", help='" + help + '\'' + ", responseMetaData=" - + responseMetaData + '}'; - } -} diff --git a/imagekit-sdk/src/main/java/io/imagekit/sdk/exceptions/ConflictException.java b/imagekit-sdk/src/main/java/io/imagekit/sdk/exceptions/ConflictException.java deleted file mode 100644 index 2734bab..0000000 --- a/imagekit-sdk/src/main/java/io/imagekit/sdk/exceptions/ConflictException.java +++ /dev/null @@ -1,24 +0,0 @@ -package io.imagekit.sdk.exceptions; - -import io.imagekit.sdk.models.ResponseMetaData; - -public class ConflictException extends Exception { - - private String message; - private String help; - private ResponseMetaData responseMetaData; - - public ConflictException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace, - String message1, String help, ResponseMetaData responseMetaData) { - super(message, cause, enableSuppression, writableStackTrace); - this.message = message1; - this.help = help; - this.responseMetaData = responseMetaData; - } - - @Override - public String toString() { - return "ConflictException{" + "message='" + message + '\'' + ", help='" + help + '\'' + ", responseMetaData=" - + responseMetaData + '}'; - } -} diff --git a/imagekit-sdk/src/main/java/io/imagekit/sdk/exceptions/ForbiddenException.java b/imagekit-sdk/src/main/java/io/imagekit/sdk/exceptions/ForbiddenException.java deleted file mode 100644 index eb73cf6..0000000 --- a/imagekit-sdk/src/main/java/io/imagekit/sdk/exceptions/ForbiddenException.java +++ /dev/null @@ -1,32 +0,0 @@ -package io.imagekit.sdk.exceptions; - -import io.imagekit.sdk.models.ResponseMetaData; - -public class ForbiddenException extends Exception { - - private String message; - private String help; - private ResponseMetaData responseMetaData; - - public ForbiddenException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace, - String message1, String help, ResponseMetaData responseMetaData) { - super(message, cause, enableSuppression, writableStackTrace); - this.message = message1; - this.help = help; - this.responseMetaData = responseMetaData; - } - - public ResponseMetaData getResponseMetaData() { - return responseMetaData; - } - - public void setResponseMetaData(ResponseMetaData responseMetaData) { - this.responseMetaData = responseMetaData; - } - - @Override - public String toString() { - return "ForbiddenException{" + "message='" + message + '\'' + ", help='" + help + '\'' + ", responseMetaData=" - + responseMetaData + '}'; - } -} diff --git a/imagekit-sdk/src/main/java/io/imagekit/sdk/exceptions/InternalServerException.java b/imagekit-sdk/src/main/java/io/imagekit/sdk/exceptions/InternalServerException.java deleted file mode 100644 index 938c464..0000000 --- a/imagekit-sdk/src/main/java/io/imagekit/sdk/exceptions/InternalServerException.java +++ /dev/null @@ -1,32 +0,0 @@ -package io.imagekit.sdk.exceptions; - -import io.imagekit.sdk.models.ResponseMetaData; - -public class InternalServerException extends Exception { - - private String message; - private String help; - private ResponseMetaData responseMetaData; - - public InternalServerException(String message, Throwable cause, boolean enableSuppression, - boolean writableStackTrace, String message1, String help, ResponseMetaData responseMetaData) { - super(message, cause, enableSuppression, writableStackTrace); - this.message = message1; - this.help = help; - this.responseMetaData = responseMetaData; - } - - public ResponseMetaData getResponseMetaData() { - return responseMetaData; - } - - public void setResponseMetaData(ResponseMetaData responseMetaData) { - this.responseMetaData = responseMetaData; - } - - @Override - public String toString() { - return "InternalServerException{" + "message='" + message + '\'' + ", help='" + help + '\'' - + ", responseMetaData=" + responseMetaData + '}'; - } -} diff --git a/imagekit-sdk/src/main/java/io/imagekit/sdk/exceptions/NotFoundException.java b/imagekit-sdk/src/main/java/io/imagekit/sdk/exceptions/NotFoundException.java deleted file mode 100644 index a3b446c..0000000 --- a/imagekit-sdk/src/main/java/io/imagekit/sdk/exceptions/NotFoundException.java +++ /dev/null @@ -1,32 +0,0 @@ -package io.imagekit.sdk.exceptions; - -import io.imagekit.sdk.models.ResponseMetaData; - -public class NotFoundException extends Exception { - - private String message; - private String help; - private ResponseMetaData responseMetaData; - - public NotFoundException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace, - String message1, String help, ResponseMetaData responseMetaData) { - super(message, cause, enableSuppression, writableStackTrace); - this.message = message1; - this.help = help; - this.responseMetaData = responseMetaData; - } - - public ResponseMetaData getResponseMetaData() { - return responseMetaData; - } - - public void setResponseMetaData(ResponseMetaData responseMetaData) { - this.responseMetaData = responseMetaData; - } - - @Override - public String toString() { - return "NotFoundException{" + "message='" + message + '\'' + ", help='" + help + '\'' + ", responseMetaData=" - + responseMetaData + '}'; - } -} diff --git a/imagekit-sdk/src/main/java/io/imagekit/sdk/exceptions/PartialSuccessException.java b/imagekit-sdk/src/main/java/io/imagekit/sdk/exceptions/PartialSuccessException.java deleted file mode 100644 index 22e318c..0000000 --- a/imagekit-sdk/src/main/java/io/imagekit/sdk/exceptions/PartialSuccessException.java +++ /dev/null @@ -1,32 +0,0 @@ -package io.imagekit.sdk.exceptions; - -import io.imagekit.sdk.models.ResponseMetaData; - -public class PartialSuccessException extends Exception { - - private String message; - private String help; - private ResponseMetaData responseMetaData; - - public PartialSuccessException(String message, Throwable cause, boolean enableSuppression, - boolean writableStackTrace, String message1, String help, ResponseMetaData responseMetaData) { - super(message, cause, enableSuppression, writableStackTrace); - this.message = message1; - this.help = help; - this.responseMetaData = responseMetaData; - } - - public ResponseMetaData getResponseMetaData() { - return responseMetaData; - } - - public void setResponseMetaData(ResponseMetaData responseMetaData) { - this.responseMetaData = responseMetaData; - } - - @Override - public String toString() { - return "PartialSuccessException{" + "message='" + message + '\'' + ", help='" + help + '\'' - + ", responseMetaData=" + responseMetaData + '}'; - } -} diff --git a/imagekit-sdk/src/main/java/io/imagekit/sdk/exceptions/TooManyRequestsException.java b/imagekit-sdk/src/main/java/io/imagekit/sdk/exceptions/TooManyRequestsException.java deleted file mode 100644 index fcdf837..0000000 --- a/imagekit-sdk/src/main/java/io/imagekit/sdk/exceptions/TooManyRequestsException.java +++ /dev/null @@ -1,32 +0,0 @@ -package io.imagekit.sdk.exceptions; - -import io.imagekit.sdk.models.ResponseMetaData; - -public class TooManyRequestsException extends Exception { - - private String message; - private String help; - private ResponseMetaData responseMetaData; - - public TooManyRequestsException(String message, Throwable cause, boolean enableSuppression, - boolean writableStackTrace, String message1, String help, ResponseMetaData responseMetaData) { - super(message, cause, enableSuppression, writableStackTrace); - this.message = message1; - this.help = help; - this.responseMetaData = responseMetaData; - } - - public ResponseMetaData getResponseMetaData() { - return responseMetaData; - } - - public void setResponseMetaData(ResponseMetaData responseMetaData) { - this.responseMetaData = responseMetaData; - } - - @Override - public String toString() { - return "TooManyRequestsException{" + "message='" + message + '\'' + ", help='" + help + '\'' - + ", responseMetaData=" + responseMetaData + '}'; - } -} diff --git a/imagekit-sdk/src/main/java/io/imagekit/sdk/exceptions/UnauthorizedException.java b/imagekit-sdk/src/main/java/io/imagekit/sdk/exceptions/UnauthorizedException.java deleted file mode 100644 index e785dab..0000000 --- a/imagekit-sdk/src/main/java/io/imagekit/sdk/exceptions/UnauthorizedException.java +++ /dev/null @@ -1,32 +0,0 @@ -package io.imagekit.sdk.exceptions; - -import io.imagekit.sdk.models.ResponseMetaData; - -public class UnauthorizedException extends Exception { - - private String message; - private String help; - private ResponseMetaData responseMetaData; - - public UnauthorizedException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace, - String message1, String help, ResponseMetaData responseMetaData) { - super(message, cause, enableSuppression, writableStackTrace); - this.message = message1; - this.help = help; - this.responseMetaData = responseMetaData; - } - - public ResponseMetaData getResponseMetaData() { - return responseMetaData; - } - - public void setResponseMetaData(ResponseMetaData responseMetaData) { - this.responseMetaData = responseMetaData; - } - - @Override - public String toString() { - return "UnauthorizedException{" + "message='" + message + '\'' + ", help='" + help + '\'' - + ", responseMetaData=" + responseMetaData + '}'; - } -} diff --git a/imagekit-sdk/src/main/java/io/imagekit/sdk/exceptions/UnknownException.java b/imagekit-sdk/src/main/java/io/imagekit/sdk/exceptions/UnknownException.java deleted file mode 100644 index 0a9a1f1..0000000 --- a/imagekit-sdk/src/main/java/io/imagekit/sdk/exceptions/UnknownException.java +++ /dev/null @@ -1,36 +0,0 @@ -package io.imagekit.sdk.exceptions; - -import io.imagekit.sdk.models.ResponseMetaData; - -public class UnknownException extends Exception { - - private String message; - private String help; - private ResponseMetaData responseMetaData; - - public UnknownException(String message, Throwable cause) { - super(message, cause); - } - - public UnknownException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace, - String message1, String help, ResponseMetaData responseMetaData) { - super(message, cause, enableSuppression, writableStackTrace); - this.message = message1; - this.help = help; - this.responseMetaData = responseMetaData; - } - - public ResponseMetaData getResponseMetaData() { - return responseMetaData; - } - - public void setResponseMetaData(ResponseMetaData responseMetaData) { - this.responseMetaData = responseMetaData; - } - - @Override - public String toString() { - return "UnknownException{" + "message='" + message + '\'' + ", help='" + help + '\'' + ", responseMetaData=" - + responseMetaData + '}'; - } -} diff --git a/imagekit-sdk/src/main/java/io/imagekit/sdk/models/AITagsRequest.java b/imagekit-sdk/src/main/java/io/imagekit/sdk/models/AITagsRequest.java deleted file mode 100644 index fb2c714..0000000 --- a/imagekit-sdk/src/main/java/io/imagekit/sdk/models/AITagsRequest.java +++ /dev/null @@ -1,29 +0,0 @@ -package io.imagekit.sdk.models; - -import java.util.List; - -public class AITagsRequest { - public List fileIds; - public List AITags; - - public List getFileIds() { - return fileIds; - } - - public void setFileIds(List fileIds) { - this.fileIds = fileIds; - } - - public List getAITags() { - return AITags; - } - - public void setAITags(List AITags) { - this.AITags = AITags; - } - - @Override - public String toString() { - return "AITagsRequest{" + "fileIds=" + fileIds + ", AITags=" + AITags + '}'; - } -} diff --git a/imagekit-sdk/src/main/java/io/imagekit/sdk/models/BaseFile.java b/imagekit-sdk/src/main/java/io/imagekit/sdk/models/BaseFile.java deleted file mode 100644 index 3161e5f..0000000 --- a/imagekit-sdk/src/main/java/io/imagekit/sdk/models/BaseFile.java +++ /dev/null @@ -1,253 +0,0 @@ -package io.imagekit.sdk.models; - -import com.google.gson.JsonArray; -import com.google.gson.JsonElement; - -import java.util.Date; -import java.util.List; - -public class BaseFile { - protected String fileId; - protected String name; - protected String url; - protected String thumbnail; - protected int height; - protected int width; - protected long size; - protected String filePath; - protected List tags; - protected boolean isPrivateFile; - protected String customCoordinates; - protected String fileType; - protected JsonArray aiTags; - protected JsonElement versionInfo; - protected JsonElement customMetadata; - - protected JsonElement embeddedMetadata; - protected JsonElement extensionStatus; - protected String type; - protected String mime; - protected Boolean hasAlpha; - protected Date createdAt; - protected Date updatedAt; - - public BaseFile() { - } - - public BaseFile(String fileId, String name, String url, String thumbnail, int height, int width, long size, - String filePath, List tags, boolean isPrivateFile, String customCoordinates, String fileType, - JsonArray aiTags, JsonElement versionInfo, JsonElement customMetadata, JsonElement embeddedMetadata, - JsonElement extensionStatus, String type, String mime, Boolean hasAlpha, Date createdAt, Date updatedAt) { - this.fileId = fileId; - this.name = name; - this.url = url; - this.thumbnail = thumbnail; - this.height = height; - this.width = width; - this.size = size; - this.filePath = filePath; - this.tags = tags; - this.isPrivateFile = isPrivateFile; - this.customCoordinates = customCoordinates; - this.fileType = fileType; - this.aiTags = aiTags; - this.versionInfo = versionInfo; - this.customMetadata = customMetadata; - this.embeddedMetadata = embeddedMetadata; - this.extensionStatus = extensionStatus; - this.type = type; - this.mime = mime; - this.hasAlpha = hasAlpha; - this.createdAt = createdAt; - this.updatedAt = updatedAt; - } - - public String getFileId() { - return fileId; - } - - public void setFileId(String fileId) { - this.fileId = fileId; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getUrl() { - return url; - } - - public void setUrl(String url) { - this.url = url; - } - - public String getThumbnail() { - return thumbnail; - } - - public void setThumbnail(String thumbnail) { - this.thumbnail = thumbnail; - } - - public int getHeight() { - return height; - } - - public void setHeight(int height) { - this.height = height; - } - - public int getWidth() { - return width; - } - - public void setWidth(int width) { - this.width = width; - } - - public long getSize() { - return size; - } - - public void setSize(long size) { - this.size = size; - } - - public String getFilePath() { - return filePath; - } - - public void setFilePath(String filePath) { - this.filePath = filePath; - } - - public List getTags() { - return tags; - } - - public void setTags(List tags) { - this.tags = tags; - } - - public boolean isPrivateFile() { - return isPrivateFile; - } - - public void setPrivateFile(boolean privateFile) { - isPrivateFile = privateFile; - } - - public String getCustomCoordinates() { - return customCoordinates; - } - - public void setCustomCoordinates(String customCoordinates) { - this.customCoordinates = customCoordinates; - } - - public String getFileType() { - return fileType; - } - - public void setFileType(String fileType) { - this.fileType = fileType; - } - - public JsonArray getAiTags() { - return aiTags; - } - - public void setAiTags(JsonArray aiTags) { - this.aiTags = aiTags; - } - - public JsonElement getVersionInfo() { - return versionInfo; - } - - public void setVersionInfo(JsonElement versionInfo) { - this.versionInfo = versionInfo; - } - - public JsonElement getCustomMetadata() { - return customMetadata; - } - - public void setCustomMetadata(JsonElement customMetadata) { - this.customMetadata = customMetadata; - } - - public JsonElement getEmbeddedMetadata() { - return embeddedMetadata; - } - - public void setEmbeddedMetadata(JsonElement embeddedMetadata) { - this.embeddedMetadata = embeddedMetadata; - } - - public JsonElement getExtensionStatus() { - return extensionStatus; - } - - public void setExtensionStatus(JsonElement extensionStatus) { - this.extensionStatus = extensionStatus; - } - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - public String getMime() { - return mime; - } - - public void setMime(String mime) { - this.mime = mime; - } - - public Boolean getHasAlpha() { - return hasAlpha; - } - - public void setHasAlpha(Boolean hasAlpha) { - this.hasAlpha = hasAlpha; - } - - public Date getCreatedAt() { - return createdAt; - } - - public void setCreatedAt(Date createdAt) { - this.createdAt = createdAt; - } - - public Date getUpdatedAt() { - return updatedAt; - } - - public void setUpdatedAt(Date updatedAt) { - this.updatedAt = updatedAt; - } - - @Override - public String toString() { - return "BaseFile{" + "fileId='" + fileId + '\'' + ", name='" + name + '\'' + ", url='" + url + '\'' - + ", thumbnail='" + thumbnail + '\'' + ", height=" + height + ", width=" + width + ", size=" + size - + ", filePath='" + filePath + '\'' + ", tags='" + tags + '\'' + ", isPrivateFile=" + isPrivateFile - + ", customCoordinates='" + customCoordinates + '\'' + ", fileType='" + fileType + '\'' + ", aiTags=" - + aiTags + ", versionInfo=" + versionInfo + ", customMetadata=" + customMetadata + ", embeddedMetadata=" - + embeddedMetadata + ", extensionStatus=" + extensionStatus + ", type='" + type + '\'' + ", mime='" - + mime + '\'' + ", hasAlpha=" + hasAlpha + ", createdAt=" + createdAt + ", updatedAt=" + updatedAt - + '}'; - } - -} diff --git a/imagekit-sdk/src/main/java/io/imagekit/sdk/models/CopyFileRequest.java b/imagekit-sdk/src/main/java/io/imagekit/sdk/models/CopyFileRequest.java deleted file mode 100644 index b915ce1..0000000 --- a/imagekit-sdk/src/main/java/io/imagekit/sdk/models/CopyFileRequest.java +++ /dev/null @@ -1,37 +0,0 @@ -package io.imagekit.sdk.models; - -public class CopyFileRequest { - public String sourceFilePath; - public String destinationPath; - public Boolean includeFileVersions; - - public String getSourceFilePath() { - return sourceFilePath; - } - - public void setSourceFilePath(String sourceFilePath) { - this.sourceFilePath = sourceFilePath; - } - - public String getDestinationPath() { - return destinationPath; - } - - public void setDestinationPath(String destinationPath) { - this.destinationPath = destinationPath; - } - - public Boolean getIncludeFileVersions() { - return includeFileVersions; - } - - public void setIncludeFileVersions(Boolean includeFileVersions) { - this.includeFileVersions = includeFileVersions; - } - - @Override - public String toString() { - return "CopyFileRequest{" + "sourceFilePath=" + sourceFilePath + ", destinationPath=" + destinationPath - + ", includeFileVersions=" + includeFileVersions + '}'; - } -} diff --git a/imagekit-sdk/src/main/java/io/imagekit/sdk/models/CopyFolderRequest.java b/imagekit-sdk/src/main/java/io/imagekit/sdk/models/CopyFolderRequest.java deleted file mode 100644 index 0938fd5..0000000 --- a/imagekit-sdk/src/main/java/io/imagekit/sdk/models/CopyFolderRequest.java +++ /dev/null @@ -1,37 +0,0 @@ -package io.imagekit.sdk.models; - -public class CopyFolderRequest { - public String sourceFolderPath; - public String destinationPath; - public Boolean includeFileVersions; - - public String getSourceFolderPath() { - return sourceFolderPath; - } - - public void setSourceFolderPath(String sourceFolderPath) { - this.sourceFolderPath = sourceFolderPath; - } - - public String getDestinationPath() { - return destinationPath; - } - - public void setDestinationPath(String destinationPath) { - this.destinationPath = destinationPath; - } - - public Boolean getIncludeFileVersions() { - return includeFileVersions; - } - - public void setIncludeFileVersions(Boolean includeFileVersions) { - this.includeFileVersions = includeFileVersions; - } - - @Override - public String toString() { - return "CopyFolderRequest{" + "sourceFolderPath=" + sourceFolderPath + ", destinationPath=" + destinationPath - + ", includeFileVersions=" + includeFileVersions + '}'; - } -} diff --git a/imagekit-sdk/src/main/java/io/imagekit/sdk/models/CreateFolderRequest.java b/imagekit-sdk/src/main/java/io/imagekit/sdk/models/CreateFolderRequest.java deleted file mode 100644 index 077d8d2..0000000 --- a/imagekit-sdk/src/main/java/io/imagekit/sdk/models/CreateFolderRequest.java +++ /dev/null @@ -1,27 +0,0 @@ -package io.imagekit.sdk.models; - -public class CreateFolderRequest { - public String folderName; - public String parentFolderPath; - - public String getFolderName() { - return folderName; - } - - public void setFolderName(String folderName) { - this.folderName = folderName; - } - - public String getParentFolderPath() { - return parentFolderPath; - } - - public void setParentFolderPath(String parentFolderPath) { - this.parentFolderPath = parentFolderPath; - } - - @Override - public String toString() { - return "DeleteFolderRequest{" + "folderName=" + folderName + "parentFolderPath=" + parentFolderPath + '}'; - } -} diff --git a/imagekit-sdk/src/main/java/io/imagekit/sdk/models/CustomMetaDataFieldCreateRequest.java b/imagekit-sdk/src/main/java/io/imagekit/sdk/models/CustomMetaDataFieldCreateRequest.java deleted file mode 100644 index fc6d3a0..0000000 --- a/imagekit-sdk/src/main/java/io/imagekit/sdk/models/CustomMetaDataFieldCreateRequest.java +++ /dev/null @@ -1,41 +0,0 @@ -package io.imagekit.sdk.models; - -public class CustomMetaDataFieldCreateRequest { - private String name; - private String label; - private CustomMetaDataFieldSchemaObject schema = new CustomMetaDataFieldSchemaObject(); - - public CustomMetaDataFieldCreateRequest() { - - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getLabel() { - return label; - } - - public void setLabel(String label) { - this.label = label; - } - - public CustomMetaDataFieldSchemaObject getSchema() { - return schema; - } - - public void setSchema(CustomMetaDataFieldSchemaObject schema) { - this.schema = schema; - } - - @Override - public String toString() { - return "CustomMetaDataFieldRequest{" + "name=" + '"' + name + '"' + ", label=" + '"' + label + '"' + ", schema=" - + schema + '}'; - } -} diff --git a/imagekit-sdk/src/main/java/io/imagekit/sdk/models/CustomMetaDataFieldSchemaObject.java b/imagekit-sdk/src/main/java/io/imagekit/sdk/models/CustomMetaDataFieldSchemaObject.java deleted file mode 100644 index dc5b98f..0000000 --- a/imagekit-sdk/src/main/java/io/imagekit/sdk/models/CustomMetaDataFieldSchemaObject.java +++ /dev/null @@ -1,94 +0,0 @@ -package io.imagekit.sdk.models; - -public class CustomMetaDataFieldSchemaObject { - private CustomMetaDataTypeEnum type; - private Object selectOptions; - private Object defaultValue; - private Boolean isValueRequired; - private Object minValue; - private Object maxValue; - private Integer minLength; - private Integer maxLength; - - public CustomMetaDataFieldSchemaObject() { - - } - - public CustomMetaDataTypeEnum getType() { - return type; - } - - public void setType(CustomMetaDataTypeEnum type) { - this.type = type; - } - - public Object getSelectOptions() { - return selectOptions; - } - - public void setSelectOptions(Object selectOptions) { - this.selectOptions = selectOptions; - } - - public Object getDefaultValue() { - return defaultValue; - } - - public void setDefaultValue(Object defaultValue) { - this.defaultValue = defaultValue; - } - - public Boolean getValueRequired() { - return isValueRequired; - } - - public void setValueRequired(Boolean valueRequired) { - isValueRequired = valueRequired; - } - - public Object getMinValue() { - return minValue; - } - - public void setMinValue(Object minValue) { - this.minValue = minValue; - } - - public Object getMaxValue() { - return maxValue; - } - - public void setMaxValue(Object maxValue) { - this.maxValue = maxValue; - } - - public Integer getMinLength() { - return minLength; - } - - public void setMinLength(Integer minLength) { - this.minLength = minLength; - } - - public Integer getMaxLength() { - return maxLength; - } - - public void setMaxLength(Integer maxLength) { - this.maxLength = maxLength; - } - - @Override - public String toString() { - return "CustomMetaDataFieldSchemaObject{" + - "type=" + type + - ", selectOptions=" + selectOptions + - ", defaultValue=" + defaultValue + - ", isValueRequired=" + isValueRequired + - ", minValue=" + minValue + - ", maxValue=" + maxValue + - ", minLength=" + minLength + - ", maxLength=" + maxLength + - '}'; - } -} diff --git a/imagekit-sdk/src/main/java/io/imagekit/sdk/models/CustomMetaDataFieldUpdateRequest.java b/imagekit-sdk/src/main/java/io/imagekit/sdk/models/CustomMetaDataFieldUpdateRequest.java deleted file mode 100644 index 6945a8e..0000000 --- a/imagekit-sdk/src/main/java/io/imagekit/sdk/models/CustomMetaDataFieldUpdateRequest.java +++ /dev/null @@ -1,41 +0,0 @@ -package io.imagekit.sdk.models; - -public class CustomMetaDataFieldUpdateRequest { - private String id; - private String label; - private CustomMetaDataFieldSchemaObject schema = new CustomMetaDataFieldSchemaObject(); - - public CustomMetaDataFieldUpdateRequest() { - - } - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public String getLabel() { - return label; - } - - public void setLabel(String label) { - this.label = label; - } - - public CustomMetaDataFieldSchemaObject getSchema() { - return schema; - } - - public void setSchema(CustomMetaDataFieldSchemaObject schema) { - this.schema = schema; - } - - @Override - public String toString() { - return "CustomMetaDataFieldRequest{" + "id=" + '"' + id + '"' + ", label=" + '"' + label + '"' + ", schema=" - + schema + '}'; - } -} diff --git a/imagekit-sdk/src/main/java/io/imagekit/sdk/models/CustomMetaDataTypeEnum.java b/imagekit-sdk/src/main/java/io/imagekit/sdk/models/CustomMetaDataTypeEnum.java deleted file mode 100644 index 97c0e24..0000000 --- a/imagekit-sdk/src/main/java/io/imagekit/sdk/models/CustomMetaDataTypeEnum.java +++ /dev/null @@ -1,5 +0,0 @@ -package io.imagekit.sdk.models; -public enum CustomMetaDataTypeEnum { - Text, Textarea, Number, Date, Boolean, SingleSelect, MultiSelect; - -} diff --git a/imagekit-sdk/src/main/java/io/imagekit/sdk/models/DeleteFileVersionRequest.java b/imagekit-sdk/src/main/java/io/imagekit/sdk/models/DeleteFileVersionRequest.java deleted file mode 100644 index 8b5b3e3..0000000 --- a/imagekit-sdk/src/main/java/io/imagekit/sdk/models/DeleteFileVersionRequest.java +++ /dev/null @@ -1,27 +0,0 @@ -package io.imagekit.sdk.models; - -public class DeleteFileVersionRequest { - public String fileId; - public String versionId; - - public String getFileId() { - return fileId; - } - - public void setFileId(String fileId) { - this.fileId = fileId; - } - - public String getVersionId() { - return versionId; - } - - public void setVersionId(String versionId) { - this.versionId = versionId; - } - - @Override - public String toString() { - return "DeleteFileVersionRequest{" + "fileId='" + fileId + '\'' + ", versionId='" + versionId + '\'' + '}'; - } -} diff --git a/imagekit-sdk/src/main/java/io/imagekit/sdk/models/DeleteFolderRequest.java b/imagekit-sdk/src/main/java/io/imagekit/sdk/models/DeleteFolderRequest.java deleted file mode 100644 index 2447fdf..0000000 --- a/imagekit-sdk/src/main/java/io/imagekit/sdk/models/DeleteFolderRequest.java +++ /dev/null @@ -1,18 +0,0 @@ -package io.imagekit.sdk.models; - -public class DeleteFolderRequest { - public String folderPath; - - public String getFolderPath() { - return folderPath; - } - - public void setFolderPath(String folderPath) { - this.folderPath = folderPath; - } - - @Override - public String toString() { - return "DeleteFolderRequest{" + "folderPath=" + folderPath + '}'; - } -} diff --git a/imagekit-sdk/src/main/java/io/imagekit/sdk/models/FileCreateRequest.java b/imagekit-sdk/src/main/java/io/imagekit/sdk/models/FileCreateRequest.java deleted file mode 100644 index 4b39425..0000000 --- a/imagekit-sdk/src/main/java/io/imagekit/sdk/models/FileCreateRequest.java +++ /dev/null @@ -1,172 +0,0 @@ -package io.imagekit.sdk.models; - -import com.google.gson.JsonArray; -import com.google.gson.JsonObject; - -import io.imagekit.sdk.utils.Utils; -import okhttp3.MediaType; -import okhttp3.MultipartBody; -import okhttp3.RequestBody; - -import java.net.URL; -import java.util.List; - -public class FileCreateRequest { - public URL url; - public String base64; - public byte[] bytes; - public String fileName; - public boolean useUniqueFileName; - public List tags; - public String folder; - public boolean isPrivateFile; - public String customCoordinates; - public List responseFields; - public JsonArray extensions; - public String webhookUrl; - public Boolean overwriteFile; - public Boolean overwriteAITags; - public Boolean overwriteTags; - public Boolean overwriteCustomMetadata; - public JsonObject customMetadata; - - public FileCreateRequest(URL url, String fileName) { - this.url = url; - this.fileName = fileName; - this.useUniqueFileName = true; - } - - public FileCreateRequest(String base64, String fileName) { - this.base64 = base64; - this.fileName = fileName; - this.useUniqueFileName = true; - } - - public FileCreateRequest(byte[] bytes, String fileName) { - this.bytes = bytes; - this.fileName = fileName; - this.useUniqueFileName = true; - } - - public String getFileName() { - return fileName; - } - - public void setFileName(String fileName) { - this.fileName = fileName; - } - - public boolean isUseUniqueFileName() { - return useUniqueFileName; - } - - public void setUseUniqueFileName(boolean useUniqueFileName) { - this.useUniqueFileName = useUniqueFileName; - } - - public List getTags() { - return tags; - } - - public void setTags(List tags) { - this.tags = tags; - } - - public String getFolder() { - return folder; - } - - public void setFolder(String folder) { - this.folder = folder; - } - - public boolean isPrivateFile() { - return isPrivateFile; - } - - public void setPrivateFile(boolean privateFile) { - isPrivateFile = privateFile; - } - - public String getCustomCoordinates() { - return customCoordinates; - } - - public void setCustomCoordinates(String customCoordinates) { - this.customCoordinates = customCoordinates; - } - - public List getResponseFields() { - return responseFields; - } - - public void setResponseFields(List responseFields) { - this.responseFields = responseFields; - } - - public JsonArray getExtensions() { - return extensions; - } - - public void setExtensions(JsonArray extensions) { - this.extensions = extensions; - } - - public String getWebhookUrl() { - return webhookUrl; - } - - public void setWebhookUrl(String webhookUrl) { - this.webhookUrl = webhookUrl; - } - - public Boolean isOverwriteFile() { - return overwriteFile; - } - - public void setOverwriteFile(Boolean overwriteFile) { - this.overwriteFile = overwriteFile; - } - - public Boolean isOverwriteAITags() { - return overwriteAITags; - } - - public void setOverwriteAITags(Boolean overwriteAITags) { - this.overwriteAITags = overwriteAITags; - } - - public Boolean isOverwriteTags() { - return overwriteTags; - } - - public void setOverwriteTags(Boolean overwriteTags) { - this.overwriteTags = overwriteTags; - } - - public Boolean isOverwriteCustomMetadata() { - return overwriteCustomMetadata; - } - - public void setOverwriteCustomMetadata(Boolean overwriteCustomMetadata) { - this.overwriteCustomMetadata = overwriteCustomMetadata; - } - - public JsonObject getCustomMetadata() { - return customMetadata; - } - - public void setCustomMetadata(JsonObject customMetadata) { - this.customMetadata = customMetadata; - } - - @Override - public String toString() { - return "FileCreateRequest{" + "fileName='" + fileName + '\'' + ", useUniqueFileName=" + useUniqueFileName - + ", tags=" + tags + ", folder='" + folder + '\'' + ", isPrivateFile=" + isPrivateFile - + ", customCoordinates=" + customCoordinates + ", responseFields=" + responseFields + ", extensions=" - + extensions + ", webhookUrl='" + webhookUrl + '\'' + ", overwriteFile=" + overwriteFile - + ", overwriteAITags=" + overwriteAITags + ", overwriteTags=" + overwriteTags - + ", overwriteCustomMetadata=" + overwriteCustomMetadata + ", customMetadata=" + customMetadata + '}'; - } -} diff --git a/imagekit-sdk/src/main/java/io/imagekit/sdk/models/FileUpdateRequest.java b/imagekit-sdk/src/main/java/io/imagekit/sdk/models/FileUpdateRequest.java deleted file mode 100644 index a263657..0000000 --- a/imagekit-sdk/src/main/java/io/imagekit/sdk/models/FileUpdateRequest.java +++ /dev/null @@ -1,93 +0,0 @@ -package io.imagekit.sdk.models; - -import com.google.gson.JsonArray; -import com.google.gson.JsonObject; - -import java.util.List; - -public class FileUpdateRequest { - private String fileId; - public List removeAITags; - - public String webhookUrl; - - public JsonArray extensions; - - private List tags; - private String customCoordinates; - - public JsonObject customMetadata; - - public FileUpdateRequest(String fileId) { - this.fileId = fileId; - } - - public String getFileId() { - return fileId; - } - - public void setFileId(String fileId) { - this.fileId = fileId; - } - - public List getRemoveAITags() { - return removeAITags; - } - - public void setRemoveAITags(List removeAITags) { - this.removeAITags = removeAITags; - } - - public String getWebhookUrl() { - return webhookUrl; - } - - public void setWebhookUrl(String webhookUrl) { - this.webhookUrl = webhookUrl; - } - - public JsonArray getExtensions() { - return extensions; - } - - public void setExtensions(JsonArray extensions) { - this.extensions = extensions; - } - - public List getTags() { - return tags; - } - - public void setTags(List tags) { - this.tags = tags; - } - - public String getCustomCoordinates() { - return customCoordinates; - } - - public void setCustomCoordinates(String customCoordinates) { - this.customCoordinates = customCoordinates; - } - - public JsonObject getCustomMetadata() { - return customMetadata; - } - - public void setCustomMetadata(JsonObject customMetadata) { - this.customMetadata = customMetadata; - } - - @Override - public String toString() { - return "FileUpdateRequest{" + - "fileId='" + fileId + '\'' + - ", removeAITags=" + removeAITags + - ", webhookUrl='" + webhookUrl + '\'' + - ", extensions=" + extensions + - ", tags=" + tags + - ", customCoordinates='" + customCoordinates + '\'' + - ", customMetadata=" + customMetadata + - '}'; - } -} diff --git a/imagekit-sdk/src/main/java/io/imagekit/sdk/models/GetFileListRequest.java b/imagekit-sdk/src/main/java/io/imagekit/sdk/models/GetFileListRequest.java deleted file mode 100644 index 0727060..0000000 --- a/imagekit-sdk/src/main/java/io/imagekit/sdk/models/GetFileListRequest.java +++ /dev/null @@ -1,92 +0,0 @@ -package io.imagekit.sdk.models; - -import java.util.Arrays; - -public class GetFileListRequest { - public String type; - public String sort; - public String path; - public String searchQuery; - public String fileType; - public String limit; - public String skip; - public String[] tags; - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - public String getSort() { - return sort; - } - - public void setSort(String sort) { - this.sort = sort; - } - - public String getPath() { - return path; - } - - public void setPath(String path) { - this.path = path; - } - - public String getSearchQuery() { - return searchQuery; - } - - public void setSearchQuery(String searchQuery) { - this.searchQuery = searchQuery; - } - - public String getFileType() { - return fileType; - } - - public void setFileType(String fileType) { - this.fileType = fileType; - } - - public String getLimit() { - return limit; - } - - public void setLimit(String limit) { - this.limit = limit; - } - - public String getSkip() { - return skip; - } - - public void setSkip(String skip) { - this.skip = skip; - } - - public String[] getTags() { - return tags; - } - - public void setTags(String[] tags) { - this.tags = tags; - } - - @Override - public String toString() { - return "GetFileListRequest{" + - "type='" + type + '\'' + - ", sort='" + sort + '\'' + - ", path='" + path + '\'' + - ", searchQuery='" + searchQuery + '\'' + - ", fileType='" + fileType + '\'' + - ", limit='" + limit + '\'' + - ", skip='" + skip + '\'' + - ", tags=" + Arrays.toString(tags) + - '}'; - } -} diff --git a/imagekit-sdk/src/main/java/io/imagekit/sdk/models/MetaData.java b/imagekit-sdk/src/main/java/io/imagekit/sdk/models/MetaData.java deleted file mode 100644 index dd2603a..0000000 --- a/imagekit-sdk/src/main/java/io/imagekit/sdk/models/MetaData.java +++ /dev/null @@ -1,731 +0,0 @@ -package io.imagekit.sdk.models; - -import com.google.gson.JsonObject; - -import java.util.List; - -public class MetaData { - private float height; - private float width; - private float size; - private String format; - private boolean hasColorProfile; - private float quality; - private float density; - private boolean hasTransparency; - private String pHash; - EXIFObject exif; - - - // Getter Methods - - public float getHeight() { - return height; - } - - public float getWidth() { - return width; - } - - public float getSize() { - return size; - } - - public String getFormat() { - return format; - } - - public boolean getHasColorProfile() { - return hasColorProfile; - } - - public float getQuality() { - return quality; - } - - public float getDensity() { - return density; - } - - public boolean getHasTransparency() { - return hasTransparency; - } - - public String getPHash() { - return pHash; - } - - public EXIFObject getExif() { - return exif; - } - - // Setter Methods - - public void setHeight(float height) { - this.height = height; - } - - public void setWidth(float width) { - this.width = width; - } - - public void setSize(float size) { - this.size = size; - } - - public void setFormat(String format) { - this.format = format; - } - - public void setHasColorProfile(boolean hasColorProfile) { - this.hasColorProfile = hasColorProfile; - } - - public void setQuality(float quality) { - this.quality = quality; - } - - public void setDensity(float density) { - this.density = density; - } - - public void setHasTransparency(boolean hasTransparency) { - this.hasTransparency = hasTransparency; - } - - public void setPHash(String pHash) { - this.pHash = pHash; - } - - public void setExif(EXIFObject exifObject) { - this.exif = exifObject; - } - - @Override - public String toString() { - return "MetaData{" + - "height=" + height + - ", width=" + width + - ", size=" + size + - ", format='" + format + '\'' + - ", hasColorProfile=" + hasColorProfile + - ", quality=" + quality + - ", density=" + density + - ", hasTransparency=" + hasTransparency + - ", pHash='" + pHash + '\'' + - ", EXIF=" + exif + - '}'; - } - - public class EXIFObject { - private ImageObject image; - private Thumbnail thumbnail; - private Exif exif; - private GPS gps; - private Interoperability interoperability; - private JsonObject makernote; - - public EXIFObject() { - } - - public ImageObject getImage() { - return image; - } - - public void setImage(ImageObject image) { - this.image = image; - } - - public Thumbnail getThumbnail() { - return thumbnail; - } - - public void setThumbnail(Thumbnail thumbnail) { - this.thumbnail = thumbnail; - } - - public Exif getExif() { - return exif; - } - - public void setExif(Exif exif) { - this.exif = exif; - } - - public GPS getGps() { - return gps; - } - - public void setGps(GPS gps) { - this.gps = gps; - } - - public Interoperability getInteroperability() { - return interoperability; - } - - public void setInteroperability(Interoperability interoperability) { - this.interoperability = interoperability; - } - - public JsonObject getMakernote() { - return makernote; - } - - public void setMakernote(JsonObject makernote) { - this.makernote = makernote; - } - - @Override - public String toString() { - return "EXIFObject{" + - "image=" + image + - ", thumbnail=" + thumbnail + - ", exif=" + exif + - ", gps=" + gps + - ", interoperability=" + interoperability + - ", makernote=" + makernote + - '}'; - } - } - - public class ImageObject{ - private String Make; - private String Model; - private int Orientation; - private int XResolution; - private int YResolution; - private int ResolutionUnit; - private String Software; - private String ModifyDate; - private int YCbCrPositioning; - private int ExifOffset; - private int GPSInfo; - - public ImageObject() { - } - - public String getMake() { - return Make; - } - - public void setMake(String make) { - Make = make; - } - - public String getModel() { - return Model; - } - - public void setModel(String model) { - Model = model; - } - - public int getOrientation() { - return Orientation; - } - - public void setOrientation(int orientation) { - Orientation = orientation; - } - - public int getXResolution() { - return XResolution; - } - - public void setXResolution(int XResolution) { - this.XResolution = XResolution; - } - - public int getYResolution() { - return YResolution; - } - - public void setYResolution(int YResolution) { - this.YResolution = YResolution; - } - - public int getResolutionUnit() { - return ResolutionUnit; - } - - public void setResolutionUnit(int resolutionUnit) { - ResolutionUnit = resolutionUnit; - } - - public String getSoftware() { - return Software; - } - - public void setSoftware(String software) { - Software = software; - } - - public String getModifyDate() { - return ModifyDate; - } - - public void setModifyDate(String modifyDate) { - ModifyDate = modifyDate; - } - - public int getYCbCrPositioning() { - return YCbCrPositioning; - } - - public void setYCbCrPositioning(int YCbCrPositioning) { - this.YCbCrPositioning = YCbCrPositioning; - } - - public int getExifOffset() { - return ExifOffset; - } - - public void setExifOffset(int exifOffset) { - ExifOffset = exifOffset; - } - - public int getGPSInfo() { - return GPSInfo; - } - - public void setGPSInfo(int GPSInfo) { - this.GPSInfo = GPSInfo; - } - - @Override - public String toString() { - return "ImageObject{" + - "Make='" + Make + '\'' + - ", Model='" + Model + '\'' + - ", Orientation=" + Orientation + - ", XResolution=" + XResolution + - ", YResolution=" + YResolution + - ", ResolutionUnit=" + ResolutionUnit + - ", Software='" + Software + '\'' + - ", ModifyDate='" + ModifyDate + '\'' + - ", YCbCrPositioning=" + YCbCrPositioning + - ", ExifOffset=" + ExifOffset + - ", GPSInfo=" + GPSInfo + - '}'; - } - } - - public class Thumbnail{ - private int Compression; - private int XResolution; - private int YResolution; - private int ResolutionUnit; - private int ThumbnailOffset; - private int ThumbnailLength; - - public Thumbnail() { - } - - public int getCompression() { - return Compression; - } - - public void setCompression(int compression) { - Compression = compression; - } - - public int getXResolution() { - return XResolution; - } - - public void setXResolution(int XResolution) { - this.XResolution = XResolution; - } - - public int getYResolution() { - return YResolution; - } - - public void setYResolution(int YResolution) { - this.YResolution = YResolution; - } - - public int getResolutionUnit() { - return ResolutionUnit; - } - - public void setResolutionUnit(int resolutionUnit) { - ResolutionUnit = resolutionUnit; - } - - public int getThumbnailOffset() { - return ThumbnailOffset; - } - - public void setThumbnailOffset(int thumbnailOffset) { - ThumbnailOffset = thumbnailOffset; - } - - public int getThumbnailLength() { - return ThumbnailLength; - } - - public void setThumbnailLength(int thumbnailLength) { - ThumbnailLength = thumbnailLength; - } - - @Override - public String toString() { - return "Thumbnail{" + - "Compression=" + Compression + - ", XResolution=" + XResolution + - ", YResolution=" + YResolution + - ", ResolutionUnit=" + ResolutionUnit + - ", ThumbnailOffset=" + ThumbnailOffset + - ", ThumbnailLength=" + ThumbnailLength + - '}'; - } - } - - public class Exif{ - private double ExposureTime; - private double FNumber; - private int ExposureProgram; - private int ISO; - private String ExifVersion; - private String DateTimeOriginal; - private String CreateDate; - private double ShutterSpeedValue; - private double ApertureValue; - private int ExposureCompensation; - private int MeteringMode; - private int Flash; - private int FocalLength; - private String SubSecTime; - private String SubSecTimeOriginal; - private String SubSecTimeDigitized; - private String FlashpixVersion; - private int ColorSpace; - private int ExifImageWidth; - private int ExifImageHeight; - private int InteropOffset; - private double FocalPlaneXResolution; - private double FocalPlaneYResolution; - private int FocalPlaneResolutionUnit; - private int CustomRendered; - private int ExposureMode; - private int WhiteBalance; - private int SceneCaptureType; - - public Exif() { - } - - public double getExposureTime() { - return ExposureTime; - } - - public void setExposureTime(double exposureTime) { - ExposureTime = exposureTime; - } - - public double getFNumber() { - return FNumber; - } - - public void setFNumber(double FNumber) { - this.FNumber = FNumber; - } - - public int getExposureProgram() { - return ExposureProgram; - } - - public void setExposureProgram(int exposureProgram) { - ExposureProgram = exposureProgram; - } - - public int getISO() { - return ISO; - } - - public void setISO(int ISO) { - this.ISO = ISO; - } - - public String getExifVersion() { - return ExifVersion; - } - - public void setExifVersion(String exifVersion) { - ExifVersion = exifVersion; - } - - public String getDateTimeOriginal() { - return DateTimeOriginal; - } - - public void setDateTimeOriginal(String dateTimeOriginal) { - DateTimeOriginal = dateTimeOriginal; - } - - public String getCreateDate() { - return CreateDate; - } - - public void setCreateDate(String createDate) { - CreateDate = createDate; - } - - public double getShutterSpeedValue() { - return ShutterSpeedValue; - } - - public void setShutterSpeedValue(double shutterSpeedValue) { - ShutterSpeedValue = shutterSpeedValue; - } - - public double getApertureValue() { - return ApertureValue; - } - - public void setApertureValue(double apertureValue) { - ApertureValue = apertureValue; - } - - public int getExposureCompensation() { - return ExposureCompensation; - } - - public void setExposureCompensation(int exposureCompensation) { - ExposureCompensation = exposureCompensation; - } - - public int getMeteringMode() { - return MeteringMode; - } - - public void setMeteringMode(int meteringMode) { - MeteringMode = meteringMode; - } - - public int getFlash() { - return Flash; - } - - public void setFlash(int flash) { - Flash = flash; - } - - public int getFocalLength() { - return FocalLength; - } - - public void setFocalLength(int focalLength) { - FocalLength = focalLength; - } - - public String getSubSecTime() { - return SubSecTime; - } - - public void setSubSecTime(String subSecTime) { - SubSecTime = subSecTime; - } - - public String getSubSecTimeOriginal() { - return SubSecTimeOriginal; - } - - public void setSubSecTimeOriginal(String subSecTimeOriginal) { - SubSecTimeOriginal = subSecTimeOriginal; - } - - public String getSubSecTimeDigitized() { - return SubSecTimeDigitized; - } - - public void setSubSecTimeDigitized(String subSecTimeDigitized) { - SubSecTimeDigitized = subSecTimeDigitized; - } - - public String getFlashpixVersion() { - return FlashpixVersion; - } - - public void setFlashpixVersion(String flashpixVersion) { - FlashpixVersion = flashpixVersion; - } - - public int getColorSpace() { - return ColorSpace; - } - - public void setColorSpace(int colorSpace) { - ColorSpace = colorSpace; - } - - public int getExifImageWidth() { - return ExifImageWidth; - } - - public void setExifImageWidth(int exifImageWidth) { - ExifImageWidth = exifImageWidth; - } - - public int getExifImageHeight() { - return ExifImageHeight; - } - - public void setExifImageHeight(int exifImageHeight) { - ExifImageHeight = exifImageHeight; - } - - public int getInteropOffset() { - return InteropOffset; - } - - public void setInteropOffset(int interopOffset) { - InteropOffset = interopOffset; - } - - public double getFocalPlaneXResolution() { - return FocalPlaneXResolution; - } - - public void setFocalPlaneXResolution(double focalPlaneXResolution) { - FocalPlaneXResolution = focalPlaneXResolution; - } - - public double getFocalPlaneYResolution() { - return FocalPlaneYResolution; - } - - public void setFocalPlaneYResolution(double focalPlaneYResolution) { - FocalPlaneYResolution = focalPlaneYResolution; - } - - public int getFocalPlaneResolutionUnit() { - return FocalPlaneResolutionUnit; - } - - public void setFocalPlaneResolutionUnit(int focalPlaneResolutionUnit) { - FocalPlaneResolutionUnit = focalPlaneResolutionUnit; - } - - public int getCustomRendered() { - return CustomRendered; - } - - public void setCustomRendered(int customRendered) { - CustomRendered = customRendered; - } - - public int getExposureMode() { - return ExposureMode; - } - - public void setExposureMode(int exposureMode) { - ExposureMode = exposureMode; - } - - public int getWhiteBalance() { - return WhiteBalance; - } - - public void setWhiteBalance(int whiteBalance) { - WhiteBalance = whiteBalance; - } - - public int getSceneCaptureType() { - return SceneCaptureType; - } - - public void setSceneCaptureType(int sceneCaptureType) { - SceneCaptureType = sceneCaptureType; - } - - @Override - public String toString() { - return "Exif{" + - "ExposureTime=" + ExposureTime + - ", FNumber=" + FNumber + - ", ExposureProgram=" + ExposureProgram + - ", ISO=" + ISO + - ", ExifVersion='" + ExifVersion + '\'' + - ", DateTimeOriginal='" + DateTimeOriginal + '\'' + - ", CreateDate='" + CreateDate + '\'' + - ", ShutterSpeedValue=" + ShutterSpeedValue + - ", ApertureValue=" + ApertureValue + - ", ExposureCompensation=" + ExposureCompensation + - ", MeteringMode=" + MeteringMode + - ", Flash=" + Flash + - ", FocalLength=" + FocalLength + - ", SubSecTime='" + SubSecTime + '\'' + - ", SubSecTimeOriginal='" + SubSecTimeOriginal + '\'' + - ", SubSecTimeDigitized='" + SubSecTimeDigitized + '\'' + - ", FlashpixVersion='" + FlashpixVersion + '\'' + - ", ColorSpace=" + ColorSpace + - ", ExifImageWidth=" + ExifImageWidth + - ", ExifImageHeight=" + ExifImageHeight + - ", InteropOffset=" + InteropOffset + - ", FocalPlaneXResolution=" + FocalPlaneXResolution + - ", FocalPlaneYResolution=" + FocalPlaneYResolution + - ", FocalPlaneResolutionUnit=" + FocalPlaneResolutionUnit + - ", CustomRendered=" + CustomRendered + - ", ExposureMode=" + ExposureMode + - ", WhiteBalance=" + WhiteBalance + - ", SceneCaptureType=" + SceneCaptureType + - '}'; - } - } - - public class GPS{ - private List GPSVersionID; - - public GPS() { - } - - public List getGPSVersionID() { - return GPSVersionID; - } - - public void setGPSVersionID(List GPSVersionID) { - this.GPSVersionID = GPSVersionID; - } - - @Override - public String toString() { - return "GPS{" + - "GPSVersionID=" + GPSVersionID + - '}'; - } - } - - public class Interoperability{ - private String InteropIndex; - private String InteropVersion; - - public Interoperability() { - } - - public String getInteropIndex() { - return InteropIndex; - } - - public void setInteropIndex(String interopIndex) { - InteropIndex = interopIndex; - } - - public String getInteropVersion() { - return InteropVersion; - } - - public void setInteropVersion(String interopVersion) { - InteropVersion = interopVersion; - } - - @Override - public String toString() { - return "Interoperability{" + - "InteropIndex='" + InteropIndex + '\'' + - ", InteropVersion='" + InteropVersion + '\'' + - '}'; - } - } -} diff --git a/imagekit-sdk/src/main/java/io/imagekit/sdk/models/MoveFileRequest.java b/imagekit-sdk/src/main/java/io/imagekit/sdk/models/MoveFileRequest.java deleted file mode 100644 index 2d015a5..0000000 --- a/imagekit-sdk/src/main/java/io/imagekit/sdk/models/MoveFileRequest.java +++ /dev/null @@ -1,27 +0,0 @@ -package io.imagekit.sdk.models; - -public class MoveFileRequest { - public String sourceFilePath; - public String destinationPath; - - public String getSourceFilePath() { - return sourceFilePath; - } - - public void setSourceFilePath(String sourceFilePath) { - this.sourceFilePath = sourceFilePath; - } - - public String getDestinationPath() { - return destinationPath; - } - - public void setDestinationPath(String destinationPath) { - this.destinationPath = destinationPath; - } - - @Override - public String toString() { - return "MoveFileRequest{" + "sourceFilePath=" + sourceFilePath + ", destinationPath=" + destinationPath + '}'; - } -} diff --git a/imagekit-sdk/src/main/java/io/imagekit/sdk/models/MoveFolderRequest.java b/imagekit-sdk/src/main/java/io/imagekit/sdk/models/MoveFolderRequest.java deleted file mode 100644 index 900a97f..0000000 --- a/imagekit-sdk/src/main/java/io/imagekit/sdk/models/MoveFolderRequest.java +++ /dev/null @@ -1,28 +0,0 @@ -package io.imagekit.sdk.models; - -public class MoveFolderRequest { - public String sourceFolderPath; - public String destinationPath; - - public String getSourceFolderPath() { - return sourceFolderPath; - } - - public void setSourceFolderPath(String sourceFolderPath) { - this.sourceFolderPath = sourceFolderPath; - } - - public String getDestinationPath() { - return destinationPath; - } - - public void setDestinationPath(String destinationPath) { - this.destinationPath = destinationPath; - } - - @Override - public String toString() { - return "MoveFolderRequest{" + "sourceFolderPath=" + sourceFolderPath + ", destinationPath=" + destinationPath - + '}'; - } -} diff --git a/imagekit-sdk/src/main/java/io/imagekit/sdk/models/RenameFileRequest.java b/imagekit-sdk/src/main/java/io/imagekit/sdk/models/RenameFileRequest.java deleted file mode 100644 index 85d5fc9..0000000 --- a/imagekit-sdk/src/main/java/io/imagekit/sdk/models/RenameFileRequest.java +++ /dev/null @@ -1,37 +0,0 @@ -package io.imagekit.sdk.models; - -public class RenameFileRequest { - public String filePath; - public String newFileName; - public Boolean purgeCache; - - public String getFilePath() { - return filePath; - } - - public void setFilePath(String filePath) { - this.filePath = filePath; - } - - public String getNewFileName() { - return newFileName; - } - - public void setNewFileName(String newFileName) { - this.newFileName = newFileName; - } - - public Boolean getPurgeCache() { - return purgeCache; - } - - public void setPurgeCache(Boolean purgeCache) { - this.purgeCache = purgeCache; - } - - @Override - public String toString() { - return "RenameFileRequest{" + "filePath=" + filePath + ", newFileName=" + newFileName + ", purgeCache=" - + purgeCache + '}'; - } -} diff --git a/imagekit-sdk/src/main/java/io/imagekit/sdk/models/ResponseMetaData.java b/imagekit-sdk/src/main/java/io/imagekit/sdk/models/ResponseMetaData.java deleted file mode 100644 index 57f1859..0000000 --- a/imagekit-sdk/src/main/java/io/imagekit/sdk/models/ResponseMetaData.java +++ /dev/null @@ -1,63 +0,0 @@ -package io.imagekit.sdk.models; - -import com.google.gson.Gson; -import com.google.gson.reflect.TypeToken; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public class ResponseMetaData { - - private String raw; - private int httpStatusCode; - private Map headers; - - public String getRaw() { - return raw; - } - - public void setRaw(String raw) { - this.raw = raw; - } - - public int getHttpStatusCode() { - return httpStatusCode; - } - - public void setHttpStatusCode(int httpStatusCode) { - this.httpStatusCode = httpStatusCode; - } - - public Map getHeaders() { - return headers; - } - - public void setHeaders(Map headers) { - this.headers = headers; - } - - public Map getMap() { - if (null != raw) { - return new Gson().fromJson(raw, new TypeToken>() { - }.getType()); - } - return new HashMap<>(); - } - - public List getList() { - if (null != raw) { - return new Gson().fromJson(raw, new TypeToken() { - }.getType()); - } - return new ArrayList<>(); - } - - @Override - public String toString() { - return "ResponseMetaData{" + "raw='" + raw + '\'' + ", httpStatusCode=" + httpStatusCode + ", headers=" - + headers + '}'; - } -} diff --git a/imagekit-sdk/src/main/java/io/imagekit/sdk/models/TagsRequest.java b/imagekit-sdk/src/main/java/io/imagekit/sdk/models/TagsRequest.java deleted file mode 100644 index 7653c8a..0000000 --- a/imagekit-sdk/src/main/java/io/imagekit/sdk/models/TagsRequest.java +++ /dev/null @@ -1,35 +0,0 @@ -package io.imagekit.sdk.models; - -import java.util.List; -import java.util.stream.Collectors; - -public class TagsRequest { - public List fileIds; - public List tags; - - public TagsRequest(List fileIds, List tags) { - this.fileIds = fileIds; - this.tags = tags; - } - - public List getTags() { - return tags; - } - - public void setTags(List tags) { - this.tags = tags; - } - - public List getFileIds() { - return fileIds; - } - - public void setFileIds(List fileIds) { - this.fileIds = fileIds; - } - - @Override - public String toString() { - return "TagsRequest{" + "fileIds=" + fileIds + ", tags=" + tags + '}'; - } -} diff --git a/imagekit-sdk/src/main/java/io/imagekit/sdk/models/results/Result.java b/imagekit-sdk/src/main/java/io/imagekit/sdk/models/results/Result.java deleted file mode 100644 index 4c51941..0000000 --- a/imagekit-sdk/src/main/java/io/imagekit/sdk/models/results/Result.java +++ /dev/null @@ -1,193 +0,0 @@ -package io.imagekit.sdk.models.results; - -import com.google.gson.Gson; -import com.google.gson.JsonArray; -import com.google.gson.JsonObject; -import com.google.gson.reflect.TypeToken; - -import io.imagekit.sdk.models.BaseFile; -import io.imagekit.sdk.models.ResponseMetaData; - -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public class Result extends BaseFile { - private String help; - @Deprecated - private String raw; - private ResponseMetaData responseMetaData = new ResponseMetaData(); - - public Result() { - } - - public Result(String fileId, String name, String url, String thumbnail, int height, int width, long size, - String filePath, List tags, boolean isPrivateFile, String customCoordinates, String fileType, - JsonArray aiTags, JsonObject versionInfo, JsonObject customMetadata, JsonObject embeddedMetadata, - JsonObject extensionStatus, String type, String mime, Boolean hasAlpha, Date createdAt, Date updatedAt) { - this.fileId = fileId; - this.name = name; - this.url = url; - this.thumbnail = thumbnail; - this.height = height; - this.width = width; - this.size = size; - this.filePath = filePath; - this.tags = tags; - this.isPrivateFile = isPrivateFile; - this.customCoordinates = customCoordinates; - this.fileType = fileType; - this.aiTags = aiTags; - this.versionInfo = versionInfo; - this.customMetadata = customMetadata; - this.embeddedMetadata = embeddedMetadata; - this.extensionStatus = extensionStatus; - this.type = type; - this.mime = mime; - this.hasAlpha = hasAlpha; - this.createdAt = createdAt; - this.updatedAt = updatedAt; - } - - public String getHelp() { - return help; - } - - public String getRaw() { - return raw; - } - - public void setRaw(String raw) { - this.raw = raw; - } - - @Deprecated - public Map getMap() { - if (null != raw) { - return new Gson().fromJson(raw, new TypeToken>() { - }.getType()); - } - return new HashMap<>(); - } - - public void setHelp(String help) { - this.help = help; - } - - public String getFileId() { - return fileId; - } - - public void setFileId(String fileId) { - this.fileId = fileId; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getUrl() { - return url; - } - - public void setUrl(String url) { - this.url = url; - } - - public String getThumbnail() { - return thumbnail; - } - - public void setThumbnail(String thumbnail) { - this.thumbnail = thumbnail; - } - - public int getHeight() { - return height; - } - - public void setHeight(int height) { - this.height = height; - } - - public int getWidth() { - return width; - } - - public void setWidth(int width) { - this.width = width; - } - - public long getSize() { - return size; - } - - public void setSize(long size) { - this.size = size; - } - - public String getFilePath() { - return filePath; - } - - public void setFilePath(String filePath) { - this.filePath = filePath; - } - - public List getTags() { - return tags; - } - - public void setTags(List tags) { - this.tags = tags; - } - - public boolean isPrivateFile() { - return isPrivateFile; - } - - public void setPrivateFile(boolean privateFile) { - isPrivateFile = privateFile; - } - - public String getCustomCoordinates() { - return customCoordinates; - } - - public void setCustomCoordinates(String customCoordinates) { - this.customCoordinates = customCoordinates; - } - - public String getFileType() { - return fileType; - } - - public void setFileType(String fileType) { - this.fileType = fileType; - } - - public ResponseMetaData getResponseMetaData() { - return responseMetaData; - } - - public void setResponseMetaData(ResponseMetaData responseMetaData) { - this.responseMetaData = responseMetaData; - } - - @Override - public String toString() { - return "Result{" + "fileId='" + fileId + '\'' + ", name='" + name + '\'' + ", url='" + url + '\'' - + ", thumbnail='" + thumbnail + '\'' + ", height=" + height + ", width=" + width + ", size=" + size - + ", filePath='" + filePath + '\'' + ", tags=" + tags + ", isPrivateFile=" + isPrivateFile - + ", customCoordinates='" + customCoordinates + '\'' + ", fileType='" + fileType + '\'' + ", aiTags=" - + aiTags + ", versionInfo=" + versionInfo + ", customMetadata=" + customMetadata + ", embeddedMetadata=" - + embeddedMetadata + ", extensionStatus=" + extensionStatus + ", type='" + type + '\'' + ", mime='" - + mime + '\'' + ", hasAlpha=" + hasAlpha + ", createdAt=" + createdAt + ", updatedAt=" + updatedAt - + ", help='" + help + '\'' + ", raw='" + raw + '\'' + ", responseMetaData=" + responseMetaData + '}'; - } -} diff --git a/imagekit-sdk/src/main/java/io/imagekit/sdk/models/results/ResultBulkJobStatus.java b/imagekit-sdk/src/main/java/io/imagekit/sdk/models/results/ResultBulkJobStatus.java deleted file mode 100644 index 644755d..0000000 --- a/imagekit-sdk/src/main/java/io/imagekit/sdk/models/results/ResultBulkJobStatus.java +++ /dev/null @@ -1,48 +0,0 @@ -package io.imagekit.sdk.models.results; - -import io.imagekit.sdk.models.ResponseMetaData; - -public class ResultBulkJobStatus { - private String jobId; - private String type; - private String status; - private ResponseMetaData responseMetaData = new ResponseMetaData(); - - public String getJobId() { - return jobId; - } - - public void setJobId(String jobId) { - this.jobId = jobId; - } - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - public String getStatus() { - return status; - } - - public void setStatus(String status) { - this.status = status; - } - - public ResponseMetaData getResponseMetaData() { - return responseMetaData; - } - - public void setResponseMetaData(ResponseMetaData responseMetaData) { - this.responseMetaData = responseMetaData; - } - - @Override - public String toString() { - return "ResultBulkJobStatus{" + "jobId='" + jobId + '\'' + ", type='" + type + '\'' + ", status='" + status - + '\'' + ", responseMetaData=" + responseMetaData + '}'; - } -} diff --git a/imagekit-sdk/src/main/java/io/imagekit/sdk/models/results/ResultCache.java b/imagekit-sdk/src/main/java/io/imagekit/sdk/models/results/ResultCache.java deleted file mode 100644 index 742ec19..0000000 --- a/imagekit-sdk/src/main/java/io/imagekit/sdk/models/results/ResultCache.java +++ /dev/null @@ -1,67 +0,0 @@ -package io.imagekit.sdk.models.results; - -import com.google.gson.Gson; -import com.google.gson.reflect.TypeToken; - -import java.util.HashMap; -import java.util.Map; - -import io.imagekit.sdk.models.ResponseMetaData; - -public class ResultCache { - private String help; - private String requestId; - @Deprecated - private String raw; - private ResponseMetaData responseMetaData = new ResponseMetaData(); - - public ResultCache() { - } - - public String getHelp() { - return help; - } - - public void setHelp(String help) { - this.help = help; - } - - public String getRaw() { - return raw; - } - - public void setRaw(String raw) { - this.raw = raw; - } - - @Deprecated - public Map getMap() { - if (null != raw) { - return new Gson().fromJson(raw, new TypeToken>() { - }.getType()); - } - return new HashMap<>(); - } - - public String getRequestId() { - return requestId; - } - - public void setRequestId(String requestId) { - this.requestId = requestId; - } - - public ResponseMetaData getResponseMetaData() { - return responseMetaData; - } - - public void setResponseMetaData(ResponseMetaData responseMetaData) { - this.responseMetaData = responseMetaData; - } - - @Override - public String toString() { - return "ResultCache{" + "help='" + help + '\'' + ", requestId='" + requestId + '\'' + ", raw='" + raw + '\'' - + ", responseMetaData=" + responseMetaData + '}'; - } -} diff --git a/imagekit-sdk/src/main/java/io/imagekit/sdk/models/results/ResultCacheStatus.java b/imagekit-sdk/src/main/java/io/imagekit/sdk/models/results/ResultCacheStatus.java deleted file mode 100644 index a61cba3..0000000 --- a/imagekit-sdk/src/main/java/io/imagekit/sdk/models/results/ResultCacheStatus.java +++ /dev/null @@ -1,67 +0,0 @@ -package io.imagekit.sdk.models.results; - -import com.google.gson.Gson; -import com.google.gson.reflect.TypeToken; - -import java.util.HashMap; -import java.util.Map; - -import io.imagekit.sdk.models.ResponseMetaData; - -public class ResultCacheStatus { - private String help; - private String status; - @Deprecated - private String raw; - private ResponseMetaData responseMetaData = new ResponseMetaData(); - - public ResultCacheStatus() { - } - - public String getHelp() { - return help; - } - - public String getRaw() { - return raw; - } - - public void setRaw(String raw) { - this.raw = raw; - } - - @Deprecated - public Map getMap() { - if (null != raw) { - return new Gson().fromJson(raw, new TypeToken>() { - }.getType()); - } - return new HashMap<>(); - } - - public void setHelp(String help) { - this.help = help; - } - - public String getStatus() { - return status; - } - - public void setStatus(String status) { - this.status = status; - } - - public ResponseMetaData getResponseMetaData() { - return responseMetaData; - } - - public void setResponseMetaData(ResponseMetaData responseMetaData) { - this.responseMetaData = responseMetaData; - } - - @Override - public String toString() { - return "ResultCacheStatus{" + "help='" + help + '\'' + ", status='" + status + '\'' + ", raw='" + raw + '\'' - + ", responseMetaData=" + responseMetaData + '}'; - } -} diff --git a/imagekit-sdk/src/main/java/io/imagekit/sdk/models/results/ResultCustomMetaDataField.java b/imagekit-sdk/src/main/java/io/imagekit/sdk/models/results/ResultCustomMetaDataField.java deleted file mode 100644 index 2dc6836..0000000 --- a/imagekit-sdk/src/main/java/io/imagekit/sdk/models/results/ResultCustomMetaDataField.java +++ /dev/null @@ -1,62 +0,0 @@ -package io.imagekit.sdk.models.results; - -import io.imagekit.sdk.models.CustomMetaDataFieldSchemaObject; -import io.imagekit.sdk.models.ResponseMetaData; - -public class ResultCustomMetaDataField { - private String id; - private String name; - private String label; - private CustomMetaDataFieldSchemaObject schema = new CustomMetaDataFieldSchemaObject(); - private ResponseMetaData responseMetaData = new ResponseMetaData(); - - public ResultCustomMetaDataField() { - - } - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getLabel() { - return label; - } - - public void setLabel(String label) { - this.label = label; - } - - public CustomMetaDataFieldSchemaObject getSchema() { - return schema; - } - - public void setSchema(CustomMetaDataFieldSchemaObject schema) { - this.schema = schema; - } - - public ResponseMetaData getResponseMetaData() { - return responseMetaData; - } - - public void setResponseMetaData(ResponseMetaData responseMetaData) { - this.responseMetaData = responseMetaData; - } - - @Override - public String toString() { - return "ResultCustomMetaDataField{" + "id='" + id + '\'' + ", name='" + name + '\'' + ", label='" + label + '\'' - + ", schema=" + schema + ", responseMetaData=" + responseMetaData + '}'; - } -} diff --git a/imagekit-sdk/src/main/java/io/imagekit/sdk/models/results/ResultCustomMetaDataFieldList.java b/imagekit-sdk/src/main/java/io/imagekit/sdk/models/results/ResultCustomMetaDataFieldList.java deleted file mode 100644 index 1528c21..0000000 --- a/imagekit-sdk/src/main/java/io/imagekit/sdk/models/results/ResultCustomMetaDataFieldList.java +++ /dev/null @@ -1,33 +0,0 @@ -package io.imagekit.sdk.models.results; - -import java.util.List; - -import io.imagekit.sdk.models.ResponseMetaData; - -public class ResultCustomMetaDataFieldList { - - private List resultCustomMetaDataFieldList; - private ResponseMetaData responseMetaData = new ResponseMetaData(); - - public List getResultCustomMetaDataFieldList() { - return resultCustomMetaDataFieldList; - } - - public void setResultCustomMetaDataFieldList(List resultCustomMetaDataFieldList) { - this.resultCustomMetaDataFieldList = resultCustomMetaDataFieldList; - } - - public ResponseMetaData getResponseMetaData() { - return responseMetaData; - } - - public void setResponseMetaData(ResponseMetaData responseMetaData) { - this.responseMetaData = responseMetaData; - } - - @Override - public String toString() { - return "ResultCustomMetaDataFieldList{" + "resultCustomMetaDataFieldList=" + resultCustomMetaDataFieldList - + ", responseMetaData=" + responseMetaData + '}'; - } -} diff --git a/imagekit-sdk/src/main/java/io/imagekit/sdk/models/results/ResultEmptyBlock.java b/imagekit-sdk/src/main/java/io/imagekit/sdk/models/results/ResultEmptyBlock.java deleted file mode 100644 index ce1cf4a..0000000 --- a/imagekit-sdk/src/main/java/io/imagekit/sdk/models/results/ResultEmptyBlock.java +++ /dev/null @@ -1,20 +0,0 @@ -package io.imagekit.sdk.models.results; - -import io.imagekit.sdk.models.ResponseMetaData; - -public class ResultEmptyBlock { - private ResponseMetaData responseMetaData = new ResponseMetaData(); - - public ResponseMetaData getResponseMetaData() { - return responseMetaData; - } - - public void setResponseMetaData(ResponseMetaData responseMetaData) { - this.responseMetaData = responseMetaData; - } - - @Override - public String toString() { - return "ResultEmptyBlock{" + "responseMetaData=" + responseMetaData + '}'; - } -} diff --git a/imagekit-sdk/src/main/java/io/imagekit/sdk/models/results/ResultException.java b/imagekit-sdk/src/main/java/io/imagekit/sdk/models/results/ResultException.java deleted file mode 100644 index 0e66630..0000000 --- a/imagekit-sdk/src/main/java/io/imagekit/sdk/models/results/ResultException.java +++ /dev/null @@ -1,42 +0,0 @@ -package io.imagekit.sdk.models.results; - -import io.imagekit.sdk.models.ResponseMetaData; - -public class ResultException { - private String message; - private String help; - private ResponseMetaData responseMetaData = new ResponseMetaData(); - - public ResultException() { - } - - public String getMessage() { - return message; - } - - public void setMessage(String message) { - this.message = message; - } - - public String getHelp() { - return help; - } - - public void setHelp(String help) { - this.help = help; - } - - public ResponseMetaData getResponseMetaData() { - return responseMetaData; - } - - public void setResponseMetaData(ResponseMetaData responseMetaData) { - this.responseMetaData = responseMetaData; - } - - @Override - public String toString() { - return "ResultException{" + "message='" + message + '\'' + ", help='" + help + '\'' + ", responseMetaData=" - + responseMetaData + '}'; - } -} diff --git a/imagekit-sdk/src/main/java/io/imagekit/sdk/models/results/ResultFileDelete.java b/imagekit-sdk/src/main/java/io/imagekit/sdk/models/results/ResultFileDelete.java deleted file mode 100644 index cb50ff4..0000000 --- a/imagekit-sdk/src/main/java/io/imagekit/sdk/models/results/ResultFileDelete.java +++ /dev/null @@ -1,81 +0,0 @@ -package io.imagekit.sdk.models.results; - -import com.google.gson.Gson; -import com.google.gson.reflect.TypeToken; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import io.imagekit.sdk.models.ResponseMetaData; - -public class ResultFileDelete { - private String help; - @Deprecated - private String raw; - private List successfullyDeletedFileIds; - private List missingFileIds; - private ResponseMetaData responseMetaData = new ResponseMetaData(); - - public ResultFileDelete() { - successfullyDeletedFileIds = new ArrayList<>(); - missingFileIds = new ArrayList<>(); - } - - public String getHelp() { - return help; - } - - public void setHelp(String help) { - this.help = help; - } - - public String getRaw() { - return raw; - } - - public void setRaw(String raw) { - this.raw = raw; - } - - @Deprecated - public Map getMap() { - if (null != raw) { - return new Gson().fromJson(raw, new TypeToken>() { - }.getType()); - } - return new HashMap<>(); - } - - public List getSuccessfullyDeletedFileIds() { - return successfullyDeletedFileIds; - } - - public void setSuccessfullyDeletedFileIds(List successfullyDeletedFileIds) { - this.successfullyDeletedFileIds = successfullyDeletedFileIds; - } - - public List getMissingFileIds() { - return missingFileIds; - } - - public void setMissingFileIds(List missingFileIds) { - this.missingFileIds = missingFileIds; - } - - public ResponseMetaData getResponseMetaData() { - return responseMetaData; - } - - public void setResponseMetaData(ResponseMetaData responseMetaData) { - this.responseMetaData = responseMetaData; - } - - @Override - public String toString() { - return "ResultFileDelete{" + "help='" + help + '\'' + ", raw='" + raw + '\'' + ", successfullyDeletedFileIds=" - + successfullyDeletedFileIds + ", missingFileIds=" + missingFileIds + ", responseMetaData=" - + responseMetaData + '}'; - } -} diff --git a/imagekit-sdk/src/main/java/io/imagekit/sdk/models/results/ResultFileVersionDetails.java b/imagekit-sdk/src/main/java/io/imagekit/sdk/models/results/ResultFileVersionDetails.java deleted file mode 100644 index f9f83c2..0000000 --- a/imagekit-sdk/src/main/java/io/imagekit/sdk/models/results/ResultFileVersionDetails.java +++ /dev/null @@ -1,221 +0,0 @@ -package io.imagekit.sdk.models.results; - -import com.google.gson.JsonArray; -import com.google.gson.JsonObject; -import java.util.List; - -import io.imagekit.sdk.models.ResponseMetaData; - -public class ResultFileVersionDetails { - - protected String type; - protected String name; - protected String createdAt; - protected String updatedAt; - protected String fileId; - protected List tags; - protected JsonArray aiTags; - protected JsonObject versionInfo; - protected JsonObject embeddedMetadata; - protected String customCoordinates; - protected JsonObject customMetadata; - protected boolean isPrivateFile; - protected String url; - protected String thumbnail; - protected String fileType; - protected String filePath; - protected int height; - protected int width; - protected long size; - protected Boolean hasAlpha; - protected String mime; - private ResponseMetaData responseMetaData = new ResponseMetaData(); - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getCreatedAt() { - return createdAt; - } - - public void setCreatedAt(String createdAt) { - this.createdAt = createdAt; - } - - public String getUpdatedAt() { - return updatedAt; - } - - public void setUpdatedAt(String updatedAt) { - this.updatedAt = updatedAt; - } - - public String getFileId() { - return fileId; - } - - public void setFileId(String fileId) { - this.fileId = fileId; - } - - public List getTags() { - return tags; - } - - public void setTags(List tags) { - this.tags = tags; - } - - public JsonArray getAiTags() { - return aiTags; - } - - public void setAiTags(JsonArray aiTags) { - this.aiTags = aiTags; - } - - public JsonObject getVersionInfo() { - return versionInfo; - } - - public void setVersionInfo(JsonObject versionInfo) { - this.versionInfo = versionInfo; - } - - public JsonObject getEmbeddedMetadata() { - return embeddedMetadata; - } - - public void setEmbeddedMetadata(JsonObject embeddedMetadata) { - this.embeddedMetadata = embeddedMetadata; - } - - public String getCustomCoordinates() { - return customCoordinates; - } - - public void setCustomCoordinates(String customCoordinates) { - this.customCoordinates = customCoordinates; - } - - public JsonObject getCustomMetadata() { - return customMetadata; - } - - public void setCustomMetadata(JsonObject customMetadata) { - this.customMetadata = customMetadata; - } - - public boolean isPrivateFile() { - return isPrivateFile; - } - - public void setPrivateFile(boolean privateFile) { - isPrivateFile = privateFile; - } - - public String getUrl() { - return url; - } - - public void setUrl(String url) { - this.url = url; - } - - public String getThumbnail() { - return thumbnail; - } - - public void setThumbnail(String thumbnail) { - this.thumbnail = thumbnail; - } - - public String getFileType() { - return fileType; - } - - public void setFileType(String fileType) { - this.fileType = fileType; - } - - public String getFilePath() { - return filePath; - } - - public void setFilePath(String filePath) { - this.filePath = filePath; - } - - public int getHeight() { - return height; - } - - public void setHeight(int height) { - this.height = height; - } - - public int getWidth() { - return width; - } - - public void setWidth(int width) { - this.width = width; - } - - public long getSize() { - return size; - } - - public void setSize(long size) { - this.size = size; - } - - public Boolean getHasAlpha() { - return hasAlpha; - } - - public void setHasAlpha(Boolean hasAlpha) { - this.hasAlpha = hasAlpha; - } - - public String getMime() { - return mime; - } - - public void setMime(String mime) { - this.mime = mime; - } - - public ResponseMetaData getResponseMetaData() { - return responseMetaData; - } - - public void setResponseMetaData(ResponseMetaData responseMetaData) { - this.responseMetaData = responseMetaData; - } - - @Override - public String toString() { - return "ResultFileVersion{" + "type='" + type + '\'' + ", name='" + name + '\'' + ", createdAt='" + createdAt - + '\'' + ", updatedAt='" + updatedAt + '\'' + ", fileId='" + fileId + '\'' + ", tags=" + tags - + ", aiTags=" + aiTags + ", versionInfo=" + versionInfo + ", embeddedMetadata=" + embeddedMetadata - + ", customCoordinates='" + customCoordinates + '\'' + ", customMetadata=" + customMetadata - + ", isPrivateFile=" + isPrivateFile + ", url='" + url + '\'' + ", thumbnail='" + thumbnail + '\'' - + ", fileType='" + fileType + '\'' + ", filePath='" + filePath + '\'' + ", height=" + height - + ", width=" + width + ", size=" + size + ", hasAlpha=" + hasAlpha + ", mime='" + mime + '\'' - + ", responseMetaData=" + responseMetaData + '}'; - } -} diff --git a/imagekit-sdk/src/main/java/io/imagekit/sdk/models/results/ResultFileVersions.java b/imagekit-sdk/src/main/java/io/imagekit/sdk/models/results/ResultFileVersions.java deleted file mode 100644 index 3e2a232..0000000 --- a/imagekit-sdk/src/main/java/io/imagekit/sdk/models/results/ResultFileVersions.java +++ /dev/null @@ -1,33 +0,0 @@ -package io.imagekit.sdk.models.results; - -import java.util.ArrayList; -import java.util.List; - -import io.imagekit.sdk.models.ResponseMetaData; - -public class ResultFileVersions { - List resultFileVersionDetailsList = new ArrayList<>(); - private ResponseMetaData responseMetaData = new ResponseMetaData(); - - public List getResultFileVersionDetailsList() { - return resultFileVersionDetailsList; - } - - public void setResultFileVersionDetailsList(List resultFileVersionDetailsList) { - this.resultFileVersionDetailsList = resultFileVersionDetailsList; - } - - public ResponseMetaData getResponseMetaData() { - return responseMetaData; - } - - public void setResponseMetaData(ResponseMetaData responseMetaData) { - this.responseMetaData = responseMetaData; - } - - @Override - public String toString() { - return "ResultFileVersions{" + "resultFileVersionDetailsList=" + resultFileVersionDetailsList - + ", responseMetaData=" + responseMetaData + '}'; - } -} diff --git a/imagekit-sdk/src/main/java/io/imagekit/sdk/models/results/ResultList.java b/imagekit-sdk/src/main/java/io/imagekit/sdk/models/results/ResultList.java deleted file mode 100644 index 7c51f5b..0000000 --- a/imagekit-sdk/src/main/java/io/imagekit/sdk/models/results/ResultList.java +++ /dev/null @@ -1,73 +0,0 @@ -package io.imagekit.sdk.models.results; - -import com.google.gson.Gson; -import com.google.gson.reflect.TypeToken; - -import io.imagekit.sdk.models.BaseFile; -import io.imagekit.sdk.models.ResponseMetaData; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -public class ResultList { - private String help; - @Deprecated - private String raw; - private List results; - private ResponseMetaData responseMetaData = new ResponseMetaData(); - - public ResultList() { - } - - public ResultList(List results) { - this.results = results; - } - - public String getHelp() { - return help; - } - - public void setHelp(String help) { - this.help = help; - } - - public String getRaw() { - return raw; - } - - public void setRaw(String raw) { - this.raw = raw; - } - - @Deprecated - public List> getMap() { - if (null != raw) { - return new Gson().fromJson(raw, new TypeToken>>() { - }.getType()); - } - return new ArrayList>(); - } - - public ResponseMetaData getResponseMetaData() { - return responseMetaData; - } - - public void setResponseMetaData(ResponseMetaData responseMetaData) { - this.responseMetaData = responseMetaData; - } - - public List getResults() { - return results; - } - - public void setResults(List results) { - this.results = results; - } - - @Override - public String toString() { - return "ResultList{" + "help='" + help + '\'' + ", raw='" + raw + '\'' + ", results=" + results - + ", responseMetaData=" + responseMetaData + '}'; - } -} diff --git a/imagekit-sdk/src/main/java/io/imagekit/sdk/models/results/ResultMetaData.java b/imagekit-sdk/src/main/java/io/imagekit/sdk/models/results/ResultMetaData.java deleted file mode 100644 index be2e6ed..0000000 --- a/imagekit-sdk/src/main/java/io/imagekit/sdk/models/results/ResultMetaData.java +++ /dev/null @@ -1,68 +0,0 @@ -package io.imagekit.sdk.models.results; - -import com.google.gson.Gson; -import com.google.gson.reflect.TypeToken; - -import java.util.HashMap; -import java.util.Map; - -import io.imagekit.sdk.models.MetaData; -import io.imagekit.sdk.models.ResponseMetaData; - -public class ResultMetaData { - private String help; - @Deprecated - private String raw; - private MetaData results; - private ResponseMetaData responseMetaData = new ResponseMetaData(); - - public ResultMetaData() { - } - - public String getHelp() { - return help; - } - - public void setHelp(String help) { - this.help = help; - } - - public String getRaw() { - return raw; - } - - public void setRaw(String raw) { - this.raw = raw; - } - - @Deprecated - public Map getMap() { - if (null != raw) { - return new Gson().fromJson(raw, new TypeToken>() { - }.getType()); - } - return new HashMap<>(); - } - - public MetaData getResults() { - return results; - } - - public void setResults(MetaData results) { - this.results = results; - } - - public ResponseMetaData getResponseMetaData() { - return responseMetaData; - } - - public void setResponseMetaData(ResponseMetaData responseMetaData) { - this.responseMetaData = responseMetaData; - } - - @Override - public String toString() { - return "ResultMetaData{" + "help='" + help + '\'' + ", raw='" + raw + '\'' + ", results=" + results - + ", responseMetaData=" + responseMetaData + '}'; - } -} diff --git a/imagekit-sdk/src/main/java/io/imagekit/sdk/models/results/ResultNoContent.java b/imagekit-sdk/src/main/java/io/imagekit/sdk/models/results/ResultNoContent.java deleted file mode 100644 index 439cb61..0000000 --- a/imagekit-sdk/src/main/java/io/imagekit/sdk/models/results/ResultNoContent.java +++ /dev/null @@ -1,20 +0,0 @@ -package io.imagekit.sdk.models.results; - -import io.imagekit.sdk.models.ResponseMetaData; - -public class ResultNoContent { - private ResponseMetaData responseMetaData = new ResponseMetaData(); - - public ResponseMetaData getResponseMetaData() { - return responseMetaData; - } - - public void setResponseMetaData(ResponseMetaData responseMetaData) { - this.responseMetaData = responseMetaData; - } - - @Override - public String toString() { - return "ResultNoContent{" + "responseMetaData=" + responseMetaData + '}'; - } -} diff --git a/imagekit-sdk/src/main/java/io/imagekit/sdk/models/results/ResultOfFolderActions.java b/imagekit-sdk/src/main/java/io/imagekit/sdk/models/results/ResultOfFolderActions.java deleted file mode 100644 index 905f43b..0000000 --- a/imagekit-sdk/src/main/java/io/imagekit/sdk/models/results/ResultOfFolderActions.java +++ /dev/null @@ -1,29 +0,0 @@ -package io.imagekit.sdk.models.results; - -import io.imagekit.sdk.models.ResponseMetaData; - -public class ResultOfFolderActions { - private String jobId; - private ResponseMetaData responseMetaData = new ResponseMetaData(); - - public String getJobId() { - return jobId; - } - - public void setJobId(String jobId) { - this.jobId = jobId; - } - - public ResponseMetaData getResponseMetaData() { - return responseMetaData; - } - - public void setResponseMetaData(ResponseMetaData responseMetaData) { - this.responseMetaData = responseMetaData; - } - - @Override - public String toString() { - return "ResultOfFolderActions{" + "jobId='" + jobId + '\'' + ", responseMetaData=" + responseMetaData + '}'; - } -} diff --git a/imagekit-sdk/src/main/java/io/imagekit/sdk/models/results/ResultRenameFile.java b/imagekit-sdk/src/main/java/io/imagekit/sdk/models/results/ResultRenameFile.java deleted file mode 100644 index fdc0686..0000000 --- a/imagekit-sdk/src/main/java/io/imagekit/sdk/models/results/ResultRenameFile.java +++ /dev/null @@ -1,30 +0,0 @@ -package io.imagekit.sdk.models.results; - -import io.imagekit.sdk.models.ResponseMetaData; - -public class ResultRenameFile { - private String purgeRequestId; - private ResponseMetaData responseMetaData = new ResponseMetaData(); - - public String getPurgeRequestId() { - return purgeRequestId; - } - - public void setPurgeRequestId(String purgeRequestId) { - this.purgeRequestId = purgeRequestId; - } - - public ResponseMetaData getResponseMetaData() { - return responseMetaData; - } - - public void setResponseMetaData(ResponseMetaData responseMetaData) { - this.responseMetaData = responseMetaData; - } - - @Override - public String toString() { - return "ResultRenameFile{" + "purgeRequestId='" + purgeRequestId + '\'' + ", responseMetaData=" - + responseMetaData + '}'; - } -} diff --git a/imagekit-sdk/src/main/java/io/imagekit/sdk/models/results/ResultTags.java b/imagekit-sdk/src/main/java/io/imagekit/sdk/models/results/ResultTags.java deleted file mode 100644 index 88499df..0000000 --- a/imagekit-sdk/src/main/java/io/imagekit/sdk/models/results/ResultTags.java +++ /dev/null @@ -1,32 +0,0 @@ -package io.imagekit.sdk.models.results; - -import java.util.List; - -import io.imagekit.sdk.models.ResponseMetaData; - -public class ResultTags { - private List successfullyUpdatedFileIds; - private ResponseMetaData responseMetaData = new ResponseMetaData(); - - public List getSuccessfullyUpdatedFileIds() { - return successfullyUpdatedFileIds; - } - - public void setSuccessfullyUpdatedFileIds(List successfullyUpdatedFileIds) { - this.successfullyUpdatedFileIds = successfullyUpdatedFileIds; - } - - public ResponseMetaData getResponseMetaData() { - return responseMetaData; - } - - public void setResponseMetaData(ResponseMetaData responseMetaData) { - this.responseMetaData = responseMetaData; - } - - @Override - public String toString() { - return "ResultTags{" + "successfullyUpdatedFileIds=" + successfullyUpdatedFileIds + ", responseMetaData=" - + responseMetaData + '}'; - } -} diff --git a/imagekit-sdk/src/main/java/io/imagekit/sdk/tasks/Calculation.java b/imagekit-sdk/src/main/java/io/imagekit/sdk/tasks/Calculation.java deleted file mode 100644 index 417af9b..0000000 --- a/imagekit-sdk/src/main/java/io/imagekit/sdk/tasks/Calculation.java +++ /dev/null @@ -1,49 +0,0 @@ -package io.imagekit.sdk.tasks; - -import org.apache.commons.codec.digest.HmacUtils; -import java.math.BigInteger; -import java.util.*; -import java.util.regex.Pattern; - -public class Calculation { - private static final int DEFAULT_TIME_DIFF = 60 * 30; - - public static Map getAuthenticatedParams(String token, long expire, String privateKey){ - if (token==null){ - token= UUID.randomUUID().toString(); - } - if (expire==0){ - expire= Calendar.getInstance().getTimeInMillis()+DEFAULT_TIME_DIFF; - } - if (privateKey==null) throw new RuntimeException("Private key can't be null."); - - String signature = HmacUtils.hmacSha1Hex(privateKey, token + expire); - - Map auth=new HashMap<>(); - auth.put("token",token); - auth.put("expire", String.valueOf(expire)); - auth.put("signature",signature); - return auth; - } - - public static int getHammingDistance(String firstHex, String secondHex){ - if (!(isValidHex(firstHex) && isValidHex(secondHex))){ - throw new RuntimeException("Both argument should be hexadecimal."); - } - if (firstHex.length()!=secondHex.length()) throw new RuntimeException("Both argument are not equal in length."); - - BigInteger xor = new BigInteger(firstHex, 16).xor(new BigInteger(secondHex, 16)); - - int count=0; - for(int i = 0; i < xor.toString(2).length(); i++) { - if (xor.toString(2).charAt(i)=='1'){ - count+=1; - } - } - return count; - } - - static boolean isValidHex(String hex){ - return Pattern.matches("^[0-9a-fA-F]+$",hex); - } -} diff --git a/imagekit-sdk/src/main/java/io/imagekit/sdk/tasks/MultipartBuilder.java b/imagekit-sdk/src/main/java/io/imagekit/sdk/tasks/MultipartBuilder.java deleted file mode 100644 index 98914b3..0000000 --- a/imagekit-sdk/src/main/java/io/imagekit/sdk/tasks/MultipartBuilder.java +++ /dev/null @@ -1,99 +0,0 @@ -package io.imagekit.sdk.tasks; - -import com.google.gson.Gson; -import com.google.gson.JsonParser; - -import io.imagekit.sdk.models.FileCreateRequest; -import io.imagekit.sdk.models.FileUpdateRequest; -import io.imagekit.sdk.utils.Utils; -import okhttp3.MediaType; -import okhttp3.MultipartBody; -import okhttp3.RequestBody; - -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; - -public class MultipartBuilder { - private static final String RANDOM_BOUNDARY = "randomBoundary-------------------"; - - public MultipartBody build(FileCreateRequest fileCreateRequest) { - MultipartBody.Builder builder = new MultipartBody.Builder(RANDOM_BOUNDARY).setType(MultipartBody.FORM); - - if (null != fileCreateRequest.url) { - builder.addFormDataPart("file", fileCreateRequest.url.toString()); - } else if (null != fileCreateRequest.base64) { - builder.addFormDataPart("file", fileCreateRequest.base64); - } else if (null != fileCreateRequest.bytes) { - builder.addFormDataPart("file", Utils.bytesToBase64(fileCreateRequest.bytes)); - } else { - throw new RuntimeException("Error: File not provided."); - } - if (null != fileCreateRequest.fileName) { - builder.addFormDataPart("fileName", fileCreateRequest.fileName); - } else { - throw new RuntimeException("Error: Filename not provided"); - } - if (fileCreateRequest.useUniqueFileName) { - builder.addFormDataPart("useUniqueFileName", "true"); - } else { - builder.addFormDataPart("useUniqueFileName", "false"); - } - if (null != fileCreateRequest.tags) { - builder.addFormDataPart("tags", Utils.listToString(fileCreateRequest.tags)); - } - if (null != fileCreateRequest.folder) { - builder.addFormDataPart("folder", fileCreateRequest.folder); - } - if (fileCreateRequest.isPrivateFile) { - builder.addFormDataPart("isPrivateFile", "true"); - } - if (null != fileCreateRequest.customCoordinates) { - builder.addFormDataPart("customCoordinates", fileCreateRequest.customCoordinates); - } - if (null != fileCreateRequest.responseFields) { - builder.addFormDataPart("responseFields", Utils.listToString(fileCreateRequest.responseFields)); - } - if (fileCreateRequest.overwriteFile != null && fileCreateRequest.overwriteFile) { - builder.addFormDataPart("overwriteFile", "true"); - } - if (fileCreateRequest.overwriteAITags != null && fileCreateRequest.overwriteAITags) { - builder.addFormDataPart("overwriteAITags", "true"); - } - if (fileCreateRequest.overwriteTags != null && fileCreateRequest.overwriteTags) { - builder.addFormDataPart("overwriteTags", "true"); - } - if (fileCreateRequest.overwriteCustomMetadata != null && fileCreateRequest.overwriteCustomMetadata) { - builder.addFormDataPart("overwriteCustomMetadata", "true"); - } - if (null != fileCreateRequest.extensions) { - builder.addFormDataPart("extensions", fileCreateRequest.extensions.toString()); - } - if (null != fileCreateRequest.webhookUrl) { - builder.addFormDataPart("webhookUrl", fileCreateRequest.webhookUrl); - } - if (null != fileCreateRequest.customMetadata) { - builder.addFormDataPart("customMetadata", fileCreateRequest.customMetadata.toString()); - } - return builder.build(); - } - - public RequestBody build(FileUpdateRequest fileUpdateRequest) { - if (fileUpdateRequest.getFileId() == null) { - throw new RuntimeException("Error: File Id not provided."); - } - if (fileUpdateRequest.getFileId().trim().length() < 1) { - throw new RuntimeException("Error: File Id not provided."); - } - return RequestBody.create(MediaType.parse("application/json; charset=utf-8"), - new Gson().toJson(fileUpdateRequest)); - } - - public RequestBody build(String json) { - if (json == null) { - throw new RuntimeException("Error: You can't send null body."); - } else { - return RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json); - } - } -} diff --git a/imagekit-sdk/src/main/java/io/imagekit/sdk/tasks/QueryMaker.java b/imagekit-sdk/src/main/java/io/imagekit/sdk/tasks/QueryMaker.java deleted file mode 100644 index 26d343c..0000000 --- a/imagekit-sdk/src/main/java/io/imagekit/sdk/tasks/QueryMaker.java +++ /dev/null @@ -1,20 +0,0 @@ -package io.imagekit.sdk.tasks; - -public class QueryMaker { - private String query; - - public void put(String q){ - if (null!=query){ - query+="&"; - } - else { - query=""; - } - query+=q; - } - - public String get(){ - return query; - } - -} diff --git a/imagekit-sdk/src/main/java/io/imagekit/sdk/tasks/RestClient.java b/imagekit-sdk/src/main/java/io/imagekit/sdk/tasks/RestClient.java deleted file mode 100644 index 5e6fbf3..0000000 --- a/imagekit-sdk/src/main/java/io/imagekit/sdk/tasks/RestClient.java +++ /dev/null @@ -1,964 +0,0 @@ -package io.imagekit.sdk.tasks; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonElement; -import com.google.gson.JsonParser; -import com.google.gson.reflect.TypeToken; - -import io.imagekit.sdk.ImageKit; -import io.imagekit.sdk.exceptions.BadRequestException; -import io.imagekit.sdk.exceptions.ConflictException; -import io.imagekit.sdk.exceptions.ForbiddenException; -import io.imagekit.sdk.exceptions.InternalServerException; -import io.imagekit.sdk.exceptions.NotFoundException; -import io.imagekit.sdk.exceptions.PartialSuccessException; -import io.imagekit.sdk.exceptions.TooManyRequestsException; -import io.imagekit.sdk.exceptions.UnauthorizedException; -import io.imagekit.sdk.exceptions.UnknownException; -import io.imagekit.sdk.models.AITagsRequest; -import io.imagekit.sdk.models.BaseFile; -import io.imagekit.sdk.models.CopyFileRequest; -import io.imagekit.sdk.models.CopyFolderRequest; -import io.imagekit.sdk.models.CreateFolderRequest; -import io.imagekit.sdk.models.CustomMetaDataFieldCreateRequest; -import io.imagekit.sdk.models.CustomMetaDataFieldUpdateRequest; -import io.imagekit.sdk.models.DeleteFileVersionRequest; -import io.imagekit.sdk.models.DeleteFolderRequest; -import io.imagekit.sdk.models.FileCreateRequest; -import io.imagekit.sdk.models.GetFileListRequest; -import io.imagekit.sdk.models.MoveFileRequest; -import io.imagekit.sdk.models.MoveFolderRequest; -import io.imagekit.sdk.models.MetaData; -import io.imagekit.sdk.models.FileUpdateRequest; -import io.imagekit.sdk.models.RenameFileRequest; -import io.imagekit.sdk.models.TagsRequest; -import io.imagekit.sdk.models.results.*; -import io.imagekit.sdk.utils.Utils; -import okhttp3.*; - -import java.io.IOException; -import java.lang.reflect.Field; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; - -public class RestClient { - - public static String API_BASE_URL = "https://api.imagekit.io/"; - public static String UPLOAD_BASE_URL = "https://upload.imagekit.io/"; - - private ImageKit imageKit; - Request request; - OkHttpClient client; - MultipartBuilder multipartBuilder; - - public RestClient(ImageKit imageKit) { - this.imageKit = imageKit; - this.client = new OkHttpClient(); - this.multipartBuilder = new MultipartBuilder(); - } - - public Result upload(FileCreateRequest fileCreateRequest) throws InternalServerException, BadRequestException, - UnknownException, ForbiddenException, TooManyRequestsException, UnauthorizedException { - Result result = null; - Map headers = Utils.getHeaders(imageKit); - - MultipartBody body = multipartBuilder.build(fileCreateRequest); - - request = new Request.Builder().url(UPLOAD_BASE_URL.concat("api/v1/files/upload")).post(body) - .headers(Headers.of(headers)).build(); - - - try { - Response response = client.newCall(request).execute(); - String respBody = ""; - if (response.code() == 200) { - respBody = response.body().string(); - result = new Gson().fromJson(respBody, Result.class); - result.setRaw(respBody); - } else { - Utils.generalApiThrowException(response); - } - Utils.populateResponseMetadata(respBody, result.getResponseMetaData(), response.code(), - response.headers().toMultimap()); - } catch (IOException e) { - throw new UnknownException(e.getMessage(), e.getCause()); - } - return result; - } - - public Result updateFileDetail(FileUpdateRequest fileUpdateRequest) - throws ForbiddenException, TooManyRequestsException, InternalServerException, UnauthorizedException, - BadRequestException, UnknownException { - Result result = null; - Map headers = Utils.getHeaders(imageKit); - String url = String.format(Locale.US, API_BASE_URL.concat("v1/files/%s/details"), - fileUpdateRequest.getFileId()); - request = new Request.Builder().url(url).patch(multipartBuilder.build(fileUpdateRequest)) - .headers(Headers.of(headers)).build(); - - try { - Response response = client.newCall(request).execute(); - String respBody = ""; - if (response.code() == 200) { - respBody = response.body().string(); - result = new Gson().fromJson(respBody, Result.class); - result.setRaw(respBody); - } else { - Utils.generalApiThrowException(response); - } - Utils.populateResponseMetadata(respBody, result.getResponseMetaData(), response.code(), - response.headers().toMultimap()); - } catch (IOException e) { - throw new UnknownException(e.getMessage(), e.getCause()); - } - return result; - } - - public ResultList getFileList(GetFileListRequest getFileListRequest) throws ForbiddenException, TooManyRequestsException, - InternalServerException, UnauthorizedException, BadRequestException, UnknownException, InstantiationException, IllegalAccessException { - ResultList resultList = new ResultList(); - Map headers = Utils.getHeaders(imageKit); - - QueryMaker queryMaker = new QueryMaker(); - Map options = new HashMap<>(); - if (getFileListRequest.getType() != null) { - options.put("type", getFileListRequest.getType()); - } - if (getFileListRequest.getSort() != null) { - options.put("sort", getFileListRequest.getSort()); - } - if (getFileListRequest.getPath() != null) { - options.put("path", getFileListRequest.getPath()); - } - if (getFileListRequest.getSearchQuery() != null) { - options.put("searchQuery", getFileListRequest.getSearchQuery()); - } - if (getFileListRequest.getFileType() != null) { - options.put("fileType", getFileListRequest.getFileType()); - } - if (getFileListRequest.getLimit() != null) { - options.put("limit", getFileListRequest.getLimit()); - } - if (getFileListRequest.getSkip() != null) { - options.put("skip", getFileListRequest.getSkip()); - } - if (getFileListRequest.getTags() != null) { - options.put("tags", String.join(",", getFileListRequest.getTags())); - } - for (Map.Entry entry : options.entrySet()) { - queryMaker.put(String.format("%s=%s", entry.getKey(), entry.getValue())); - } - - String url = String.format(Locale.US, API_BASE_URL.concat("v1/files?%s"), queryMaker.get()); - - request = new Request.Builder().url(url).get().headers(Headers.of(headers)).build(); - - try { - Response response = client.newCall(request).execute(); - String respBody = ""; - if (response.code() == 200) { - respBody = response.body().string(); - List files = new Gson().fromJson(respBody, - new TypeToken>() { - }.getType()); - resultList.setResults(files); - resultList.setRaw(respBody); - } else { - Utils.generalApiThrowException(response); - } - Utils.populateResponseMetadata(respBody, resultList.getResponseMetaData(), response.code(), - response.headers().toMultimap()); - } catch (IOException e) { - throw new UnknownException(e.getMessage(), e.getCause()); - } - return resultList; - } - - public Result getFileDetail(String fileId) throws ForbiddenException, TooManyRequestsException, - InternalServerException, UnauthorizedException, BadRequestException, UnknownException { - Result result = new Result(); - Map headers = Utils.getHeaders(imageKit); - - String url = String.format(Locale.US, API_BASE_URL.concat("v1/files/%s/details"), fileId); - - request = new Request.Builder().url(url).get().headers(Headers.of(headers)).build(); - - try { - Response response = client.newCall(request).execute(); - String respBody = ""; - if (response.code() == 200) { - respBody = response.body().string(); - result = new Gson().fromJson(respBody, Result.class); - result.setRaw(respBody); - } else { - Utils.generalApiThrowException(response); - } - Utils.populateResponseMetadata(respBody, result.getResponseMetaData(), response.code(), - response.headers().toMultimap()); - } catch (IOException e) { - throw new UnknownException(e.getMessage(), e.getCause()); - } - return result; - } - - public ResultMetaData getFileMetaData(String fileId) throws ForbiddenException, TooManyRequestsException, - InternalServerException, UnauthorizedException, BadRequestException, UnknownException { - ResultMetaData result = new ResultMetaData(); - Map headers = Utils.getHeaders(imageKit); - - String url = String.format(Locale.US, API_BASE_URL.concat("v1/files/%s/metadata"), fileId); - - request = new Request.Builder().url(url).get().headers(Headers.of(headers)).build(); - - try { - Response response = client.newCall(request).execute(); - String respBody = ""; - if (response.code() == 200) { - respBody = response.body().string(); - MetaData metaData = new Gson().fromJson(respBody, MetaData.class); - result.setResults(metaData); - result.setRaw(respBody); - } else { - Utils.generalApiThrowException(response); - } - Utils.populateResponseMetadata(respBody, result.getResponseMetaData(), response.code(), - response.headers().toMultimap()); - } catch (IOException e) { - throw new UnknownException(e.getMessage(), e.getCause()); - } - return result; - } - - public ResultMetaData getRemoteFileMetaData(String url) throws ForbiddenException, TooManyRequestsException, - InternalServerException, UnauthorizedException, BadRequestException, UnknownException { - ResultMetaData result = new ResultMetaData(); - Map headers = Utils.getHeaders(imageKit); - - String apiURL = API_BASE_URL.concat("v1/metadata?url=") + url; - - request = new Request.Builder().url(apiURL).get().headers(Headers.of(headers)).build(); - - try { - Response response = client.newCall(request).execute(); - String respBody = ""; - if (response.code() == 200) { - respBody = response.body().string(); - MetaData metaData = new Gson().fromJson(respBody, MetaData.class); - result.setResults(metaData); - result.setRaw(respBody); - } else { - Utils.generalApiThrowException(response); - } - Utils.populateResponseMetadata(respBody, result.getResponseMetaData(), response.code(), - response.headers().toMultimap()); - } catch (IOException e) { - throw new UnknownException(e.getMessage(), e.getCause()); - } - return result; - } - - public Result deleteFile(String fileId) throws ForbiddenException, TooManyRequestsException, - InternalServerException, UnauthorizedException, BadRequestException, UnknownException { - Result result = new Result(); - Map headers = Utils.getHeaders(imageKit); - - String url = String.format(Locale.US, API_BASE_URL.concat("v1/files/%s"), fileId); - - request = new Request.Builder().url(url).delete().headers(Headers.of(headers)).build(); - - try { - Response response = client.newCall(request).execute(); - String respBody = ""; - if (response.code() == 204) { - respBody = response.body().string(); - result.setFileId(fileId); - result.setRaw(respBody); - } else { - Utils.generalApiThrowException(response); - } - Utils.populateResponseMetadata(respBody, result.getResponseMetaData(), response.code(), - response.headers().toMultimap()); - } catch (IOException e) { - throw new UnknownException(e.getMessage(), e.getCause()); - } - return result; - } - - public ResultFileDelete bulkDeleteFiles(List fileIds) - throws ForbiddenException, TooManyRequestsException, InternalServerException, PartialSuccessException, - UnauthorizedException, NotFoundException, BadRequestException, UnknownException { - ResultFileDelete result = new ResultFileDelete(); - Map headers = Utils.getHeaders(imageKit); - - String url = API_BASE_URL.concat("v1/files/batch/deleteByFileIds"); - - request = new Request.Builder().url(url) - .post(multipartBuilder.build(String.format("{\"fileIds\":%s}", new Gson().toJson(fileIds)))) - .headers(Headers.of(headers)).build(); - - try { - Response response = client.newCall(request).execute(); - String respBody = ""; - if (response.code() == 200) { - respBody = response.body().string(); - result = new Gson().fromJson(respBody, ResultFileDelete.class); - result.setRaw(respBody); - } else if (response.code() == 207 || response.code() == 404) { - Utils.throwOtherException(response); - } else { - Utils.generalApiThrowException(response); - } - Utils.populateResponseMetadata(respBody, result.getResponseMetaData(), response.code(), - response.headers().toMultimap()); - } catch (IOException e) { - throw new UnknownException(e.getMessage(), e.getCause()); - } - return result; - } - - public ResultCache purgeCache(String url) throws ForbiddenException, TooManyRequestsException, - InternalServerException, UnauthorizedException, BadRequestException, UnknownException { - ResultCache result = new ResultCache(); - Map headers = Utils.getHeaders(imageKit); - - request = new Request.Builder().url(API_BASE_URL.concat("v1/files/purge")) - .post(multipartBuilder.build(String.format("{\"url\":\"%s\"}", url))).headers(Headers.of(headers)) - .build(); - - try { - Response response = client.newCall(request).execute(); - String respBody = ""; - if (response.code() == 200 || response.code() == 201) { - respBody = response.body().string(); - result = new Gson().fromJson(respBody, ResultCache.class); - result.setRaw(respBody); - } else { - Utils.generalApiThrowException(response); - } - Utils.populateResponseMetadata(respBody, result.getResponseMetaData(), response.code(), - response.headers().toMultimap()); - } catch (IOException e) { - throw new UnknownException(e.getMessage(), e.getCause()); - } - return result; - } - - public ResultCacheStatus getPurgeCacheStatus(String requestId) throws ForbiddenException, TooManyRequestsException, - InternalServerException, UnauthorizedException, BadRequestException, UnknownException { - ResultCacheStatus result = new ResultCacheStatus(); - Map headers = Utils.getHeaders(imageKit); - - String url = String.format(Locale.US, API_BASE_URL.concat("v1/files/purge/%s"), requestId); - - request = new Request.Builder().url(url).get().headers(Headers.of(headers)).build(); - - try { - Response response = client.newCall(request).execute(); - String respBody = ""; - if (response.code() == 200) { - respBody = response.body().string(); - result = new Gson().fromJson(respBody, ResultCacheStatus.class); - result.setRaw(respBody); - } else { - Utils.generalApiThrowException(response); - } - Utils.populateResponseMetadata(respBody, result.getResponseMetaData(), response.code(), - response.headers().toMultimap()); - } catch (IOException e) { - throw new UnknownException(e.getMessage(), e.getCause()); - } - return result; - } - - public ResultTags manageTags(TagsRequest tagsRequest, String action) - throws NotFoundException, PartialSuccessException, BadRequestException, InternalServerException, - UnknownException, ForbiddenException, TooManyRequestsException, UnauthorizedException { - ResultTags resultTags = new ResultTags(); - Map headers = Utils.getHeaders(imageKit); - - RequestBody requestBody = RequestBody.create(okhttp3.MediaType.parse("application/json"), - new Gson().toJson(tagsRequest)); - request = new Request.Builder() - .url(action.equals("removeTags") ? API_BASE_URL.concat("v1/files/removeTags") - : API_BASE_URL.concat("v1/files/addTags")) - .post(requestBody).headers(Headers.of(headers)).build(); - - try { - Response response = client.newCall(request).execute(); - String respBody = ""; - if (response.code() == 200) { - respBody = response.body().string(); - resultTags = new Gson().fromJson(respBody, ResultTags.class); - } else if (response.code() == 207 || response.code() == 404) { - Utils.throwOtherException(response); - } else { - Utils.generalApiThrowException(response); - } - Utils.populateResponseMetadata(respBody, resultTags.getResponseMetaData(), response.code(), - response.headers().toMultimap()); - } catch (IOException e) { - throw new UnknownException(e.getMessage(), e.getCause()); - } - return resultTags; - } - - public ResultTags removeAITags(AITagsRequest aiTagsRequest) - throws PartialSuccessException, NotFoundException, BadRequestException, InternalServerException, - UnknownException, ForbiddenException, TooManyRequestsException, UnauthorizedException { - ResultTags resultTags = new ResultTags(); - Map headers = Utils.getHeaders(imageKit); - - RequestBody requestBody = RequestBody.create(okhttp3.MediaType.parse("application/json"), - new Gson().toJson(aiTagsRequest)); - request = new Request.Builder().url(API_BASE_URL.concat("v1/files/removeAITags")).post(requestBody) - .headers(Headers.of(headers)).build(); - - try { - Response response = client.newCall(request).execute(); - String respBody = ""; - if (response.code() == 200) { - respBody = response.body().string(); - resultTags = new Gson().fromJson(respBody, ResultTags.class); - } else if (response.code() == 207 || response.code() == 404) { - Utils.throwOtherException(response); - } else { - Utils.generalApiThrowException(response); - } - Utils.populateResponseMetadata(respBody, resultTags.getResponseMetaData(), response.code(), - response.headers().toMultimap()); - - } catch (IOException e) { - throw new UnknownException(e.getMessage(), e.getCause()); - } - return resultTags; - } - - public ResultCustomMetaDataFieldList getCustomMetaDataFields(boolean includeDeleted) throws UnknownException { - ResultCustomMetaDataFieldList resultCustomMetaDataFieldList = new ResultCustomMetaDataFieldList(); - - Map headers = Utils.getHeaders(imageKit); - - request = new Request.Builder() - .url(API_BASE_URL.concat("v1/customMetadataFields?includeDeleted=" + includeDeleted)).get() - .headers(Headers.of(headers)).build(); - - try { - Response response = client.newCall(request).execute(); - String respBody = ""; - if (response.code() == 200) { - respBody = response.body().string(); - List resultCustomMetaDataFields = new Gson().fromJson(respBody, - new TypeToken>() { - }.getType()); - resultCustomMetaDataFieldList.setResultCustomMetaDataFieldList(resultCustomMetaDataFields); - } - Utils.populateResponseMetadata(respBody, resultCustomMetaDataFieldList.getResponseMetaData(), - response.code(), response.headers().toMultimap()); - } catch (IOException e) { - throw new UnknownException(e.getMessage(), e.getCause()); - } - return resultCustomMetaDataFieldList; - } - - public ResultCustomMetaDataField createCustomMetaDataFields( - CustomMetaDataFieldCreateRequest customMetaDataFieldCreateRequest) - throws BadRequestException, UnknownException { - if (customMetaDataFieldCreateRequest.getName() == null) { - throw new RuntimeException("Error: Name not provided."); - } - if (customMetaDataFieldCreateRequest.getLabel() == null) { - throw new RuntimeException("Error: Label not provided."); - } - ResultCustomMetaDataField resultCustomMetaDataField = new ResultCustomMetaDataField(); - Map headers = Utils.getHeaders(imageKit); - - RequestBody requestBody = RequestBody.create(okhttp3.MediaType.parse("application/json"), - new Gson().toJson(customMetaDataFieldCreateRequest)); - request = new Request.Builder().url(API_BASE_URL.concat("v1/customMetadataFields")).post(requestBody) - .headers(Headers.of(headers)).build(); - - try { - Response response = client.newCall(request).execute(); - String respBody = ""; - if (response.code() == 201) { - respBody = response.body().string(); - JsonElement responseBody = new JsonParser().parse(respBody); - resultCustomMetaDataField = new Gson().fromJson(responseBody, ResultCustomMetaDataField.class); - } else { - if (response.code() == 400) { - ResultException result = Utils.populateResult(response); - throw new BadRequestException(result.getMessage(), null, false, false, result.getMessage(), - result.getHelp(), result.getResponseMetaData()); - } - } - Utils.populateResponseMetadata(respBody, resultCustomMetaDataField.getResponseMetaData(), response.code(), - response.headers().toMultimap()); - } catch (IOException e) { - throw new UnknownException(e.getMessage(), e.getCause()); - } - return resultCustomMetaDataField; - } - - public ResultNoContent deleteCustomMetaDataField(String id) throws NotFoundException, UnknownException { - ResultNoContent resultNoContent = new ResultNoContent(); - Map headers = Utils.getHeaders(imageKit); - - String url = String.format(Locale.US, API_BASE_URL.concat("v1/customMetadataFields/%s"), id); - - request = new Request.Builder().url(url).delete().headers(Headers.of(headers)).build(); - - try { - Response response = client.newCall(request).execute(); - String respBody = ""; - if (response.code() == 204) { - String respString = response.body().string(); - respBody = respString == null ? "" : respString; - } else { - if (response.code() == 404) { - ResultException result = Utils.populateResult(response); - throw new NotFoundException(result.getMessage(), null, false, false, result.getMessage(), - result.getHelp(), result.getResponseMetaData()); - } - } - Utils.populateResponseMetadata(respBody, resultNoContent.getResponseMetaData(), response.code(), - response.headers().toMultimap()); - } catch (IOException e) { - throw new UnknownException(e.getMessage(), e.getCause()); - } - return resultNoContent; - } - - public ResultCustomMetaDataField updateCustomMetaDataFields( - CustomMetaDataFieldUpdateRequest customMetaDataFieldUpdateRequest) - throws BadRequestException, NotFoundException, UnknownException { - ResultCustomMetaDataField resultCustomMetaDataField = new ResultCustomMetaDataField(); - - Map headers = Utils.getHeaders(imageKit); - - RequestBody requestBody = RequestBody.create(okhttp3.MediaType.parse("application/json"), - new Gson().toJson(customMetaDataFieldUpdateRequest)); - String url = String.format(Locale.US, API_BASE_URL.concat("v1/customMetadataFields/%s"), - customMetaDataFieldUpdateRequest.getId()); - request = new Request.Builder().url(url).patch(requestBody).headers(Headers.of(headers)).build(); - - try { - Response response = client.newCall(request).execute(); - String respBody = ""; - if (response.code() == 200) { - respBody = response.body().string(); - JsonElement responseBody = new JsonParser().parse(respBody); - resultCustomMetaDataField = new Gson().fromJson(responseBody, ResultCustomMetaDataField.class); - } else { - if (response.code() == 400 || response.code() == 404) { - ResultException result = Utils.populateResult(response); - if (response.code() == 400) { - throw new BadRequestException(result.getMessage(), null, false, false, result.getMessage(), - result.getHelp(), result.getResponseMetaData()); - } else { - throw new NotFoundException(result.getMessage(), null, false, false, result.getMessage(), - result.getHelp(), result.getResponseMetaData()); - } - } - } - Utils.populateResponseMetadata(respBody, resultCustomMetaDataField.getResponseMetaData(), response.code(), - response.headers().toMultimap()); - } catch (IOException e) { - throw new UnknownException(e.getMessage(), e.getCause()); - } - return resultCustomMetaDataField; - } - - public ResultNoContent deleteFileVersion(DeleteFileVersionRequest deleteFileVersionRequest) - throws BadRequestException, NotFoundException, InternalServerException, UnknownException, - ForbiddenException, TooManyRequestsException, UnauthorizedException { - ResultNoContent resultNoContent = new ResultNoContent(); - - Map headers = Utils.getHeaders(imageKit); - - String url = String.format(Locale.US, API_BASE_URL.concat("v1/files/%s/versions/%s"), - deleteFileVersionRequest.getFileId(), deleteFileVersionRequest.getVersionId()); - request = new Request.Builder().url(url).delete().headers(Headers.of(headers)).build(); - - try { - Response response = client.newCall(request).execute(); - String respBody = ""; - if (response.code() == 204) { - String respString = response.body().string(); - respBody = respString == null ? "" : respString; - } else if (response.code() == 400 || response.code() == 404) { - ResultException result = Utils.populateResult(response); - if (response.code() == 400) { - throw new BadRequestException(result.getMessage(), null, false, false, result.getMessage(), - result.getHelp(), result.getResponseMetaData()); - } else { - throw new NotFoundException(result.getMessage(), null, false, false, result.getMessage(), - result.getHelp(), result.getResponseMetaData()); - } - } else { - Utils.generalApiThrowException(response); - } - Utils.populateResponseMetadata(respBody, resultNoContent.getResponseMetaData(), response.code(), - response.headers().toMultimap()); - } catch (IOException e) { - throw new UnknownException(e.getMessage(), e.getCause()); - } - return resultNoContent; - } - - public ResultNoContent copyFile(CopyFileRequest copyFileRequest) - throws NotFoundException, BadRequestException, InternalServerException, UnknownException, - ForbiddenException, TooManyRequestsException, UnauthorizedException { - ResultNoContent resultNoContent = new ResultNoContent(); - Map headers = Utils.getHeaders(imageKit); - - RequestBody requestBody = RequestBody.create(okhttp3.MediaType.parse("application/json"), - new Gson().toJson(copyFileRequest)); - request = new Request.Builder().url(API_BASE_URL.concat("v1/files/copy")).post(requestBody) - .headers(Headers.of(headers)).build(); - - try { - Response response = client.newCall(request).execute(); - String respBody = ""; - if (response.code() == 204) { - String respString = response.body().string(); - respBody = respString == null ? "" : respString; - } else if (response.code() == 404) { - ResultException result = Utils.populateResult(response); - throw new NotFoundException(result.getMessage(), null, false, false, result.getMessage(), - result.getHelp(), result.getResponseMetaData()); - } else { - Utils.generalApiThrowException(response); - } - Utils.populateResponseMetadata(respBody, resultNoContent.getResponseMetaData(), response.code(), - response.headers().toMultimap()); - } catch (IOException e) { - throw new UnknownException(e.getMessage(), e.getCause()); - } - return resultNoContent; - } - - public ResultNoContent moveFile(MoveFileRequest moveFileRequest) - throws NotFoundException, BadRequestException, InternalServerException, UnknownException, - ForbiddenException, TooManyRequestsException, UnauthorizedException { - ResultNoContent resultNoContent = new ResultNoContent(); - Map headers = Utils.getHeaders(imageKit); - - RequestBody requestBody = RequestBody.create(okhttp3.MediaType.parse("application/json"), - new Gson().toJson(moveFileRequest)); - request = new Request.Builder().url(API_BASE_URL.concat("v1/files/move")).post(requestBody) - .headers(Headers.of(headers)).build(); - - try { - Response response = client.newCall(request).execute(); - String respBody = ""; - if (response.code() == 204) { - String respString = response.body().string(); - respBody = respString == null ? "" : respString; - } else if (response.code() == 404) { - ResultException result = Utils.populateResult(response); - throw new NotFoundException(result.getMessage(), null, false, false, result.getMessage(), - result.getHelp(), result.getResponseMetaData()); - } else { - Utils.generalApiThrowException(response); - } - Utils.populateResponseMetadata(respBody, resultNoContent.getResponseMetaData(), response.code(), - response.headers().toMultimap()); - } catch (IOException e) { - throw new UnknownException(e.getMessage(), e.getCause()); - } - return resultNoContent; - } - - public ResultRenameFile renameFile(RenameFileRequest renameFileRequest) throws PartialSuccessException, - ConflictException, NotFoundException, BadRequestException, InternalServerException, UnknownException, - ForbiddenException, TooManyRequestsException, UnauthorizedException { - ResultRenameFile resultRenameFile = new ResultRenameFile(); - Map headers = Utils.getHeaders(imageKit); - - RequestBody requestBody = RequestBody.create(okhttp3.MediaType.parse("application/json"), - new Gson().toJson(renameFileRequest)); - request = new Request.Builder().url(API_BASE_URL.concat("v1/files/rename")).put(requestBody) - .headers(Headers.of(headers)).build(); - - try { - Response response = client.newCall(request).execute(); - String respBody = ""; - if (response.code() == 200) { - String respString = response.body().string(); - respBody = respString == null || respString.equals("") ? "{}" : respString; - resultRenameFile = new Gson().fromJson(respBody, ResultRenameFile.class); - } else if (response.code() == 207 || response.code() == 404) { - Utils.throwOtherException(response); - } else if (response.code() == 409) { - ResultException result = Utils.populateResult(response); - throw new ConflictException(result.getMessage(), null, false, false, result.getMessage(), - result.getHelp(), result.getResponseMetaData()); - } else { - Utils.generalApiThrowException(response); - } - Utils.populateResponseMetadata(respBody, resultRenameFile.getResponseMetaData(), response.code(), - response.headers().toMultimap()); - } catch (IOException e) { - throw new UnknownException(e.getMessage(), e.getCause()); - } - return resultRenameFile; - } - - public Result restoreFileVersion(String fileId, String versionId) - throws NotFoundException, BadRequestException, InternalServerException, UnknownException, - ForbiddenException, TooManyRequestsException, UnauthorizedException { - Result resultFileVersionDetails = new Result(); - Map headers = Utils.getHeaders(imageKit); - - String url = String.format(Locale.US, API_BASE_URL.concat("v1/files/%s/versions/%s/restore"), fileId, - versionId); - RequestBody requestBody = RequestBody.create(okhttp3.MediaType.parse("application/json"), ""); - request = new Request.Builder().url(url).put(requestBody).headers(Headers.of(headers)).build(); - - try { - Response response = client.newCall(request).execute(); - String respBody = ""; - if (response.code() == 200) { - System.out.println("20000000000000"); - respBody = response.body().string(); - resultFileVersionDetails = new Gson().fromJson(respBody, Result.class); - } else if (response.code() == 404) { - System.out.println("400000000000004"); - ResultException result = Utils.populateResult(response); - throw new NotFoundException(result.getMessage(), null, false, false, result.getMessage(), - result.getHelp(), result.getResponseMetaData()); - } else { - Utils.generalApiThrowException(response); - } - Utils.populateResponseMetadata(respBody, resultFileVersionDetails.getResponseMetaData(), response.code(), - response.headers().toMultimap()); - } catch (IOException e) { - throw new UnknownException(e.getMessage(), e.getCause()); - } - return resultFileVersionDetails; - } - - public ResultEmptyBlock createFolder(CreateFolderRequest createFolderRequest) throws UnknownException { - ResultEmptyBlock resultEmptyBlock = new ResultEmptyBlock(); - Map headers = Utils.getHeaders(imageKit); - - RequestBody requestBody = RequestBody.create(okhttp3.MediaType.parse("application/json"), - new Gson().toJson(createFolderRequest)); - request = new Request.Builder().url(API_BASE_URL.concat("v1/folder/")).post(requestBody) - .headers(Headers.of(headers)).build(); - - try { - Response response = client.newCall(request).execute(); - String respBody = ""; - if (response.code() == 201) { - String respString = response.body().string(); - respBody = respString == null || respString.equals("") ? "{}" : respString; - } - Utils.populateResponseMetadata(respBody, resultEmptyBlock.getResponseMetaData(), response.code(), - response.headers().toMultimap()); - } catch (IOException e) { - throw new UnknownException(e.getMessage(), e.getCause()); - } - return resultEmptyBlock; - } - - public ResultNoContent deleteFolder(DeleteFolderRequest deleteFolderRequest) - throws NotFoundException, BadRequestException, InternalServerException, UnknownException, - ForbiddenException, TooManyRequestsException, UnauthorizedException { - ResultNoContent resultNoContent = new ResultNoContent(); - Map headers = Utils.getHeaders(imageKit); - - RequestBody requestBody = RequestBody.create(okhttp3.MediaType.parse("application/json"), - new Gson().toJson(deleteFolderRequest)); - request = new Request.Builder().url(API_BASE_URL.concat("v1/folder/")).delete(requestBody) - .headers(Headers.of(headers)).build(); - - try { - Response response = client.newCall(request).execute(); - String respBody = ""; - if (response.code() == 204) { - String respString = response.body().string(); - respBody = respString == null ? "" : respString; - } else if (response.code() == 404) { - ResultException result = Utils.populateResult(response); - throw new NotFoundException(result.getMessage(), null, false, false, result.getMessage(), - result.getHelp(), result.getResponseMetaData()); - } else { - Utils.generalApiThrowException(response); - } - Utils.populateResponseMetadata(respBody, resultNoContent.getResponseMetaData(), response.code(), - response.headers().toMultimap()); - } catch (IOException e) { - throw new UnknownException(e.getMessage(), e.getCause()); - } - return resultNoContent; - } - - public ResultOfFolderActions copyFolder(CopyFolderRequest copyFolderRequest) - throws NotFoundException, BadRequestException, InternalServerException, UnknownException, - ForbiddenException, TooManyRequestsException, UnauthorizedException { - ResultOfFolderActions resultOfFolderActions = new ResultOfFolderActions(); - Map headers = Utils.getHeaders(imageKit); - - RequestBody requestBody = RequestBody.create(okhttp3.MediaType.parse("application/json"), - new Gson().toJson(copyFolderRequest)); - - request = new Request.Builder().url(API_BASE_URL.concat("v1/bulkJobs/moveFolder")).post(requestBody) - .headers(Headers.of(headers)).build(); - - try { - Response response = client.newCall(request).execute(); - String respBody = ""; - if (response.code() == 200) { - respBody = response.body().string(); - resultOfFolderActions = new Gson().fromJson(respBody, ResultOfFolderActions.class); - } else if (response.code() == 404) { - ResultException result = Utils.populateResult(response); - throw new NotFoundException(result.getMessage(), null, false, false, result.getMessage(), - result.getHelp(), result.getResponseMetaData()); - } else { - Utils.generalApiThrowException(response); - } - Utils.populateResponseMetadata(respBody, resultOfFolderActions.getResponseMetaData(), response.code(), - response.headers().toMultimap()); - } catch (IOException e) { - throw new UnknownException(e.getMessage(), e.getCause()); - } - return resultOfFolderActions; - } - - public ResultOfFolderActions moveFolder(MoveFolderRequest moveFolderRequest) - throws NotFoundException, BadRequestException, InternalServerException, UnknownException, - ForbiddenException, TooManyRequestsException, UnauthorizedException { - ResultOfFolderActions resultOfFolderActions = new ResultOfFolderActions(); - Map headers = Utils.getHeaders(imageKit); - - RequestBody requestBody = RequestBody.create(okhttp3.MediaType.parse("application/json"), - new Gson().toJson(moveFolderRequest)); - - request = new Request.Builder().url(API_BASE_URL.concat("v1/bulkJobs/moveFolder")).post(requestBody) - .headers(Headers.of(headers)).build(); - - try { - Response response = client.newCall(request).execute(); - String respBody = ""; - if (response.code() == 200) { - respBody = response.body().string(); - resultOfFolderActions = new Gson().fromJson(respBody, ResultOfFolderActions.class); - } else if (response.code() == 404) { - ResultException result = Utils.populateResult(response); - throw new NotFoundException(result.getMessage(), null, false, false, result.getMessage(), - result.getHelp(), result.getResponseMetaData()); - } else { - Utils.generalApiThrowException(response); - } - Utils.populateResponseMetadata(respBody, resultOfFolderActions.getResponseMetaData(), response.code(), - response.headers().toMultimap()); - } catch (IOException e) { - throw new UnknownException(e.getMessage(), e.getCause()); - } - return resultOfFolderActions; - } - - public ResultBulkJobStatus getBulkJobStatus(String jobId) throws ForbiddenException, TooManyRequestsException, - InternalServerException, UnauthorizedException, BadRequestException, UnknownException { - ResultBulkJobStatus resultBulkJobStatus = new ResultBulkJobStatus(); - - Map headers = Utils.getHeaders(imageKit); - - String url = String.format(Locale.US, API_BASE_URL.concat("v1/bulkJobs/%s"), jobId); - - request = new Request.Builder().url(url).get().headers(Headers.of(headers)).build(); - - try { - Response response = client.newCall(request).execute(); - String respBody = ""; - if (response.code() == 200) { - respBody = response.body().string(); - resultBulkJobStatus = new Gson().fromJson(respBody, ResultBulkJobStatus.class); - } else { - Utils.generalApiThrowException(response); - } - Utils.populateResponseMetadata(respBody, resultBulkJobStatus.getResponseMetaData(), response.code(), - response.headers().toMultimap()); - } catch (IOException e) { - throw new UnknownException(e.getMessage(), e.getCause()); - } - return resultBulkJobStatus; - } - - public ResultFileVersions getFileVersions(String fileId) - throws NotFoundException, BadRequestException, InternalServerException, UnknownException, - ForbiddenException, TooManyRequestsException, UnauthorizedException { - ResultFileVersions resultFileVersions = new ResultFileVersions(); - Map headers = Utils.getHeaders(imageKit); - - String url = String.format(Locale.US, API_BASE_URL.concat("v1/files/%s/versions"), fileId); - - request = new Request.Builder().url(url).get().headers(Headers.of(headers)).build(); - - try { - Response response = client.newCall(request).execute(); - String respBody = ""; - if (response.code() == 200) { - respBody = response.body().string(); - List resultFileVersionDetailsList = new Gson().fromJson(respBody, - new TypeToken>() { - }.getType()); - resultFileVersions.setResultFileVersionDetailsList(resultFileVersionDetailsList); - } else if (response.code() == 404) { - ResultException result = Utils.populateResult(response); - throw new NotFoundException(result.getMessage(), null, false, false, result.getMessage(), - result.getHelp(), result.getResponseMetaData()); - } else { - Utils.generalApiThrowException(response); - } - Utils.populateResponseMetadata(respBody, resultFileVersions.getResponseMetaData(), response.code(), - response.headers().toMultimap()); - } catch (IOException e) { - throw new UnknownException(e.getMessage(), e.getCause()); - } - return resultFileVersions; - } - - public ResultFileVersionDetails getFileVersionDetails(String fileId, String versionId) - throws NotFoundException, BadRequestException, InternalServerException, UnknownException, - ForbiddenException, TooManyRequestsException, UnauthorizedException { - if (fileId == null) { - throw new RuntimeException("Error: FileId not provided."); - } - if (versionId == null) { - throw new RuntimeException("Error: versionId not provided."); - } - ResultFileVersionDetails resultFileVersionDetails = new ResultFileVersionDetails(); - Map headers = Utils.getHeaders(imageKit); - - String url = String.format(Locale.US, API_BASE_URL.concat("v1/files/%s/versions/%s"), fileId, versionId); - - request = new Request.Builder().url(url).get().headers(Headers.of(headers)).build(); - - try { - Response response = client.newCall(request).execute(); - String respBody = ""; - if (response.code() == 200) { - respBody = response.body().string(); - resultFileVersionDetails = new Gson().fromJson(respBody, ResultFileVersionDetails.class); - } else if (response.code() == 404) { - ResultException result = Utils.populateResult(response); - throw new NotFoundException(result.getMessage(), null, false, false, result.getMessage(), - result.getHelp(), result.getResponseMetaData()); - } else { - Utils.generalApiThrowException(response); - } - Utils.populateResponseMetadata(respBody, resultFileVersionDetails.getResponseMetaData(), response.code(), - response.headers().toMultimap()); - } catch (IOException e) { - throw new UnknownException(e.getMessage(), e.getCause()); - } - return resultFileVersionDetails; - } -} diff --git a/imagekit-sdk/src/main/java/io/imagekit/sdk/tasks/UrlGen.java b/imagekit-sdk/src/main/java/io/imagekit/sdk/tasks/UrlGen.java deleted file mode 100644 index 771e078..0000000 --- a/imagekit-sdk/src/main/java/io/imagekit/sdk/tasks/UrlGen.java +++ /dev/null @@ -1,212 +0,0 @@ -package io.imagekit.sdk.tasks; - -import io.imagekit.sdk.ImageKit; -import io.imagekit.sdk.config.Configuration; -import io.imagekit.sdk.constants.Transformer; -import io.imagekit.sdk.constants.Version; -import org.apache.commons.codec.digest.HmacUtils; - -import java.net.URI; -import java.net.URISyntaxException; -import java.util.*; - -public class UrlGen { - - private static final long DEFAULT_TIMESTAMP = 9999999999L; - - public static String getUrl(Map options) { - String path = (String) options.get("path"); - String urlEndpoint = (String) options.get("urlEndpoint"); - String src = (String) options.get("src"); - Map queryParams = (Map) options.get("queryParameters"); - List> transformation = (List>) options.get("transformation"); - String transformationPosition = (String) options.get("transformationPosition"); - boolean signed = false; - if (null != options.get("signed")) { - signed = (boolean) options.get("signed"); - } - long expire = 0; - if (null != options.get("expireSeconds")) { - expire = (long) (int) options.get("expireSeconds"); - } - return UrlGen.generateUrl(path, urlEndpoint, src, queryParams, transformation, transformationPosition, signed, - expire); - } - - private static String generateUrl(String path, String urlEndpoint, String src, Map queryParameters, - List> transformation, String transformationPosition, boolean signed, - long expireSeconds) { - Configuration config = ImageKit.getInstance().getConfig(); - if (urlEndpoint == null) { - urlEndpoint = config.getUrlEndpoint(); - } - if (urlEndpoint.charAt(urlEndpoint.length() - 1) != '/') { - urlEndpoint += "/"; - } - String newUrl = null; - if (null != src) { - newUrl = buildFullUrl(src, queryParameters, transformation, transformationPosition, signed, expireSeconds, - config.getPrivateKey(), urlEndpoint); - } else { - if ("query".equalsIgnoreCase(transformationPosition)) { - newUrl = buildFullUrl(urlEndpoint + (path.charAt(0) == '/' ? path.substring(1, path.length()) : path), - queryParameters, transformation, transformationPosition, signed, expireSeconds, - config.getPrivateKey(), urlEndpoint); - } else { - newUrl = buildPathUrl(path.charAt(0) == '/' ? path : "/" + path, urlEndpoint, queryParameters, - transformation, transformationPosition, signed, expireSeconds, config.getPrivateKey()); - } - } - return newUrl; - } - - private static String buildPathUrl(String path, String urlEndpoint, Map queryParameters, - List> transformation, String transformationPosition, boolean signed, long expireSeconds, - String privateKey) { - - StringBuilder tr = new StringBuilder(""); - if (transformation != null && transformation.size() > 0) { - tr.append("tr"); - for (Map map : transformation) { - Set> entries = map.entrySet(); - tr.append(":"); - int i = 0; - for (Map.Entry entry : entries) { - String key = entry.getKey(); - String value = entry.getValue(); - String element = Transformer.getInstance().transform(key) - + (value.equalsIgnoreCase("-") ? "" : "-" + value); - tr.append(element.contains("oi") || element.contains("di") - ? element.replaceFirst("/", "").replaceAll("/", "@@") - : element); - if (i < entries.size() - 1) { - tr.append(","); - } - i++; - } - } - } - - QueryMaker queryMaker = new QueryMaker(); - if (null != queryParameters) { - for (Map.Entry entry : queryParameters.entrySet()) { - queryMaker.put(String.format(Locale.US, "%s=%s", entry.getKey(), entry.getValue())); - } - } - - URI baseUrl = URI.create(urlEndpoint); - URI newUri = null; - try { - String newPath = baseUrl.getPath(); - if (tr.toString().equalsIgnoreCase("")) { - newPath += path.substring(1, path.length()); - } else { - newPath += tr + path; - } - - URI tmpUri = new URI(baseUrl.getScheme(), baseUrl.getUserInfo(), baseUrl.getHost(), baseUrl.getPort(), - newPath, queryMaker.get(), null); - - if (signed) { - sign(urlEndpoint, expireSeconds, privateKey, queryMaker, tmpUri); - } - - newUri = new URI(baseUrl.getScheme(), baseUrl.getUserInfo(), baseUrl.getHost(), baseUrl.getPort(), newPath, - queryMaker.get(), null); - - } catch (URISyntaxException e) { - e.printStackTrace(); - } - return newUri.toString(); - } - - private static String buildFullUrl(String src, Map queryParameters, - List> transformation, String transformationPosition, boolean signed, long expireSeconds, - String privateKey, String urlEndpoint) { - StringBuilder tr = new StringBuilder(""); - if (transformation != null && transformation.size() > 0) { - tr.append("tr="); - for (Map map : transformation) { - Set> entries = map.entrySet(); - if (!tr.toString().equalsIgnoreCase("tr=")) - tr.append(":"); - int i = 0; - for (Map.Entry entry : entries) { - String key = entry.getKey(); - String value = entry.getValue(); - String element = Transformer.getInstance().transform(key) - + (value.equalsIgnoreCase("-") ? "" : "-" + value); - tr.append(element); - if (i < entries.size() - 1) { - tr.append(","); - } - i++; - } - } - } - - QueryMaker queryMaker = new QueryMaker(); - - // check existing query params - if (null != src) { - String[] parts = src.split("\\?"); - if (parts.length > 1) { - String[] queries = parts[1].split("&"); - for (String query : queries) { - queryMaker.put(query); - } - } - } - - if (null != queryParameters) { - for (Map.Entry entry : queryParameters.entrySet()) { - queryMaker.put(String.format(Locale.US, "%s=%s", entry.getKey(), entry.getValue())); - } - } - if (!tr.toString().equalsIgnoreCase("")) { - queryMaker.put(tr.toString()); - } - - URI baseUrl = URI.create(src); - URI newUri = null; - try { - String newPath = baseUrl.getPath(); - URI tmpUri = new URI(baseUrl.getScheme(), baseUrl.getUserInfo(), baseUrl.getHost(), baseUrl.getPort(), - newPath, queryMaker.get(), null); - - if (signed) { - sign(urlEndpoint, expireSeconds, privateKey, queryMaker, tmpUri); - } - - newUri = new URI(baseUrl.getScheme(), baseUrl.getUserInfo(), baseUrl.getHost(), baseUrl.getPort(), newPath, - queryMaker.get(), null); - } catch (URISyntaxException e) { - e.printStackTrace(); - } - return newUri.toString(); - } - - private static void sign(String urlEndpoint, long expireSeconds, String privateKey, QueryMaker queryMaker, - URI tmpUri) { - long expiryTimestamp = DEFAULT_TIMESTAMP; - if (expireSeconds > 0) { - expiryTimestamp = ((Calendar.getInstance().getTimeInMillis() / 1000) + expireSeconds); - } - String signature = signUrl(privateKey, tmpUri.toString(), urlEndpoint, expiryTimestamp); - if (expiryTimestamp > 0 && expiryTimestamp != DEFAULT_TIMESTAMP) { - queryMaker.put("ik-t=" + expiryTimestamp); - } - queryMaker.put("ik-s=" + signature); - } - - public static String signUrl(String privateKey, String url, String urlEndpoint, long expiryTimestamp) { - if (expiryTimestamp < 1) { - expiryTimestamp = DEFAULT_TIMESTAMP; - } - if (urlEndpoint.charAt(urlEndpoint.length() - 1) != '/') { - urlEndpoint += "/"; - } - String replaceUrl = url.replace(urlEndpoint, "") + expiryTimestamp; - return HmacUtils.hmacSha1Hex(privateKey, replaceUrl); - } -} diff --git a/imagekit-sdk/src/main/java/io/imagekit/sdk/utils/Utils.java b/imagekit-sdk/src/main/java/io/imagekit/sdk/utils/Utils.java deleted file mode 100644 index 19fa01c..0000000 --- a/imagekit-sdk/src/main/java/io/imagekit/sdk/utils/Utils.java +++ /dev/null @@ -1,185 +0,0 @@ -package io.imagekit.sdk.utils; - -import com.google.gson.Gson; -import com.google.gson.JsonArray; -import com.google.gson.JsonElement; - -import io.imagekit.sdk.ImageKit; -import io.imagekit.sdk.config.Configuration; -import io.imagekit.sdk.exceptions.BadRequestException; -import io.imagekit.sdk.exceptions.ConflictException; -import io.imagekit.sdk.exceptions.ForbiddenException; -import io.imagekit.sdk.exceptions.InternalServerException; -import io.imagekit.sdk.exceptions.NotFoundException; -import io.imagekit.sdk.exceptions.PartialSuccessException; -import io.imagekit.sdk.exceptions.TooManyRequestsException; -import io.imagekit.sdk.exceptions.UnauthorizedException; -import io.imagekit.sdk.exceptions.UnknownException; -import io.imagekit.sdk.models.ResponseMetaData; -import io.imagekit.sdk.models.results.ResultCache; -import io.imagekit.sdk.models.results.ResultException; -import okhttp3.Credentials; -import okhttp3.Response; - -import java.io.*; -import java.util.ArrayList; -import java.util.Base64; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Properties; -import java.util.Set; -import java.util.stream.Collectors; - -public class Utils { - - public static String listToString(List list) { - StringBuilder builder = new StringBuilder(); - for (int i = 0; i < list.size(); i++) { - if (null != list.get(i)) { - builder.append(list.get(i)); - if (i < list.size() - 1) { - builder.append(","); - } - } - } - return builder.toString(); - } - - public static String fileToBase64(File file) { - String base64File = ""; - try (FileInputStream imageInFile = new FileInputStream(file)) { - // Reading a file from file system - byte fileData[] = new byte[(int) file.length()]; - imageInFile.read(fileData); - base64File = Base64.getEncoder().encodeToString(fileData); - } catch (FileNotFoundException e) { - System.out.println("File not found" + e); - } catch (IOException ioe) { - System.out.println("Exception while reading the file " + ioe); - } - return base64File; - } - - public static byte[] fileToBytes(File file) { - byte[] bytes = null; - try (FileInputStream imageInFile = new FileInputStream(file)) { - // Reading a file from file system - bytes = new byte[(int) file.length()]; - imageInFile.read(bytes); - } catch (FileNotFoundException e) { - System.out.println("File not found" + e); - } catch (IOException ioe) { - System.out.println("Exception while reading the file " + ioe); - } - return bytes; - } - - public static String bytesToBase64(byte[] fileData) { - String base64File = ""; - base64File = Base64.getEncoder().encodeToString(fileData); - return base64File; - } - - /** - * - * @param cls is a Class name from which this method will invoke - * @return it will return object of Configuration class - * @throws IOException if config.properties file doesn't exists - */ - public static Configuration getSystemConfig(Class cls) throws IOException { - Properties properties = new Properties(); - String configFile = "config.properties"; - InputStream is = cls.getClassLoader().getResourceAsStream(configFile); - if (null != is) { - properties.load(is); - } else { - throw new FileNotFoundException("Property file '" + configFile + "' not found in classpath"); - } - Configuration config = new Configuration(); - config.setUrlEndpoint(properties.getProperty("UrlEndpoint")); - config.setPublicKey(properties.getProperty("PublicKey")); - config.setPrivateKey(properties.getProperty("PrivateKey")); - config.validate(); - return config; - } - - public static Map mapListOfStringToString(Map> listMap) { - Map stringMap = new HashMap<>(); - Set>> listMapEntries = listMap.entrySet(); - for (Entry> entry : listMapEntries) { - stringMap.put(entry.getKey(), entry.getValue().stream().collect(Collectors.joining(","))); - - } - return stringMap; - } - - public static void populateResponseMetadata(String respBody, ResponseMetaData responseMetadata, int responseCode, - Map> responseHeaders) throws IOException { - responseMetadata.setRaw(respBody); - if (responseHeaders != null) { - Map mappedHeader = Utils.mapListOfStringToString(responseHeaders); - responseMetadata.setHeaders(mappedHeader); - } - responseMetadata.setHttpStatusCode(responseCode); - } - - public static Map getHeaders(ImageKit imageKit) { - String credential = Credentials.basic(imageKit.getConfig().getPrivateKey(), ""); - Map headers = new HashMap<>(); - headers.put("Accept-Encoding", "application/json"); - headers.put("Content-Type", "application/json"); - headers.put("Authorization", credential); - return headers; - } - - public static void generalApiThrowException(Response response) - throws IOException, BadRequestException, InternalServerException, UnknownException, UnauthorizedException, - ForbiddenException, TooManyRequestsException { - ResultException result = populateResult(response); - if (response.code() == 400) { - throw new BadRequestException(result.getMessage(), null, false, false, result.getMessage(), - result.getHelp(), result.getResponseMetaData()); - } else if (response.code() == 401) { - throw new UnauthorizedException(result.getMessage(), null, false, false, result.getMessage(), - result.getHelp(), result.getResponseMetaData()); - } else if (response.code() == 403) { - throw new ForbiddenException(result.getMessage(), null, false, false, result.getMessage(), result.getHelp(), - result.getResponseMetaData()); - } else if (response.code() == 429) { - throw new TooManyRequestsException(result.getMessage(), null, false, false, result.getMessage(), - result.getHelp(), result.getResponseMetaData()); - } else if (response.code() == 500 || response.code() == 502 || response.code() == 503 - || response.code() == 504) { - throw new InternalServerException(result.getMessage(), null, false, false, result.getMessage(), - result.getHelp(), result.getResponseMetaData()); - } else { - throw new UnknownException(result.getMessage(), null, false, false, result.getMessage(), result.getHelp(), - result.getResponseMetaData()); - } - } - - public static void throwOtherException(Response response) - throws IOException, PartialSuccessException, NotFoundException, UnknownException { - ResultException result = populateResult(response); - if (response.code() == 207) { - throw new PartialSuccessException(result.getMessage(), null, false, false, result.getMessage(), - result.getHelp(), result.getResponseMetaData()); - } else if (response.code() == 404) { - throw new NotFoundException(result.getMessage(), null, false, false, result.getMessage(), result.getHelp(), - result.getResponseMetaData()); - } else { - throw new UnknownException(result.getMessage(), null, false, false, result.getMessage(), result.getHelp(), - result.getResponseMetaData()); - } - } - - public static ResultException populateResult(Response response) throws IOException { - String resp = response.body().string(); - ResultException result = new Gson().fromJson(resp, ResultException.class); - populateResponseMetadata(resp, result.getResponseMetaData(), response.code(), response.headers().toMultimap()); - return result; - } - -} diff --git a/imagekit-sdk/src/test/java/io/imagekit/sdk/FileOperationTest.java b/imagekit-sdk/src/test/java/io/imagekit/sdk/FileOperationTest.java deleted file mode 100644 index 9528413..0000000 --- a/imagekit-sdk/src/test/java/io/imagekit/sdk/FileOperationTest.java +++ /dev/null @@ -1,255 +0,0 @@ -package io.imagekit.sdk; - -import io.imagekit.sdk.exceptions.BadRequestException; -import io.imagekit.sdk.exceptions.ConflictException; -import io.imagekit.sdk.exceptions.ForbiddenException; -import io.imagekit.sdk.exceptions.InternalServerException; -import io.imagekit.sdk.exceptions.NotFoundException; -import io.imagekit.sdk.exceptions.PartialSuccessException; -import io.imagekit.sdk.exceptions.TooManyRequestsException; -import io.imagekit.sdk.exceptions.UnauthorizedException; -import io.imagekit.sdk.exceptions.UnknownException; -import io.imagekit.sdk.models.CopyFileRequest; -import io.imagekit.sdk.models.MoveFileRequest; -import io.imagekit.sdk.models.RenameFileRequest; -import io.imagekit.sdk.tasks.RestClient; -import io.imagekit.sdk.utils.Utils; -import okhttp3.mockwebserver.MockResponse; -import okhttp3.mockwebserver.MockWebServer; -import okhttp3.mockwebserver.RecordedRequest; -import org.junit.Before; -import org.junit.Test; - -import java.io.IOException; - -import static org.junit.Assert.assertEquals; - -public class FileOperationTest { - private ImageKit SUT; - - @Before - public void setUp() throws Exception { - SUT = ImageKit.getInstance(); - SUT.setConfig(Utils.getSystemConfig(ImageKitTest.class)); - } - - @Test(expected = NotFoundException.class) - public void copyFile_404_Expected() - throws InterruptedException, IOException, NotFoundException, BadRequestException, InternalServerException, - UnknownException, ForbiddenException, TooManyRequestsException, UnauthorizedException { - - CopyFileRequest copyFileRequest = new CopyFileRequest(); - copyFileRequest.setSourceFilePath("/sample_image.jpg"); - copyFileRequest.setDestinationPath("/Gallery/"); - copyFileRequest.setIncludeFileVersions(true); - - MockWebServer server = new MockWebServer(); - server.enqueue(new MockResponse().setResponseCode(404) - .setBody("{\n" + " \"message\": \"No file found with filePath /sample_image.jpg\",\n" - + " \"help\": \"For support kindly contact us at support@imagekit.io .\",\n" - + " \"reason\": \"SOURCE_FILE_MISSING\"\n" + "}")); - server.start(); - RestClient.API_BASE_URL = server.url("/").toString(); - SUT.copyFile(copyFileRequest); - server.takeRequest(); - } - - @Test - public void copyFile_successExpected() - throws InterruptedException, IOException, NotFoundException, BadRequestException, InternalServerException, - UnknownException, ForbiddenException, TooManyRequestsException, UnauthorizedException { - - CopyFileRequest copyFileRequest = new CopyFileRequest(); - copyFileRequest.setSourceFilePath("/car_false.jpeg"); - copyFileRequest.setDestinationPath("/Gallery/"); - copyFileRequest.setIncludeFileVersions(true); - - MockWebServer server = new MockWebServer(); - server.enqueue(new MockResponse().setResponseCode(204).setBody("")); - server.start(); - RestClient.API_BASE_URL = server.url("/").toString(); - SUT.copyFile(copyFileRequest); - RecordedRequest request = server.takeRequest(); - - String copyFileRequestJson = "{\"sourceFilePath\":\"/car_false.jpeg\",\"destinationPath\":\"/Gallery/\",\"includeFileVersions\":true}"; - String utf8RequestBody = request.getBody().readUtf8(); - assertEquals(copyFileRequestJson, utf8RequestBody); - assertEquals("application/json; charset=utf-8", request.getHeader("Content-Type")); - assertEquals("POST /v1/files/copy HTTP/1.1", request.getRequestLine()); - assertEquals(RestClient.API_BASE_URL.concat("v1/files/copy"), request.getRequestUrl().toString()); - } - - @Test(expected = NotFoundException.class) - public void moveFile_404_Expected() - throws InterruptedException, IOException, NotFoundException, BadRequestException, InternalServerException, - UnknownException, ForbiddenException, TooManyRequestsException, UnauthorizedException { - - MoveFileRequest moveFileRequest = new MoveFileRequest(); - moveFileRequest.setSourceFilePath("/demo1/sample_image_th.jpg"); - moveFileRequest.setDestinationPath("/"); - - MockWebServer server = new MockWebServer(); - server.enqueue(new MockResponse().setResponseCode(404) - .setBody("{\n" + " \"message\": \"No file found with filePath /demo1/sample_image_th.jpg\",\n" - + " \"help\": \"For support kindly contact us at support@imagekit.io .\",\n" - + " \"reason\": \"SOURCE_FILE_MISSING\"\n" + "}")); - server.start(); - RestClient.API_BASE_URL = server.url("/").toString(); - SUT.moveFile(moveFileRequest); - server.takeRequest(); - } - - @Test - public void moveFile_successExpected() - throws InterruptedException, IOException, NotFoundException, BadRequestException, InternalServerException, - UnknownException, ForbiddenException, TooManyRequestsException, UnauthorizedException { - - MoveFileRequest moveFileRequest = new MoveFileRequest(); - moveFileRequest.setSourceFilePath("/new_la.jpg"); - moveFileRequest.setDestinationPath("test"); - - MockWebServer server = new MockWebServer(); - server.enqueue(new MockResponse().setResponseCode(204).setBody("")); - server.start(); - RestClient.API_BASE_URL = server.url("/").toString(); - SUT.moveFile(moveFileRequest); - RecordedRequest request = server.takeRequest(); - - String moveFileRequestJson = "{\"sourceFilePath\":\"/new_la.jpg\",\"destinationPath\":\"test\"}"; - String utf8RequestBody = request.getBody().readUtf8(); - assertEquals(moveFileRequestJson, utf8RequestBody); - assertEquals("application/json; charset=utf-8", request.getHeader("Content-Type")); - assertEquals("POST /v1/files/move HTTP/1.1", request.getRequestLine()); - assertEquals(RestClient.API_BASE_URL.concat("v1/files/move"), request.getRequestUrl().toString()); - } - - @Test(expected = NotFoundException.class) - public void renameFile_404_Expected() throws InterruptedException, IOException, ConflictException, - PartialSuccessException, NotFoundException, BadRequestException, InternalServerException, UnknownException, - ForbiddenException, TooManyRequestsException, UnauthorizedException { - - RenameFileRequest renameFileRequest = new RenameFileRequest(); - renameFileRequest.setFilePath("/sample_image_th.jpg"); - renameFileRequest.setNewFileName("new_car.jpg"); - renameFileRequest.setPurgeCache(true); - - MockWebServer server = new MockWebServer(); - server.enqueue(new MockResponse().setResponseCode(404) - .setBody("{\n" - + " \"message\": \"No file found in media library with filePath /sample_image_th.jpg\",\n" - + " \"help\": \"For support kindly contact us at support@imagekit.io .\",\n" - + " \"reason\": \"FILE_MISSING\"\n" + "}")); - server.start(); - RestClient.API_BASE_URL = server.url("/").toString(); - SUT.renameFile(renameFileRequest); - server.takeRequest(); - } - - @Test(expected = ConflictException.class) - public void renameFile_409_Expected() throws InterruptedException, IOException, ConflictException, - PartialSuccessException, NotFoundException, BadRequestException, InternalServerException, UnknownException, - ForbiddenException, TooManyRequestsException, UnauthorizedException { - - RenameFileRequest renameFileRequest = new RenameFileRequest(); - renameFileRequest.setFilePath("/new1.jpg"); - renameFileRequest.setNewFileName("new_car.jpg"); - renameFileRequest.setPurgeCache(false); - - MockWebServer server = new MockWebServer(); - server.enqueue(new MockResponse().setResponseCode(409) - .setBody("{\n" - + " \"message\": \"File with name new_car.jpg already exists at the same location.\",\n" - + " \"help\": \"For support kindly contact us at support@imagekit.io .\",\n" - + " \"reason\": \"FILE_ALREADY_EXISTS\"\n" + "}")); - server.start(); - RestClient.API_BASE_URL = server.url("/").toString(); - SUT.renameFile(renameFileRequest); - server.takeRequest(); - } - - @Test - public void renameFile_successExpected() throws InterruptedException, IOException, ConflictException, - PartialSuccessException, NotFoundException, BadRequestException, InternalServerException, UnknownException, - ForbiddenException, TooManyRequestsException, UnauthorizedException { - - RenameFileRequest renameFileRequest = new RenameFileRequest(); - renameFileRequest.setFilePath("/car_false.jpeg"); - renameFileRequest.setNewFileName("new_car.jpeg"); - renameFileRequest.setPurgeCache(false); - - MockWebServer server = new MockWebServer(); - server.enqueue(new MockResponse().setBody("{}")); - server.start(); - RestClient.API_BASE_URL = server.url("/").toString(); - SUT.renameFile(renameFileRequest); - RecordedRequest request = server.takeRequest(); - - String renameFileRequestJson = "{\"filePath\":\"/car_false.jpeg\",\"newFileName\":\"new_car.jpeg\",\"purgeCache\":false}"; - String utf8RequestBody = request.getBody().readUtf8(); - assertEquals(renameFileRequestJson, utf8RequestBody); - assertEquals("application/json; charset=utf-8", request.getHeader("Content-Type")); - assertEquals("PUT /v1/files/rename HTTP/1.1", request.getRequestLine()); - assertEquals(RestClient.API_BASE_URL.concat("v1/files/rename"), request.getRequestUrl().toString()); - } - - @Test - public void renameFile_successExpected_with_purge_cache() throws InterruptedException, IOException, - ConflictException, PartialSuccessException, NotFoundException, BadRequestException, InternalServerException, - UnknownException, ForbiddenException, TooManyRequestsException, UnauthorizedException { - - RenameFileRequest renameFileRequest = new RenameFileRequest(); - renameFileRequest.setFilePath("/car_false.jpeg"); - renameFileRequest.setNewFileName("new_car.jpeg"); - renameFileRequest.setPurgeCache(true); - - MockWebServer server = new MockWebServer(); - server.enqueue( - new MockResponse().setBody("{\n" + " \"purgeRequestId\": \"62b973a00f0ad4164f307dad\"\n" + "}")); - server.start(); - RestClient.API_BASE_URL = server.url("/").toString(); - SUT.renameFile(renameFileRequest); - RecordedRequest request = server.takeRequest(); - - String renameFileRequestJson = "{\"filePath\":\"/car_false.jpeg\",\"newFileName\":\"new_car.jpeg\",\"purgeCache\":true}"; - String utf8RequestBody = request.getBody().readUtf8(); - assertEquals(renameFileRequestJson, utf8RequestBody); - assertEquals("application/json; charset=utf-8", request.getHeader("Content-Type")); - assertEquals("PUT /v1/files/rename HTTP/1.1", request.getRequestLine()); - assertEquals(RestClient.API_BASE_URL.concat("v1/files/rename"), request.getRequestUrl().toString()); - } - - @Test(expected = InternalServerException.class) - public void getBulkJobStatus_500_Expected() - throws InterruptedException, IOException, ForbiddenException, TooManyRequestsException, - InternalServerException, UnauthorizedException, BadRequestException, UnknownException { - - MockWebServer server = new MockWebServer(); - server.enqueue(new MockResponse().setResponseCode(500) - .setBody("{\n" - + " \"message\": \"We have experienced an internal error while processing your request.\",\n" - + " \"help\": \"For support kindly contact us at support@imagekit.io .\"\n" + "}")); - server.start(); - RestClient.API_BASE_URL = server.url("/").toString(); - SUT.getBulkJobStatus("jobId"); - server.takeRequest(); - } - - @Test - public void getBulkJobStatus_successExpected() - throws InterruptedException, IOException, ForbiddenException, TooManyRequestsException, - InternalServerException, UnauthorizedException, BadRequestException, UnknownException { - - MockWebServer server = new MockWebServer(); - server.enqueue(new MockResponse().setBody("{\n" + " \"jobId\": \"629f44ac7eb0fe8173622d4b\",\n" - + " \"type\": \"MOVE_FOLDER\",\n" + " \"status\": \"Completed\"\n" + "}")); - server.start(); - RestClient.API_BASE_URL = server.url("/").toString(); - SUT.getBulkJobStatus("629f44ac7eb0fe8173622d4b"); - RecordedRequest request = server.takeRequest(); - - assertEquals("application/json", request.getHeader("Content-Type")); - assertEquals("GET /v1/bulkJobs/629f44ac7eb0fe8173622d4b HTTP/1.1", request.getRequestLine()); - assertEquals(RestClient.API_BASE_URL.concat("v1/bulkJobs/629f44ac7eb0fe8173622d4b"), - request.getRequestUrl().toString()); - } -} diff --git a/imagekit-sdk/src/test/java/io/imagekit/sdk/FolderOperationTest.java b/imagekit-sdk/src/test/java/io/imagekit/sdk/FolderOperationTest.java deleted file mode 100644 index 899fb0f..0000000 --- a/imagekit-sdk/src/test/java/io/imagekit/sdk/FolderOperationTest.java +++ /dev/null @@ -1,227 +0,0 @@ -package io.imagekit.sdk; - -import io.imagekit.sdk.exceptions.BadRequestException; -import io.imagekit.sdk.exceptions.ForbiddenException; -import io.imagekit.sdk.exceptions.InternalServerException; -import io.imagekit.sdk.exceptions.NotFoundException; -import io.imagekit.sdk.exceptions.TooManyRequestsException; -import io.imagekit.sdk.exceptions.UnauthorizedException; -import io.imagekit.sdk.exceptions.UnknownException; -import io.imagekit.sdk.models.CopyFolderRequest; -import io.imagekit.sdk.models.CreateFolderRequest; -import io.imagekit.sdk.models.DeleteFolderRequest; -import io.imagekit.sdk.models.MoveFolderRequest; -import io.imagekit.sdk.tasks.RestClient; -import io.imagekit.sdk.utils.Utils; -import okhttp3.mockwebserver.MockResponse; -import okhttp3.mockwebserver.MockWebServer; -import okhttp3.mockwebserver.RecordedRequest; -import org.junit.Before; -import org.junit.Test; - -import java.io.IOException; - -import static org.junit.Assert.assertEquals; - -public class FolderOperationTest { - private ImageKit SUT; - - @Before - public void setUp() throws Exception { - SUT = ImageKit.getInstance(); - SUT.setConfig(Utils.getSystemConfig(ImageKitTest.class)); - } - - @Test - public void createFolder_400_Expected() throws InterruptedException, IOException, UnknownException { - - CreateFolderRequest createFolderRequest = new CreateFolderRequest(); - createFolderRequest.setFolderName("/testFolder"); - createFolderRequest.setParentFolderPath("/"); - - MockWebServer server = new MockWebServer(); - server.enqueue(new MockResponse().setResponseCode(400)); - server.enqueue( - new MockResponse().setBody("{\n" + " \"message\": \"folderName parameter cannot have a slash.\",\n" - + " \"help\": \"For support kindly contact us at support@imagekit.io .\"\n" + "}")); - server.start(); - RestClient.API_BASE_URL = server.url("/").toString(); - SUT.createFolder(createFolderRequest); - server.takeRequest(); - } - - @Test - public void createFolder_successExpected() throws InterruptedException, IOException, UnknownException { - - CreateFolderRequest createFolderRequest = new CreateFolderRequest(); - createFolderRequest.setFolderName("testFolder"); - createFolderRequest.setParentFolderPath("/"); - - MockWebServer server = new MockWebServer(); - server.enqueue(new MockResponse().setBody("{}")); - server.start(); - RestClient.API_BASE_URL = server.url("/").toString(); - SUT.createFolder(createFolderRequest); - RecordedRequest request = server.takeRequest(); - - String createFolderRequestJson = "{\"folderName\":\"testFolder\",\"parentFolderPath\":\"/\"}"; - String utf8RequestBody = request.getBody().readUtf8(); - assertEquals(createFolderRequestJson, utf8RequestBody); - assertEquals("application/json; charset=utf-8", request.getHeader("Content-Type")); - assertEquals("POST /v1/folder/ HTTP/1.1", request.getRequestLine()); - assertEquals(RestClient.API_BASE_URL.concat("v1/folder/"), request.getRequestUrl().toString()); - } - - @Test(expected = NotFoundException.class) - public void deleteFolder_404_Expected() - throws InterruptedException, IOException, NotFoundException, BadRequestException, InternalServerException, - UnknownException, ForbiddenException, TooManyRequestsException, UnauthorizedException { - - DeleteFolderRequest deleteFolderRequest = new DeleteFolderRequest(); - deleteFolderRequest.setFolderPath("/testFolder"); - - MockWebServer server = new MockWebServer(); - server.enqueue(new MockResponse().setResponseCode(404) - .setBody("{\n" + " \"message\": \"No folder found with folderPath testFolder/\",\n" - + " \"help\": \"For support kindly contact us at support@imagekit.io .\",\n" - + " \"reason\": \"FOLDER_NOT_FOUND\"\n" + "}")); - server.start(); - RestClient.API_BASE_URL = server.url("/").toString(); - SUT.deleteFolder(deleteFolderRequest); - server.takeRequest(); - } - - @Test - public void deleteFolder_successExpected() - throws InterruptedException, IOException, NotFoundException, BadRequestException, InternalServerException, - UnknownException, ForbiddenException, TooManyRequestsException, UnauthorizedException { - - DeleteFolderRequest deleteFolderRequest = new DeleteFolderRequest(); - deleteFolderRequest.setFolderPath("testFolder"); - - MockWebServer server = new MockWebServer(); - server.enqueue(new MockResponse().setResponseCode(204).setBody("")); - server.start(); - RestClient.API_BASE_URL = server.url("/").toString(); - SUT.deleteFolder(deleteFolderRequest); - RecordedRequest request = server.takeRequest(); - - String deleteFolderRequestJson = "{\"folderPath\":\"testFolder\"}"; - String utf8RequestBody = request.getBody().readUtf8(); - assertEquals(deleteFolderRequestJson, utf8RequestBody); - assertEquals("application/json; charset=utf-8", request.getHeader("Content-Type")); - assertEquals("DELETE /v1/folder/ HTTP/1.1", request.getRequestLine()); - assertEquals(RestClient.API_BASE_URL.concat("v1/folder/"), request.getRequestUrl().toString()); - } - - @Test(expected = BadRequestException.class) - public void copyFolder_400_Expected() - throws InterruptedException, IOException, NotFoundException, BadRequestException, InternalServerException, - UnknownException, ForbiddenException, TooManyRequestsException, UnauthorizedException { - - CopyFolderRequest copyFolderRequest = new CopyFolderRequest(); - copyFolderRequest.setSourceFolderPath("/"); - copyFolderRequest.setDestinationPath("/test"); - copyFolderRequest.setIncludeFileVersions(false); - - MockWebServer server = new MockWebServer(); - server.enqueue(new MockResponse().setResponseCode(400) - .setBody("{\n" + " \"message\": \"sourceFolderPath cannot be root\",\n" - + " \"help\": \"For support kindly contact us at support@imagekit.io .\",\n" - + " \"reason\": \"SOURCE_IS_ROOT\"\n" + "}")); - server.start(); - RestClient.API_BASE_URL = server.url("/").toString(); - SUT.copyFolder(copyFolderRequest); - server.takeRequest(); - } - - @Test(expected = NotFoundException.class) - public void copyFolder_404_Expected() - throws InterruptedException, IOException, NotFoundException, BadRequestException, InternalServerException, - UnknownException, ForbiddenException, TooManyRequestsException, UnauthorizedException { - - CopyFolderRequest copyFolderRequest = new CopyFolderRequest(); - copyFolderRequest.setSourceFolderPath("/testFolder"); - copyFolderRequest.setDestinationPath("/test"); - copyFolderRequest.setIncludeFileVersions(true); - - MockWebServer server = new MockWebServer(); - server.enqueue(new MockResponse().setResponseCode(404) - .setBody("{\n" + " \"message\": \"No files & folder found at sourceFolderPath /testFolder\",\n" - + " \"help\": \"For support kindly contact us at support@imagekit.io .\",\n" - + " \"reason\": \"NO_FILES_FOLDER\"\n" + "}")); - server.start(); - RestClient.API_BASE_URL = server.url("/").toString(); - SUT.copyFolder(copyFolderRequest); - server.takeRequest(); - } - - @Test - public void copyFolder_successExpected() - throws InterruptedException, IOException, NotFoundException, BadRequestException, InternalServerException, - UnknownException, ForbiddenException, TooManyRequestsException, UnauthorizedException { - - CopyFolderRequest copyFolderRequest = new CopyFolderRequest(); - copyFolderRequest.setSourceFolderPath("/testFolder"); - copyFolderRequest.setDestinationPath("/Gallery"); - copyFolderRequest.setIncludeFileVersions(true); - - MockWebServer server = new MockWebServer(); - server.enqueue(new MockResponse().setBody("{\n" + " \"jobId\": \"629f43017eb0feff5c61f83c\"\n" + "}")); - server.start(); - RestClient.API_BASE_URL = server.url("/").toString(); - SUT.copyFolder(copyFolderRequest); - RecordedRequest request = server.takeRequest(); - - String copyFolderRequestJson = "{\"sourceFolderPath\":\"/testFolder\",\"destinationPath\":\"/Gallery\",\"includeFileVersions\":true}"; - String utf8RequestBody = request.getBody().readUtf8(); - assertEquals(copyFolderRequestJson, utf8RequestBody); - assertEquals("application/json; charset=utf-8", request.getHeader("Content-Type")); - assertEquals("POST /v1/bulkJobs/moveFolder HTTP/1.1", request.getRequestLine()); - assertEquals(RestClient.API_BASE_URL.concat("v1/bulkJobs/moveFolder"), request.getRequestUrl().toString()); - } - - @Test(expected = NotFoundException.class) - public void moveFolder_404_Expected() - throws InterruptedException, IOException, NotFoundException, BadRequestException, InternalServerException, - UnknownException, ForbiddenException, TooManyRequestsException, UnauthorizedException { - - MoveFolderRequest moveFolderRequest = new MoveFolderRequest(); - moveFolderRequest.setSourceFolderPath("/testFolder/"); - moveFolderRequest.setDestinationPath("/Gallery"); - - MockWebServer server = new MockWebServer(); - server.enqueue(new MockResponse().setResponseCode(404) - .setBody("{\n" + " \"message\": \"No files & folder found at sourceFolderPath /testFolder\",\n" - + " \"help\": \"For support kindly contact us at support@imagekit.io .\",\n" - + " \"reason\": \"NO_FILES_FOLDER\"\n" + "}")); - server.start(); - RestClient.API_BASE_URL = server.url("/").toString(); - SUT.moveFolder(moveFolderRequest); - server.takeRequest(); - } - - @Test - public void moveFolder_successExpected() - throws InterruptedException, IOException, NotFoundException, BadRequestException, InternalServerException, - UnknownException, ForbiddenException, TooManyRequestsException, UnauthorizedException { - - MoveFolderRequest moveFolderRequest = new MoveFolderRequest(); - moveFolderRequest.setSourceFolderPath("/testFolder"); - moveFolderRequest.setDestinationPath("/Gallery"); - - MockWebServer server = new MockWebServer(); - server.enqueue(new MockResponse().setBody("{\n" + " \"jobId\": \"629f44ac7eb0fe8173622d4b\"\n" + "}")); - server.start(); - RestClient.API_BASE_URL = server.url("/").toString(); - SUT.moveFolder(moveFolderRequest); - RecordedRequest request = server.takeRequest(); - - String moveFolderRequestJson = "{\"sourceFolderPath\":\"/testFolder\",\"destinationPath\":\"/Gallery\"}"; - String utf8RequestBody = request.getBody().readUtf8(); - assertEquals(moveFolderRequestJson, utf8RequestBody); - assertEquals("application/json; charset=utf-8", request.getHeader("Content-Type")); - assertEquals("POST /v1/bulkJobs/moveFolder HTTP/1.1", request.getRequestLine()); - assertEquals(RestClient.API_BASE_URL.concat("v1/bulkJobs/moveFolder"), request.getRequestUrl().toString()); - } -} diff --git a/imagekit-sdk/src/test/java/io/imagekit/sdk/GetUrlTest.java b/imagekit-sdk/src/test/java/io/imagekit/sdk/GetUrlTest.java deleted file mode 100644 index 8a79b12..0000000 --- a/imagekit-sdk/src/test/java/io/imagekit/sdk/GetUrlTest.java +++ /dev/null @@ -1,491 +0,0 @@ -package io.imagekit.sdk; - -import io.imagekit.sdk.utils.Utils; -import org.hamcrest.MatcherAssert; -import org.junit.Before; -import org.junit.Test; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.regex.Pattern; - -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; - -public class GetUrlTest { - private static final Pattern IMAGEKIT_SIGNED_URL_PATTERN = Pattern.compile("(https://.*)\\?ik-t=(.*)&ik-s=(.*)"); - private ImageKit SUT; - - @Before - public void setUp() throws Exception { - SUT = ImageKit.getInstance(); - SUT.setConfig(Utils.getSystemConfig(ImageKitTest.class)); - } - - private void assertSignedUrl(String expectedBaseUrl, String actualUrl) { - java.util.regex.Matcher matcher = IMAGEKIT_SIGNED_URL_PATTERN.matcher(actualUrl); - assertTrue(actualUrl + " does not look like a signed url", matcher.matches()); - assertEquals(expectedBaseUrl, matcher.group(1)); - assertFalse(matcher.group(2).trim().isEmpty()); - assertFalse(matcher.group(3).trim().isEmpty()); - } - - @Test - public void getUrl_with_height_width_options() { - List> transformation = new ArrayList<>(); - Map scale = new HashMap<>(); - scale.put("height", "600"); - scale.put("width", "400"); - transformation.add(scale); - - Map options = new HashMap<>(); - options.put("path", "/default-image.jpg"); - options.put("transformation", transformation); - String url = SUT.getUrl(options); - - assertThat(SUT.getConfig().getUrlEndpoint() + "/tr:w-400,h-600/default-image.jpg", is(url)); - } - - @Test - public void getUrl_with_height_width_options_url_version_check() { - List> transformation = new ArrayList<>(); - Map scale = new HashMap<>(); - scale.put("height", "600"); - scale.put("width", "400"); - transformation.add(scale); - Map options = new HashMap<>(); - options.put("path", "/default-image.jpg"); - options.put("transformation", transformation); - String url = SUT.getUrl(options); - assertThat(SUT.getConfig().getUrlEndpoint() + "/tr:w-400,h-600/default-image.jpg", is(url)); - } - - @Test - public void getUrl_with_new_transformation_params_options() throws IOException { - SUT = ImageKit.getInstance(); - SUT.setConfig(Utils.getSystemConfig(ImageKitTest.class)); - List> transformation = new ArrayList<>(); - Map scale = new HashMap<>(); - scale.put("height", "600"); - scale.put("width", "400"); - transformation.add(scale); - Map newParams = new HashMap<>(); - newParams.put("myparam", "40"); - transformation.add(newParams); - - Map options = new HashMap<>(); - options.put("path", "/default-image.jpg"); - options.put("transformation", transformation); - String url = SUT.getUrl(options); - assertThat(SUT.getConfig().getUrlEndpoint() + "/tr:w-400,h-600:myparam-40/default-image.jpg", is(url)); - } - - @Test - public void getUrl_with_slash_in_path() { - List> transformation = new ArrayList<>(); - Map scale = new HashMap<>(); - scale.put("height", "600"); - scale.put("width", "400"); - transformation.add(scale); - - Map options = new HashMap<>(); - options.put("path", "/default-image.jpg"); - options.put("transformation", transformation); - String url = SUT.getUrl(options); - assertThat(SUT.getConfig().getUrlEndpoint() + "/tr:w-400,h-600/default-image.jpg", is(url)); - } - - @Test - public void getUrl_without_slash_in_path() { - List> transformation = new ArrayList<>(); - Map scale = new HashMap<>(); - scale.put("height", "600"); - scale.put("width", "400"); - transformation.add(scale); - Map options = new HashMap<>(); - options.put("path", "default-image.jpg"); - options.put("transformation", transformation); - String url = SUT.getUrl(options); - assertThat(SUT.getConfig().getUrlEndpoint() + "/tr:w-400,h-600/default-image.jpg", is(url)); - } - - @Test - public void getUrl_with_overriding_urlEndpoint() { - List> transformation = new ArrayList<>(); - Map scale = new HashMap<>(); - scale.put("height", "600"); - scale.put("width", "400"); - transformation.add(scale); - - Map options = new HashMap<>(); - options.put("path", "/default-image.jpg"); - options.put("urlEndpoint", "https://ik.imagekit.io/your_imagekit_id/different-url-endpoint-prefix"); - options.put("transformation", transformation); - - String url = SUT.getUrl(options); - assertThat( - "https://ik.imagekit.io/your_imagekit_id/different-url-endpoint-prefix/tr:w-400,h-600/default-image.jpg", - is(url)); - } - - @Test - public void getUrl_with_transformation_parameters() { - List> transformation = new ArrayList>(); - Map scale = new HashMap<>(); - scale.put("height", "600"); - scale.put("width", "400"); - scale.put("aspectRatio", "4-3"); - scale.put("quality", "40"); - scale.put("crop", "force"); - scale.put("cropMode", "extract"); - scale.put("focus", "left"); - scale.put("format", "png"); - scale.put("radius", "20"); - scale.put("background", "A94D34"); - scale.put("border", "5-A94D34"); - scale.put("rotation", "90"); - scale.put("blur", "10"); - scale.put("named", "any_name"); - scale.put("overlayImage", "/folder/file.jpg"); - scale.put("overlayX", "20"); - scale.put("overlayY", "10"); - scale.put("overlayFocus", "top"); - scale.put("overlayHeight", "20"); - scale.put("overlayWidth", "20"); - scale.put("overlayText", "Image Text"); - scale.put("overlayTextFontSize", "18"); - scale.put("overlayTextFontFamily", "Open Sans"); - scale.put("overlayTextColor", "00FFFF"); - scale.put("overlayAlpha", ""); - scale.put("overlayTextTypography", "b"); - scale.put("overlayBackground", "00AAFF55"); - scale.put("overlayImageTrim", String.valueOf(false)); - scale.put("progressive", String.valueOf(true)); - scale.put("lossless", String.valueOf(true)); - scale.put("trim", "5"); - scale.put("metadata", String.valueOf(true)); - scale.put("colorProfile", String.valueOf(true)); - scale.put("defaultImage", "/folder/file.jpg"); - scale.put("dpr", "3"); - scale.put("effectSharpen", "-"); - scale.put("effectUSM", ""); - scale.put("effectContrast", "1"); - scale.put("effectGray", ""); - scale.put("original", String.valueOf(true)); - scale.put("raw", "w-200,h-200"); - scale.put("overlayImage", "oi"); - scale.put("overlayImageTrim", "oit"); - scale.put("overlayImageAspectRatio", "oiar"); - scale.put("overlayImageBackground", "oibg"); - scale.put("overlayImageBorder", "oib"); - scale.put("overlayImageDPR", "oidpr"); - scale.put("overlayImageQuality", "oiq"); - scale.put("overlayImageCropping", "oic"); - scale.put("overlayImageFocus", "oifo"); - - transformation.add(scale); - - Map options = new HashMap<>(); - options.put("path", "/default-image.jpg"); - options.put("urlEndpoint", "https://ik.imagekit.io/your_imagekit_id/"); - options.put("transformation", transformation); - - String url = SUT.getUrl(options); - assertThat( - "https://ik.imagekit.io/your_imagekit_id/tr:cm-extract,ofo-top,n-any_name,md-true,ow-20,e-contrast-1,oiar-oiar,fo-left,bl-10,ar-4-3,oit-oit,e-usm-,oidpr-oidpr,oa-,obg-00AAFF55,ots-18,t-5,oh-20,oic-oic,cp-true,r-20,ox-20,ot-Image%20Text,oy-10,otc-00FFFF,di-folder@@file.jpg,h-600,b-5-A94D34,orig-true,rt-90,dpr-3,f-png,raw-w-200,h-200,lo-true,e-grayscale-,oibg-oibg,q-40,ott-b,oib-oib,oiq-oiq,bg-A94D34,w-400,pr-true,e-sharpen,oi-oi,oifo-oifo,c-force,otf-Open%20Sans/default-image.jpg", - is(url)); - } - - @Test - public void getUrl_with_overriding_urlEndpoint_double_slash_tests() { - List> transformation = new ArrayList>(); - Map scale = new HashMap<>(); - scale.put("height", "600"); - scale.put("width", "400"); - transformation.add(scale); - - Map options = new HashMap<>(); - options.put("path", "/default-image.jpg"); - options.put("urlEndpoint", "https://ik.imagekit.io/your_imagekit_id/"); - options.put("transformation", transformation); - - String url = SUT.getUrl(options); - assertThat("https://ik.imagekit.io/your_imagekit_id/tr:w-400,h-600/default-image.jpg", is(url)); - } - - @Test - public void getUrl_with_options_as_query() { - Map queryParams = new HashMap<>(); - queryParams.put("v", "123"); - - List> transformation = new ArrayList<>(); - Map scale = new HashMap<>(); - scale.put("height", "600"); - scale.put("width", "400"); - transformation.add(scale); - - Map options = new HashMap<>(); - options.put("path", "/default-image.jpg"); - options.put("queryParameters", queryParams); - options.put("transformation", transformation); - options.put("transformationPosition", "query"); - - String url = SUT.getUrl(options); - MatcherAssert.assertThat(SUT.getConfig().getUrlEndpoint() + "/default-image.jpg?v=123&tr=w-400,h-600", is(url)); - } - - @Test() - public void getUrl_with_options_as_path() { - Map queryParams = new HashMap<>(); - queryParams.put("v", "123"); - - List> transformation = new ArrayList<>(); - Map scale = new HashMap<>(); - scale.put("height", "600"); - scale.put("width", "400"); - transformation.add(scale); - - Map options = new HashMap<>(); - options.put("path", "/default-image.jpg"); - options.put("queryParameters", queryParams); - options.put("transformation", transformation); - - String url = SUT.getUrl(options); - assertThat(SUT.getConfig().getUrlEndpoint() + "/tr:w-400,h-600/default-image.jpg?v=123", is(url)); - } - - @Test - public void getUrl_with_chained_transformation_options_as_query() { - Map queryParams = new HashMap<>(); - queryParams.put("v", "123"); - - List> transformation = new ArrayList<>(); - Map scale = new HashMap<>(); - scale.put("height", "600"); - scale.put("width", "400"); - transformation.add(scale); - Map rotate = new HashMap<>(); - rotate.put("rotation", "90"); - transformation.add(rotate); - - Map options = new HashMap<>(); - options.put("path", "/default-image.jpg"); - options.put("queryParameters", queryParams); - options.put("transformation", transformation); - options.put("transformationPosition", "query"); - - String url = SUT.getUrl(options); - assertThat(SUT.getConfig().getUrlEndpoint() + "/default-image.jpg?v=123&tr=w-400,h-600:rt-90", is(url)); - } - - @Test - public void getUrl_with_chained_transformation_options_as_path() { - Map queryParams = new HashMap<>(); - queryParams.put("v", "123"); - - List> transformation = new ArrayList<>(); - Map scale = new HashMap<>(); - scale.put("height", "600"); - scale.put("width", "400"); - transformation.add(scale); - Map rotate = new HashMap<>(); - rotate.put("rotation", "90"); - transformation.add(rotate); - - Map options = new HashMap<>(); - options.put("path", "/default-image.jpg"); - options.put("queryParameters", queryParams); - options.put("transformation", transformation); - - String url = SUT.getUrl(options); - assertThat(SUT.getConfig().getUrlEndpoint() + "/tr:w-400,h-600:rt-90/default-image.jpg?v=123", is(url)); - } - - @Test - public void getUrl_with_multiple_query_params_addition_check() { - Map queryParams = new HashMap<>(); - queryParams.put("v", "123"); - queryParams.put("z", "234"); - - List> transformation = new ArrayList<>(); - Map scale = new HashMap<>(); - scale.put("height", "600"); - scale.put("width", "400"); - transformation.add(scale); - - Map options = new HashMap<>(); - options.put("src", "https://ik.imagekit.io/your_imagekit_id/endpoint/default-image.jpg?q=abc"); - options.put("queryParameters", queryParams); - options.put("transformation", transformation); - - String url = SUT.getUrl(options); - assertThat( - "https://ik.imagekit.io/your_imagekit_id/endpoint/default-image.jpg?q=abc&v=123&z=234&tr=w-400,h-600", - is(url)); - } - - @Test - public void getUrl_with_double_and_check() { - Map queryParams = new HashMap<>(); - queryParams.put("v", "123"); - queryParams.put("z", "234"); - - List> transformation = new ArrayList<>(); - Map scale = new HashMap<>(); - scale.put("height", "600"); - scale.put("width", "400"); - transformation.add(scale); - - Map options = new HashMap<>(); - options.put("src", "https://ik.imagekit.io/your_imagekit_id/endpoint/default-image.jpg?q=abc&&"); - options.put("queryParameters", queryParams); - options.put("transformation", transformation); - - String url = SUT.getUrl(options); - assertThat( - "https://ik.imagekit.io/your_imagekit_id/endpoint/default-image.jpg?q=abc&v=123&z=234&tr=w-400,h-600", - is(url)); - } - - @Test - public void getUrl_with_double_question_mark_check() { - Map queryParams = new HashMap<>(); - queryParams.put("v", "123"); - queryParams.put("z", "234"); - - List> transformation = new ArrayList<>(); - Map scale = new HashMap<>(); - scale.put("height", "600"); - scale.put("width", "400"); - transformation.add(scale); - - Map options = new HashMap<>(); - options.put("src", "https://ik.imagekit.io/your_imagekit_id/endpoint/default-image.jpg??"); - options.put("queryParameters", queryParams); - options.put("transformation", transformation); - - String url = SUT.getUrl(options); - assertThat("https://ik.imagekit.io/your_imagekit_id/endpoint/default-image.jpg?v=123&z=234&tr=w-400,h-600", - is(url)); - } - - @Test - public void getUrl_with_src() { - List> transformation = new ArrayList<>(); - Map scale = new HashMap<>(); - scale.put("height", "600"); - scale.put("width", "400"); - transformation.add(scale); - - Map options = new HashMap<>(); - options.put("src", "https://ik.imagekit.io/your_imagekit_id/endpoint/default-image.jpg"); - options.put("transformation", transformation); - - String url = SUT.getUrl(options); - assertThat("https://ik.imagekit.io/your_imagekit_id/endpoint/default-image.jpg?tr=w-400,h-600", is(url)); - } - - @Test - public void getUrl_src_with_query_params() { - Map queryParams = new HashMap<>(); - queryParams.put("v", "123"); - queryParams.put("z", "234"); - - List> transformation = new ArrayList<>(); - Map scale = new HashMap<>(); - scale.put("height", "600"); - scale.put("width", "400"); - transformation.add(scale); - - Map options = new HashMap<>(); - options.put("src", "https://ik.imagekit.io/your_imagekit_id/endpoint/default-image.jpg?srcParam=srcParamValue"); - options.put("queryParameters", queryParams); - options.put("transformation", transformation); - - String url = SUT.getUrl(options); - assertThat( - "https://ik.imagekit.io/your_imagekit_id/endpoint/default-image.jpg?srcParam=srcParamValue&v=123&z=234&tr=w-400,h-600", - is(url)); - } - - @Test - public void getUrl_src_with_query_params_but_transformationPosition_is_path() { - Map queryParam = new HashMap<>(); - queryParam.put("v", "123"); - queryParam.put("z", "234"); - - List> transformation = new ArrayList>(); - Map scale = new HashMap<>(); - scale.put("height", "600"); - scale.put("width", "400"); - transformation.add(scale); - - Map options = new HashMap<>(); - options.put("src", "https://ik.imagekit.io/your_imagekit_id/endpoint/default-image.jpg"); - options.put("queryParameters", queryParam); - options.put("transformation", transformation); - options.put("transformationPosition", "path"); - - String url = SUT.getUrl(options); - assertThat("https://ik.imagekit.io/your_imagekit_id/endpoint/default-image.jpg?v=123&z=234&tr=w-400,h-600", - is(url)); - } - - @Test - public void getUrl_with_signature() { - List> transformation = new ArrayList>(); - Map scale = new HashMap<>(); - scale.put("width", "100"); - transformation.add(scale); - - Map options = new HashMap<>(); - options.put("path", "/test-signed-url.png"); - options.put("transformation", transformation); - options.put("signed", true); - options.put("expireSeconds", 1000); - - String url = SUT.getUrl(options); - - assertSignedUrl("https://ik.imagekit.io/imagekit_id/tr:w-100/test-signed-url.png", url); - } - - @Test - public void getUrl_with_signature_src_noTransform() { - Map options = new HashMap<>(); - options.put("src", "https://ik.imagekit.io/your_imagekit_id/endpoint/default-image.jpg"); - options.put("signed", true); - options.put("expireSeconds", 1000); - - String url = SUT.getUrl(options); - - assertSignedUrl("https://ik.imagekit.io/your_imagekit_id/endpoint/default-image.jpg", url); - } - - @Test - public void getUrl_with_time_expire() { - List> transformation = new ArrayList>(); - Map scale = new HashMap<>(); - scale.put("height", "600"); - scale.put("width", "400"); - transformation.add(scale); - Map rotate = new HashMap<>(); - rotate.put("rotation", "90"); - transformation.add(rotate); - - Map options = new HashMap<>(); - options.put("path", "/default-image.jpg"); - options.put("transformation", transformation); - options.put("expireSeconds", 100); - options.put("signed", true); - - String url = SUT.getUrl(options); - assertTrue(url.contains("ik-t")); - } -} diff --git a/imagekit-sdk/src/test/java/io/imagekit/sdk/ImageKitTest.java b/imagekit-sdk/src/test/java/io/imagekit/sdk/ImageKitTest.java deleted file mode 100644 index ba2123e..0000000 --- a/imagekit-sdk/src/test/java/io/imagekit/sdk/ImageKitTest.java +++ /dev/null @@ -1,82 +0,0 @@ -package io.imagekit.sdk; - -import io.imagekit.sdk.config.Configuration; -import io.imagekit.sdk.utils.Utils; -import org.junit.Before; -import org.junit.Test; - -import java.util.Map; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -public class ImageKitTest { - private ImageKit SUT; - - @Before - public void setUp() throws Exception { - SUT = ImageKit.getInstance(); - SUT.setConfig(Utils.getSystemConfig(ImageKitTest.class)); - } - - @Test - public void imageKit_configurationTest() { - Configuration config = new Configuration(); - config.setPrivateKey("private_Key"); - config.setPublicKey("public_key"); - config.setUrlEndpoint("url_end_point"); - ImageKit.getInstance().setConfig(config); - assertEquals(config.toString(), ImageKit.getInstance().getConfig().toString()); - } - - @Test - public void withoutToken_getAuthenticationParameters_successExpected() { - Map auth = SUT.getAuthenticationParameters(); - assertNotNull(auth); - } - - @Test(expected = RuntimeException.class) - public void withoutPrivateKey_getAuthenticationParameters_successExpected() { - SUT.getConfig().setPrivateKey(null); - Map auth = SUT.getAuthenticationParameters(); - assertNotNull(auth); - } - - @Test - public void withTokenAndExpire_getAuthenticationParameters_successExpected() { - Map auth = SUT.getAuthenticationParameters("your_token", 1582269249); - assertNotNull(auth); - assertEquals("your_token", auth.get("token")); - assertEquals("1582269249", auth.get("expire")); - assertEquals("e71bcd6031016b060d349d212e23e85c791decdd", auth.get("signature")); - } - - @Test - public void sameImage_getHammingDistance_expectedSuccessWith() { - int hammingDistance = SUT.pHashDistance("f06830ca9f1e3e90", "f06830ca9f1e3e90"); - assertEquals(0, hammingDistance); - } - - @Test - public void similarImage_getHammingDistance_expectedSuccessWith() { - int hammingDistance = SUT.pHashDistance("33699c96619cc69e", "968e978414fe04ea"); - assertEquals(30, hammingDistance); - } - - @Test - public void dissimilarImage_getHammingDistance_expectedSuccessWith() { - int hammingDistance = SUT.pHashDistance("a4a65595ac94518b", "7838873e791f8400"); - assertEquals(37, hammingDistance); - } - - @Test(expected = RuntimeException.class) - public void invalidHash_getHammingDistance_throwException() { - int hammingDistance = SUT.pHashDistance("a4a65595ac94518Z", "7838873e791f8400"); - } - - @Test(expected = RuntimeException.class) - public void differentLength_getHammingDistance_throwException() { - int hammingDistance = SUT.pHashDistance("a4a65595ac94518b3", "7838873e791f8400"); - } - -} \ No newline at end of file diff --git a/imagekit-sdk/src/test/java/io/imagekit/sdk/PurgeCacheTest.java b/imagekit-sdk/src/test/java/io/imagekit/sdk/PurgeCacheTest.java deleted file mode 100644 index cbb68f9..0000000 --- a/imagekit-sdk/src/test/java/io/imagekit/sdk/PurgeCacheTest.java +++ /dev/null @@ -1,98 +0,0 @@ -package io.imagekit.sdk; - -import io.imagekit.sdk.exceptions.BadRequestException; -import io.imagekit.sdk.exceptions.ForbiddenException; -import io.imagekit.sdk.exceptions.InternalServerException; -import io.imagekit.sdk.exceptions.TooManyRequestsException; -import io.imagekit.sdk.exceptions.UnauthorizedException; -import io.imagekit.sdk.exceptions.UnknownException; -import io.imagekit.sdk.tasks.RestClient; -import io.imagekit.sdk.utils.Utils; -import okhttp3.mockwebserver.MockResponse; -import okhttp3.mockwebserver.MockWebServer; -import okhttp3.mockwebserver.RecordedRequest; -import org.junit.Before; -import org.junit.Test; - -import java.io.IOException; - -import static org.junit.Assert.assertEquals; - -public class PurgeCacheTest { - - private ImageKit SUT; - - @Before - public void setUp() throws Exception { - SUT = ImageKit.getInstance(); - SUT.setConfig(Utils.getSystemConfig(ImageKitTest.class)); - } - - @Test(expected = BadRequestException.class) - public void imageKit_purgeCache_404Expected() - throws ForbiddenException, TooManyRequestsException, InternalServerException, UnauthorizedException, - BadRequestException, UnknownException, InterruptedException, IOException { - MockWebServer server = new MockWebServer(); - String responseJson = "{\n" + " \"message\": \"Invalid url\"\n" + "}"; - server.enqueue(new MockResponse().setResponseCode(400).setBody(responseJson)); - server.start(); - RestClient.API_BASE_URL = server.url("/").toString(); - SUT.purgeCache("url"); - - server.takeRequest(); - } - - @Test - public void imageKit_purgeCache_successExpected() - throws IOException, ForbiddenException, TooManyRequestsException, InternalServerException, - UnauthorizedException, BadRequestException, UnknownException, InterruptedException { - MockWebServer server = new MockWebServer(); - String responseJson = "{\n" + " \"requestId\": \"62b01f15214dfbdf3692dd0a\"\n" + "}"; - server.enqueue(new MockResponse().setBody(responseJson)); - server.start(); - RestClient.API_BASE_URL = server.url("/").toString(); - SUT.purgeCache("https://ik.imagekit.io/zv3rkhsym/sample-image11_g1Qv0wpqP.jpg"); - - RecordedRequest request = server.takeRequest(); - String utf8RequestBody = request.getBody().readUtf8(); - assertEquals("{\"url\":\"https://ik.imagekit.io/zv3rkhsym/sample-image11_g1Qv0wpqP.jpg\"}", utf8RequestBody); - assertEquals("application/json; charset=utf-8", request.getHeader("Content-Type")); - assertEquals("POST /v1/files/purge HTTP/1.1", request.getRequestLine()); - assertEquals(RestClient.API_BASE_URL.concat("v1/files/purge"), request.getRequestUrl().toString()); - } - - @Test(expected = BadRequestException.class) - public void imageKit_getPurgeCacheStatus_400Expected() - throws ForbiddenException, TooManyRequestsException, InternalServerException, UnauthorizedException, - BadRequestException, UnknownException, InterruptedException, IOException { - MockWebServer server = new MockWebServer(); - String responseJson = "{\n" + " \"message\": \"No request found for this requestId.\",\n" - + " \"help\": \"For support kindly contact us at support@imagekit.io .\"\n" + "}"; - server.enqueue(new MockResponse().setResponseCode(400).setBody(responseJson)); - server.start(); - RestClient.API_BASE_URL = server.url("/").toString(); - SUT.getPurgeCacheStatus("62b01f15214dfbdf3692dd0b"); - - server.takeRequest(); - } - - @Test - public void imageKit_getPurgeCacheStatus_successExpected() - throws ForbiddenException, TooManyRequestsException, InternalServerException, UnauthorizedException, - BadRequestException, UnknownException, InterruptedException, IOException { - MockWebServer server = new MockWebServer(); - String responseJson = "{\n" + " \"status\": \"Completed\"\n" + "}"; - server.enqueue(new MockResponse().setBody(responseJson)); - server.start(); - RestClient.API_BASE_URL = server.url("/").toString(); - SUT.getPurgeCacheStatus("62b01f15214dfbdf3692dd0a"); - - RecordedRequest request = server.takeRequest(); - String utf8RequestBody = request.getBody().readUtf8(); - assertEquals("", utf8RequestBody); - assertEquals("application/json", request.getHeader("Content-Type")); - assertEquals("GET /v1/files/purge/62b01f15214dfbdf3692dd0a HTTP/1.1", request.getRequestLine()); - assertEquals(RestClient.API_BASE_URL.concat("v1/files/purge/62b01f15214dfbdf3692dd0a"), - request.getRequestUrl().toString()); - } -} diff --git a/imagekit-sdk/src/test/java/io/imagekit/sdk/UploadTest.java b/imagekit-sdk/src/test/java/io/imagekit/sdk/UploadTest.java deleted file mode 100644 index ad07580..0000000 --- a/imagekit-sdk/src/test/java/io/imagekit/sdk/UploadTest.java +++ /dev/null @@ -1,251 +0,0 @@ -package io.imagekit.sdk; - -import com.google.gson.JsonArray; -import com.google.gson.JsonObject; -import io.imagekit.sdk.exceptions.BadRequestException; -import io.imagekit.sdk.exceptions.ForbiddenException; -import io.imagekit.sdk.exceptions.InternalServerException; -import io.imagekit.sdk.exceptions.TooManyRequestsException; -import io.imagekit.sdk.exceptions.UnauthorizedException; -import io.imagekit.sdk.exceptions.UnknownException; -import io.imagekit.sdk.models.FileCreateRequest; -import io.imagekit.sdk.tasks.RestClient; -import io.imagekit.sdk.utils.Utils; -import okhttp3.mockwebserver.MockResponse; -import okhttp3.mockwebserver.MockWebServer; -import okhttp3.mockwebserver.RecordedRequest; -import org.junit.Before; -import org.junit.Test; - -import java.io.IOException; -import java.net.HttpURLConnection; -import java.net.URL; -import java.net.UnknownHostException; -import java.util.ArrayList; -import java.util.List; - -import static org.junit.Assert.assertEquals; - -public class UploadTest { - private ImageKit SUT; - - @Before - public void setUp() throws Exception { - SUT = ImageKit.getInstance(); - SUT.setConfig(Utils.getSystemConfig(ImageKitTest.class)); - } - - @Test(expected = UnknownHostException.class) - public void imageKit_upload_expect_UnknownHostException() throws IOException { - String imageUrl = "https://homepagesabc.cae.wisc.edu/~ece533/images/12.png"; - URL url = new URL(imageUrl); - HttpURLConnection urlConnect = (HttpURLConnection) url.openConnection(); - urlConnect.getContent(); - } - - @Test(expected = RuntimeException.class) - public void imageKit_upload_expected_RuntimeException_for_file() - throws IOException, InterruptedException, InternalServerException, BadRequestException, UnknownException, - ForbiddenException, TooManyRequestsException, UnauthorizedException { - FileCreateRequest fileCreateRequest = new FileCreateRequest((String) null, "sample-cat-image.png"); - - MockWebServer server = new MockWebServer(); - server.enqueue(new MockResponse().setBody("java.lang.RuntimeException: Error: File not provided.")); - server.start(); - RestClient.UPLOAD_BASE_URL = server.url("/").toString(); - SUT.upload(fileCreateRequest); - RecordedRequest request = server.takeRequest(); - } - - @Test - public void imageKit_upload_returnSuccess() throws IOException, InterruptedException, InternalServerException, - BadRequestException, UnknownException, ForbiddenException, TooManyRequestsException, UnauthorizedException { - String imageUrl = "https://homepages.cae.wisc.edu/~ece533/images/cat.png"; - URL url = new URL(imageUrl); - FileCreateRequest fileCreateRequest = new FileCreateRequest(url, "sample-cat-image.png"); - List tags = new ArrayList<>(); - tags.add("Software"); - tags.add("Developer"); - tags.add("Engineer"); - fileCreateRequest.setTags(tags); - fileCreateRequest.setFolder("demo1"); - String customCoordinates = "10,10,20,20"; - fileCreateRequest.setCustomCoordinates(customCoordinates); - - List responseFields = new ArrayList<>(); - responseFields.add("thumbnail"); - responseFields.add("tags"); - responseFields.add("customCoordinates"); - - fileCreateRequest.setResponseFields(responseFields); - JsonObject optionsInnerObject = new JsonObject(); - optionsInnerObject.addProperty("add_shadow", true); - JsonObject innerObject1 = new JsonObject(); - innerObject1.addProperty("name", "remove-bg"); - innerObject1.add("options", optionsInnerObject); - JsonObject innerObject2 = new JsonObject(); - innerObject2.addProperty("name", "google-auto-tagging"); - innerObject2.addProperty("minConfidence", 10); - innerObject2.addProperty("maxTags", 5); - JsonArray jsonArray = new JsonArray(); - jsonArray.add(innerObject1); - jsonArray.add(innerObject2); - fileCreateRequest.setExtensions(jsonArray); - fileCreateRequest.setWebhookUrl("https://webhook.site/c78d617f-33bc-40d9-9e61-608999721e2e"); - fileCreateRequest.setOverwriteFile(true); - fileCreateRequest.setUseUniqueFileName(false); - fileCreateRequest.setPrivateFile(false); - fileCreateRequest.setOverwriteAITags(false); - fileCreateRequest.setOverwriteTags(false); - fileCreateRequest.setOverwriteCustomMetadata(true); - JsonObject jsonObjectCustomMetadata = new JsonObject(); - jsonObjectCustomMetadata.addProperty("test1", 10); - fileCreateRequest.setCustomMetadata(jsonObjectCustomMetadata); - - MockWebServer server = new MockWebServer(); - server.enqueue(new MockResponse().setBody("{\r\n" + " \"fileId\": \"62a465d245a84a0ef3852968\",\r\n" - + " \"name\": \"sample-cat-image_GG0_X8GOn.jpg\",\r\n" + " \"size\": 23023,\r\n" - + " \"versionInfo\": {\r\n" + " \"id\": \"62a465d245a84a0ef3852968\",\r\n" - + " \"name\": \"Version 1\"\r\n" + " },\r\n" - + " \"filePath\": \"/demo1/sample-cat-image_GG0_X8GOn.jpg\",\r\n" - + " \"url\": \"https://ik.imagekit.io/zv3rkhsym/demo1/sample-cat-image_GG0_X8GOn.jpg\",\r\n" - + " \"fileType\": \"image\",\r\n" + " \"height\": 354,\r\n" + " \"width\": 236,\r\n" - + " \"thumbnailUrl\": \"https://ik.imagekit.io/zv3rkhsym/tr:n-ik_ml_thumbnail/demo1/sample-cat-image_GG0_X8GOn.jpg\",\r\n" - + " \"AITags\": [\r\n" + " {\r\n" + " \"name\": \"Clothing\",\r\n" - + " \"confidence\": 98.77,\r\n" + " \"source\": \"google-auto-tagging\"\r\n" - + " },\r\n" + " {\r\n" + " \"name\": \"Plant\",\r\n" - + " \"confidence\": 96.51,\r\n" + " \"source\": \"google-auto-tagging\"\r\n" - + " },\r\n" + " {\r\n" + " \"name\": \"Smile\",\r\n" - + " \"confidence\": 95.31,\r\n" + " \"source\": \"google-auto-tagging\"\r\n" - + " },\r\n" + " {\r\n" + " \"name\": \"Shoe\",\r\n" - + " \"confidence\": 95.2,\r\n" + " \"source\": \"google-auto-tagging\"\r\n" - + " },\r\n" + " {\r\n" + " \"name\": \"Street light\",\r\n" - + " \"confidence\": 91.05,\r\n" + " \"source\": \"google-auto-tagging\"\r\n" - + " }\r\n" + " ],\r\n" + " \"extensionStatus\": {\r\n" + " \"remove-bg\": \"pending\",\r\n" - + " \"google-auto-tagging\": \"success\"\r\n" + " }\r\n" + "}")); - server.start(); - RestClient.UPLOAD_BASE_URL = server.url("/").toString(); - SUT.upload(fileCreateRequest); - RecordedRequest request = server.takeRequest(); - String json = "--randomBoundary-------------------\r\n" + - "Content-Disposition: form-data; name=\"file\"\r\n" + - "Content-Length: 53\r\n" + - "\r\n" + - "https://homepages.cae.wisc.edu/~ece533/images/cat.png\r\n" + - "--randomBoundary-------------------\r\n" + - "Content-Disposition: form-data; name=\"fileName\"\r\n" + - "Content-Length: 20\r\n" + - "\r\n" + - "sample-cat-image.png\r\n" + - "--randomBoundary-------------------\r\n" + - "Content-Disposition: form-data; name=\"useUniqueFileName\"\r\n" + - "Content-Length: 5\r\n" + - "\r\n" + - "false\r\n" + - "--randomBoundary-------------------\r\n" + - "Content-Disposition: form-data; name=\"tags\"\r\n" + - "Content-Length: 27\r\n" + - "\r\n" + - "Software,Developer,Engineer\r\n" + - "--randomBoundary-------------------\r\n" + - "Content-Disposition: form-data; name=\"folder\"\r\n" + - "Content-Length: 5\r\n" + - "\r\n" + - "demo1\r\n" + - "--randomBoundary-------------------\r\n" + - "Content-Disposition: form-data; name=\"customCoordinates\"\r\n" + - "Content-Length: 11\r\n" + - "\r\n" + - "10,10,20,20\r\n" + - "--randomBoundary-------------------\r\n" + - "Content-Disposition: form-data; name=\"responseFields\"\r\n" + - "Content-Length: 32\r\n" + - "\r\n" + - "thumbnail,tags,customCoordinates\r\n" + - "--randomBoundary-------------------\r\n" + - "Content-Disposition: form-data; name=\"overwriteFile\"\r\n" + - "Content-Length: 4\r\n" + - "\r\n" + - "true\r\n" + - "--randomBoundary-------------------\r\n" + - "Content-Disposition: form-data; name=\"overwriteCustomMetadata\"\r\n" + - "Content-Length: 4\r\n" + - "\r\n" + - "true\r\n" + - "--randomBoundary-------------------\r\n" + - "Content-Disposition: form-data; name=\"extensions\"\r\n" + - "Content-Length: 114\r\n" + - "\r\n" + - "[{\"name\":\"remove-bg\",\"options\":{\"add_shadow\":true}},{\"name\":\"google-auto-tagging\",\"minConfidence\":10,\"maxTags\":5}]\r\n" + - "--randomBoundary-------------------\r\n" + - "Content-Disposition: form-data; name=\"webhookUrl\"\r\n" + - "Content-Length: 57\r\n" + - "\r\n" + - "https://webhook.site/c78d617f-33bc-40d9-9e61-608999721e2e\r\n" + - "--randomBoundary-------------------\r\n" + - "Content-Disposition: form-data; name=\"customMetadata\"\r\n" + - "Content-Length: 12\r\n" + - "\r\n" + - "{\"test1\":10}\r\n" + - "--randomBoundary---------------------"; - assertEquals(json, request.getBody().readUtf8().trim()); - assertEquals("POST /api/v1/files/upload HTTP/1.1", request.getRequestLine()); - assertEquals(RestClient.UPLOAD_BASE_URL.concat("api/v1/files/upload"), request.getRequestUrl().toString()); - } - - @Test(expected = BadRequestException.class) - public void imageKit_upload_400_expected() throws IOException, InterruptedException, InternalServerException, - BadRequestException, UnknownException, ForbiddenException, TooManyRequestsException, UnauthorizedException { - String imageUrl = "https://homepages.cae.wisc.edu/~ece533/images/cat.png"; - URL url = new URL(imageUrl); - FileCreateRequest fileCreateRequest = new FileCreateRequest(url, "sample-cat-image.png"); - List tags = new ArrayList<>(); - tags.add("Software"); - tags.add("Developer"); - tags.add("Engineer"); - fileCreateRequest.setTags(tags); - fileCreateRequest.setFolder("demo1"); - String customCoordinates = "10,10,20,20"; - fileCreateRequest.setCustomCoordinates(customCoordinates); - - List responseFields = new ArrayList<>(); - responseFields.add("thumbnail"); - responseFields.add("tags"); - responseFields.add("customCoordinates"); - - fileCreateRequest.setResponseFields(responseFields); - JsonObject optionsInnerObject = new JsonObject(); - optionsInnerObject.addProperty("add_shadow", true); - JsonObject innerObject1 = new JsonObject(); - innerObject1.addProperty("name", "remove-bg"); - innerObject1.add("options", optionsInnerObject); - JsonObject innerObject2 = new JsonObject(); - innerObject2.addProperty("name", "google-auto-tagging"); - innerObject2.addProperty("minConfidence", 10); - innerObject2.addProperty("maxTags", 5); - JsonArray jsonArray = new JsonArray(); - jsonArray.add(innerObject1); - jsonArray.add(innerObject2); - fileCreateRequest.setExtensions(jsonArray); - fileCreateRequest.setWebhookUrl("https://webhook.site/c78d617f-33bc-40d9-9e61-608999721e2e"); - fileCreateRequest.setUseUniqueFileName(false); - fileCreateRequest.setPrivateFile(false); - fileCreateRequest.setOverwriteFile(false); - fileCreateRequest.setOverwriteAITags(false); - fileCreateRequest.setOverwriteTags(false); - fileCreateRequest.setOverwriteCustomMetadata(true); - JsonObject jsonObjectCustomMetadata = new JsonObject(); - jsonObjectCustomMetadata.addProperty("test1", 10); - fileCreateRequest.setCustomMetadata(jsonObjectCustomMetadata); - - MockWebServer server = new MockWebServer(); - server.enqueue(new MockResponse().setResponseCode(400).setBody("{\r\n" - + " \"message\": \"A file with the same name already exists at the exact location. We could not overwrite it because both overwriteFile and useUniqueFileName are set to false.\"\r\n" - + "}")); - server.start(); - RestClient.UPLOAD_BASE_URL = server.url("/").toString(); - SUT.upload(fileCreateRequest); - server.takeRequest(); - } - -} \ No newline at end of file diff --git a/imagekit-sdk/src/test/java/io/imagekit/sdk/config/ConfigurationTest.java b/imagekit-sdk/src/test/java/io/imagekit/sdk/config/ConfigurationTest.java deleted file mode 100644 index cd94018..0000000 --- a/imagekit-sdk/src/test/java/io/imagekit/sdk/config/ConfigurationTest.java +++ /dev/null @@ -1,44 +0,0 @@ -package io.imagekit.sdk.config; - -import org.junit.Test; -import java.io.IOException; - -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.*; - -public class ConfigurationTest { - - Configuration SUT; - - @Test - public void configFileExit_validate_successExpected() throws IOException { - SUT=new Configuration(); - SUT.setPrivateKey("privateKey"); - SUT.setPublicKey("publicKey"); - SUT.setUrlEndpoint("endPoint"); - - boolean result=SUT.validate(); - assertTrue(result); - } - - @Test(expected = RuntimeException.class) - public void configNotExit_validate_errorExpected() throws IOException { - SUT=new Configuration(); - SUT.setPrivateKey("privateKey"); - SUT.setUrlEndpoint("endPoint"); - - boolean result=SUT.validate(); - assertTrue(result); - } - - @Test - public void config_getter_setter_successExpected() throws IOException { - String privateKey="privateKey"; - String publicKey="publicKey"; - String endPoint="endPoint"; - SUT=new Configuration(publicKey,privateKey,endPoint); - assertThat(privateKey,is(SUT.getPrivateKey())); - assertThat(publicKey,is(SUT.getPublicKey())); - assertThat(endPoint,is(SUT.getUrlEndpoint())); - } -} \ No newline at end of file diff --git a/imagekit-sdk/src/test/java/io/imagekit/sdk/manage/CustomMetaDataFieldTest.java b/imagekit-sdk/src/test/java/io/imagekit/sdk/manage/CustomMetaDataFieldTest.java deleted file mode 100644 index d62919c..0000000 --- a/imagekit-sdk/src/test/java/io/imagekit/sdk/manage/CustomMetaDataFieldTest.java +++ /dev/null @@ -1,477 +0,0 @@ -package io.imagekit.sdk.manage; - -import io.imagekit.sdk.ImageKit; -import io.imagekit.sdk.ImageKitTest; -import io.imagekit.sdk.exceptions.BadRequestException; -import io.imagekit.sdk.exceptions.NotFoundException; -import io.imagekit.sdk.exceptions.UnknownException; -import io.imagekit.sdk.models.CustomMetaDataFieldCreateRequest; -import io.imagekit.sdk.models.CustomMetaDataFieldSchemaObject; -import io.imagekit.sdk.models.CustomMetaDataFieldUpdateRequest; -import io.imagekit.sdk.models.CustomMetaDataTypeEnum; -import io.imagekit.sdk.models.results.ResultCustomMetaDataField; -import io.imagekit.sdk.tasks.RestClient; -import io.imagekit.sdk.utils.Utils; -import okhttp3.mockwebserver.MockResponse; -import okhttp3.mockwebserver.MockWebServer; -import okhttp3.mockwebserver.RecordedRequest; -import org.junit.Before; -import org.junit.Test; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import static org.junit.Assert.assertEquals; - -public class CustomMetaDataFieldTest { - - private ImageKit SUT; - - @Before - public void setUp() throws Exception { - SUT = ImageKit.getInstance(); - SUT.setConfig(Utils.getSystemConfig(ImageKitTest.class)); - } - - @Test - public void get_custom_metadata_fields_expectedSuccessWith() - throws IOException, InterruptedException, UnknownException { - - MockWebServer server = new MockWebServer(); - server.enqueue(new MockResponse().setBody("[\n" + " {\n" + " \"id\": \"6291f00890ba008cc27f64d1\",\n" - + " \"name\": \"price\",\n" + " \"label\": \"Amount\",\n" + " \"schema\": {\n" - + " \"minValue\": 10,\n" + " \"maxValue\": 200,\n" - + " \"type\": \"Number\"\n" + " }\n" + " },\n" + " {\n" - + " \"id\": \"6296f91191fa57ccc36b15cf\",\n" + " \"name\": \"Amount2\",\n" - + " \"label\": \"Amouunt\",\n" + " \"schema\": {\n" - + " \"type\": \"Number\",\n" + " \"minValue\": 10,\n" - + " \"maxValue\": 1000\n" + " }\n" + " }\n" + "]")); - server.start(); - RestClient.API_BASE_URL = server.url("/").toString(); - SUT.getCustomMetaDataFields(false); - RecordedRequest request = server.takeRequest(); - assertEquals("application/json", request.getHeader("Content-Type")); - assertEquals("GET /v1/customMetadataFields?includeDeleted=false HTTP/1.1", request.getRequestLine()); - assertEquals(RestClient.API_BASE_URL.concat("v1/customMetadataFields?includeDeleted=false"), - request.getRequestUrl().toString()); - } - - @Test(expected = BadRequestException.class) - public void createCustomMetaDataFields_expected_400() - throws InterruptedException, IOException, BadRequestException, UnknownException { - - MockWebServer server = new MockWebServer(); - String responseJson = "{\n" + " \"message\": \"Invalid schema object\",\n" - + " \"help\": \"For support kindly contact us at support@imagekit.io .\",\n" + " \"errors\": {\n" - + " \"minValue\": \"not allowed for this type\",\n" - + " \"maxValue\": \"not allowed for this type\"\n" + " }\n" + "}"; - server.enqueue(new MockResponse().setResponseCode(400).setBody(responseJson)); - server.start(); - RestClient.API_BASE_URL = server.url("/").toString(); - - CustomMetaDataFieldSchemaObject mockCustomMetaDataFieldSchemaObject = new CustomMetaDataFieldSchemaObject(); - mockCustomMetaDataFieldSchemaObject.setType(CustomMetaDataTypeEnum.Text); - mockCustomMetaDataFieldSchemaObject.setMinValue(10); - mockCustomMetaDataFieldSchemaObject.setMaxValue(100); - - CustomMetaDataFieldCreateRequest customMetaDataFieldCreateRequest = new CustomMetaDataFieldCreateRequest(); - customMetaDataFieldCreateRequest.setName("mockName"); - customMetaDataFieldCreateRequest.setLabel("mockLabel"); - customMetaDataFieldCreateRequest.setSchema(mockCustomMetaDataFieldSchemaObject); - - ResultCustomMetaDataField resultCustomMetaDataField = SUT - .createCustomMetaDataFields(customMetaDataFieldCreateRequest); - RecordedRequest request = server.takeRequest(); - String customMetaDataFieldCreateRequestJson = "{\"name\":\"mockName\",\"label\":\"mockLabel\",\"schema\":{\"type\":\"Number\",\"minValue\":10,\"maxValue\":100}}"; - String utf8RequestBody = request.getBody().readUtf8(); - assertEquals(400, resultCustomMetaDataField.getResponseMetaData().getHttpStatusCode()); - assertEquals(customMetaDataFieldCreateRequestJson, utf8RequestBody); - assertEquals("application/json; charset=utf-8", request.getHeader("Content-Type")); - assertEquals("POST /v1/customMetadataFields HTTP/1.1", request.getRequestLine()); - assertEquals(RestClient.API_BASE_URL.concat("v1/customMetadataFields"), request.getRequestUrl().toString()); - } - - @Test - public void createCustomMetaDataFields_successExpected() - throws InterruptedException, IOException, BadRequestException, UnknownException { - - MockWebServer server = new MockWebServer(); - server.enqueue(new MockResponse().setBody("{\n" + " \"id\": \"629f2e2f7eb0fe2eb25f9988\",\n" - + " \"name\": \"test1\",\n" + " \"label\": \"test1\",\n" + " \"schema\": {\n" - + " \"type\": \"Number\",\n" + " \"isValueRequired\": false,\n" - + " \"minValue\": 10,\n" + " \"maxValue\": 1000\n" + " }\n" + "}")); - server.start(); - RestClient.API_BASE_URL = server.url("/").toString(); - - CustomMetaDataFieldSchemaObject mockCustomMetaDataFieldSchemaObject = new CustomMetaDataFieldSchemaObject(); - mockCustomMetaDataFieldSchemaObject.setType(CustomMetaDataTypeEnum.Number); - mockCustomMetaDataFieldSchemaObject.setMinValue(10); - mockCustomMetaDataFieldSchemaObject.setMaxValue(100); - - CustomMetaDataFieldCreateRequest customMetaDataFieldCreateRequest = new CustomMetaDataFieldCreateRequest(); - customMetaDataFieldCreateRequest.setName("mockName"); - customMetaDataFieldCreateRequest.setLabel("mockLabel"); - customMetaDataFieldCreateRequest.setSchema(mockCustomMetaDataFieldSchemaObject); - - SUT.createCustomMetaDataFields(customMetaDataFieldCreateRequest); - RecordedRequest request = server.takeRequest(); - - String customMetaDataFieldCreateRequestJson = "{\"name\":\"mockName\",\"label\":\"mockLabel\",\"schema\":{\"type\":\"Number\",\"minValue\":10,\"maxValue\":100}}"; - String utf8RequestBody = request.getBody().readUtf8(); - assertEquals(customMetaDataFieldCreateRequestJson, utf8RequestBody); - assertEquals("application/json; charset=utf-8", request.getHeader("Content-Type")); - assertEquals("POST /v1/customMetadataFields HTTP/1.1", request.getRequestLine()); - assertEquals(RestClient.API_BASE_URL.concat("v1/customMetadataFields"), request.getRequestUrl().toString()); - } - - @Test - public void createCustomMetaDataFields_successExpected_type_Textarea() - throws InterruptedException, IOException, BadRequestException, UnknownException { - - MockWebServer server = new MockWebServer(); - server.enqueue(new MockResponse().setBody("{\n" + - " \"name\": \"mockName\",\n" + - " \"label\": \"mockLabel\",\n" + - " \"schema\": {\n" + - " \"isValueRequired\": true,\n" + - " \"defaultValue\": \"default value of test\",\n" + - " \"type\": \"Textarea\",\n" + - " \"minLength\": 10,\n" + - " \"maxLength\": 1000\n" + - " }\n" + - "}")); - server.start(); - RestClient.API_BASE_URL = server.url("/").toString(); - - CustomMetaDataFieldSchemaObject mockCustomMetaDataFieldSchemaObject = new CustomMetaDataFieldSchemaObject(); - mockCustomMetaDataFieldSchemaObject.setValueRequired(true); - mockCustomMetaDataFieldSchemaObject.setDefaultValue("default value of test"); - mockCustomMetaDataFieldSchemaObject.setType(CustomMetaDataTypeEnum.Textarea); - mockCustomMetaDataFieldSchemaObject.setMinLength(10); - mockCustomMetaDataFieldSchemaObject.setMaxLength(100); - - CustomMetaDataFieldCreateRequest customMetaDataFieldCreateRequest = new CustomMetaDataFieldCreateRequest(); - customMetaDataFieldCreateRequest.setName("mockName"); - customMetaDataFieldCreateRequest.setLabel("mockLabel"); - customMetaDataFieldCreateRequest.setSchema(mockCustomMetaDataFieldSchemaObject); - - SUT.createCustomMetaDataFields(customMetaDataFieldCreateRequest); - RecordedRequest request = server.takeRequest(); - - String customMetaDataFieldCreateRequestJson = "{\"name\":\"mockName\",\"label\":\"mockLabel\",\"schema\":{\"type\":\"Textarea\",\"defaultValue\":\"default value of test\",\"isValueRequired\":true,\"minLength\":10,\"maxLength\":100}}"; - String utf8RequestBody = request.getBody().readUtf8(); - assertEquals(customMetaDataFieldCreateRequestJson, utf8RequestBody); - assertEquals("application/json; charset=utf-8", request.getHeader("Content-Type")); - assertEquals("POST /v1/customMetadataFields HTTP/1.1", request.getRequestLine()); - assertEquals(RestClient.API_BASE_URL.concat("v1/customMetadataFields"), request.getRequestUrl().toString()); - } - - @Test - public void createCustomMetaDataFields_successExpected_type_Date() - throws InterruptedException, IOException, BadRequestException, UnknownException { - - MockWebServer server = new MockWebServer(); - server.enqueue(new MockResponse().setBody("{\n" + - " \"id\": \"62c2d18da6f0abb293b3941a\",\n" + - " \"name\": \"name\",\n" + - " \"label\": \"label\",\n" + - " \"schema\": {\n" + - " \"type\": \"Date\",\n" + - " \"minValue\": \"2022-11-30T10:11:10+00:00\",\n" + - " \"maxValue\": \"2022-12-30T10:11:10+00:00\"\n" + - " }\n" + - "}")); - server.start(); - RestClient.API_BASE_URL = server.url("/").toString(); - - CustomMetaDataFieldSchemaObject customMetaDataFieldSchemaObject = new CustomMetaDataFieldSchemaObject(); - customMetaDataFieldSchemaObject.setType(CustomMetaDataTypeEnum.Date); - customMetaDataFieldSchemaObject.setMinValue("2022-11-30T10:11:10+00:00"); - customMetaDataFieldSchemaObject.setMaxValue("2022-12-30T10:11:10+00:00"); - - CustomMetaDataFieldCreateRequest customMetaDataFieldCreateRequest = new CustomMetaDataFieldCreateRequest(); - customMetaDataFieldCreateRequest.setName("Name"); - customMetaDataFieldCreateRequest.setLabel("Label"); - customMetaDataFieldCreateRequest.setSchema(customMetaDataFieldSchemaObject); - - SUT.createCustomMetaDataFields(customMetaDataFieldCreateRequest); - RecordedRequest request = server.takeRequest(); - - String customMetaDataFieldCreateRequestJson = "{\"name\":\"Name\",\"label\":\"Label\",\"schema\":{\"type\":\"Date\",\"minValue\":\"2022-11-30T10:11:10+00:00\",\"maxValue\":\"2022-12-30T10:11:10+00:00\"}}"; - String utf8RequestBody = request.getBody().readUtf8(); - assertEquals(customMetaDataFieldCreateRequestJson, utf8RequestBody); - assertEquals("application/json; charset=utf-8", request.getHeader("Content-Type")); - assertEquals("POST /v1/customMetadataFields HTTP/1.1", request.getRequestLine()); - assertEquals(RestClient.API_BASE_URL.concat("v1/customMetadataFields"), request.getRequestUrl().toString()); - } - - @Test - public void createCustomMetaDataFields_successExpected_type_Boolean() - throws InterruptedException, IOException, BadRequestException, UnknownException { - - MockWebServer server = new MockWebServer(); - server.enqueue(new MockResponse().setBody("{\n" + - " \"id\": \"62c2e4268eed64d4a80c585a\",\n" + - " \"name\": \"Name\",\n" + - " \"label\": \"Label\",\n" + - " \"schema\": {\n" + - " \"type\": \"Boolean\",\n" + - " \"isValueRequired\": true,\n" + - " \"defaultValue\": true\n" + - " }\n" + - "}")); - server.start(); - RestClient.API_BASE_URL = server.url("/").toString(); - - CustomMetaDataFieldSchemaObject customMetaDataFieldSchemaObject = new CustomMetaDataFieldSchemaObject(); - customMetaDataFieldSchemaObject.setType(CustomMetaDataTypeEnum.Boolean); - customMetaDataFieldSchemaObject.setValueRequired(true); - customMetaDataFieldSchemaObject.setDefaultValue(true); - - CustomMetaDataFieldCreateRequest customMetaDataFieldCreateRequest = new CustomMetaDataFieldCreateRequest(); - customMetaDataFieldCreateRequest.setName("Name"); - customMetaDataFieldCreateRequest.setLabel("Label"); - customMetaDataFieldCreateRequest.setSchema(customMetaDataFieldSchemaObject); - - SUT.createCustomMetaDataFields(customMetaDataFieldCreateRequest); - RecordedRequest request = server.takeRequest(); - - String customMetaDataFieldCreateRequestJson = "{\"name\":\"Name\",\"label\":\"Label\",\"schema\":{\"type\":\"Boolean\",\"defaultValue\":true,\"isValueRequired\":true}}"; - String utf8RequestBody = request.getBody().readUtf8(); - assertEquals(customMetaDataFieldCreateRequestJson, utf8RequestBody); - assertEquals("application/json; charset=utf-8", request.getHeader("Content-Type")); - assertEquals("POST /v1/customMetadataFields HTTP/1.1", request.getRequestLine()); - assertEquals(RestClient.API_BASE_URL.concat("v1/customMetadataFields"), request.getRequestUrl().toString()); - } - - @Test - public void createCustomMetaDataFields_successExpected_type_SingleSelect() - throws InterruptedException, IOException, BadRequestException, UnknownException { - - MockWebServer server = new MockWebServer(); - server.enqueue(new MockResponse().setBody("{\n" + - " \"id\": \"62c2cfe2a6f0ab95fcb3640f\",\n" + - " \"name\": \"Name\",\n" + - " \"label\": \"Label\",\n" + - " \"schema\": {\n" + - " \"type\": \"SingleSelect\",\n" + - " \"selectOptions\": [\n" + - " \"small\",\n" + - " \"medium\",\n" + - " \"large\",\n" + - " 30,\n" + - " 40,\n" + - " true\n" + - " ]\n" + - " }\n" + - "}")); - server.start(); - RestClient.API_BASE_URL = server.url("/").toString(); - - List objectList = new ArrayList<>(); - objectList.add("small"); - objectList.add("medium"); - objectList.add("large"); - objectList.add(30); - objectList.add(40); - objectList.add(true); - CustomMetaDataFieldSchemaObject customMetaDataFieldSchemaObject = new CustomMetaDataFieldSchemaObject(); - customMetaDataFieldSchemaObject.setType(CustomMetaDataTypeEnum.SingleSelect); - customMetaDataFieldSchemaObject.setSelectOptions(objectList); - - CustomMetaDataFieldCreateRequest customMetaDataFieldCreateRequest = new CustomMetaDataFieldCreateRequest(); - customMetaDataFieldCreateRequest.setName("Name"); - customMetaDataFieldCreateRequest.setLabel("Label"); - customMetaDataFieldCreateRequest.setSchema(customMetaDataFieldSchemaObject); - - SUT.createCustomMetaDataFields(customMetaDataFieldCreateRequest); - RecordedRequest request = server.takeRequest(); - - String customMetaDataFieldCreateRequestJson = "{\"name\":\"Name\",\"label\":\"Label\",\"schema\":{\"type\":\"SingleSelect\",\"selectOptions\":[\"small\",\"medium\",\"large\",30,40,true]}}"; - String utf8RequestBody = request.getBody().readUtf8(); - assertEquals(customMetaDataFieldCreateRequestJson, utf8RequestBody); - assertEquals("application/json; charset=utf-8", request.getHeader("Content-Type")); - assertEquals("POST /v1/customMetadataFields HTTP/1.1", request.getRequestLine()); - assertEquals(RestClient.API_BASE_URL.concat("v1/customMetadataFields"), request.getRequestUrl().toString()); - } - - @Test - public void createCustomMetaDataFields_successExpected_type_MultiSelect() - throws InterruptedException, IOException, BadRequestException, UnknownException { - - MockWebServer server = new MockWebServer(); - server.enqueue(new MockResponse().setBody("{\n" + - " \"id\": \"62c2d3c5a6f0ab2330b3b0b2\",\n" + - " \"name\": \"Name\",\n" + - " \"label\": \"Label\",\n" + - " \"schema\": {\n" + - " \"isValueRequired\": true,\n" + - " \"defaultValue\": [\n" + - " \"small\",\n" + - " 30,\n" + - " true\n" + - " ],\n" + - " \"type\": \"MultiSelect\",\n" + - " \"selectOptions\": [\n" + - " \"small\",\n" + - " \"medium\",\n" + - " \"large\",\n" + - " 30,\n" + - " 40,\n" + - " true\n" + - " ]\n" + - " }\n" + - "}")); - server.start(); - RestClient.API_BASE_URL = server.url("/").toString(); - - List objectList = new ArrayList<>(); - objectList.add("small"); - objectList.add("medium"); - objectList.add("large"); - objectList.add(30); - objectList.add(40); - objectList.add(true); - - List defaultValueObject = new ArrayList<>(); - defaultValueObject.add("small"); - defaultValueObject.add(30); - defaultValueObject.add(true); - CustomMetaDataFieldSchemaObject customMetaDataFieldSchemaObject = new CustomMetaDataFieldSchemaObject(); - customMetaDataFieldSchemaObject.setType(CustomMetaDataTypeEnum.MultiSelect); - customMetaDataFieldSchemaObject.setValueRequired(true); - customMetaDataFieldSchemaObject.setDefaultValue(defaultValueObject); - customMetaDataFieldSchemaObject.setSelectOptions(objectList); - - CustomMetaDataFieldCreateRequest customMetaDataFieldCreateRequest = new CustomMetaDataFieldCreateRequest(); - customMetaDataFieldCreateRequest.setName("Name"); - customMetaDataFieldCreateRequest.setLabel("Label"); - customMetaDataFieldCreateRequest.setSchema(customMetaDataFieldSchemaObject); - - SUT.createCustomMetaDataFields(customMetaDataFieldCreateRequest); - RecordedRequest request = server.takeRequest(); - - String customMetaDataFieldCreateRequestJson = "{\"name\":\"Name\",\"label\":\"Label\",\"schema\":{\"type\":\"MultiSelect\",\"selectOptions\":[\"small\",\"medium\",\"large\",30,40,true],\"defaultValue\":[\"small\",30,true],\"isValueRequired\":true}}"; - String utf8RequestBody = request.getBody().readUtf8(); - assertEquals(customMetaDataFieldCreateRequestJson, utf8RequestBody); - assertEquals("application/json; charset=utf-8", request.getHeader("Content-Type")); - assertEquals("POST /v1/customMetadataFields HTTP/1.1", request.getRequestLine()); - assertEquals(RestClient.API_BASE_URL.concat("v1/customMetadataFields"), request.getRequestUrl().toString()); - } - - @Test(expected = NotFoundException.class) - public void deleteCustomMetaDataField_404_Expected() - throws IOException, InterruptedException, NotFoundException, UnknownException { - MockWebServer server = new MockWebServer(); - server.enqueue(new MockResponse().setResponseCode(404) - .setBody("{\n" + " \"message\": \"No such custom metadata field exists\",\n" - + " \"help\": \"For support kindly contact us at support@imagekit.io .\"\n" + "}")); - server.start(); - RestClient.API_BASE_URL = server.url("/").toString(); - - SUT.deleteCustomMetaDataField("6296fd7091fa5768106b808E"); - server.takeRequest(); - } - - @Test - public void deleteCustomMetaDataField_successExpected() - throws IOException, InterruptedException, NotFoundException, UnknownException { - MockWebServer server = new MockWebServer(); - server.enqueue(new MockResponse().setBody("")); - server.start(); - RestClient.API_BASE_URL = server.url("/").toString(); - - SUT.deleteCustomMetaDataField("629f2e2f7eb0fe2eb25f9988"); - RecordedRequest request = server.takeRequest(); - - String utf8RequestBody = request.getBody().readUtf8(); - assertEquals("", utf8RequestBody); - assertEquals("application/json", request.getHeader("Content-Type")); - assertEquals("DELETE /v1/customMetadataFields/629f2e2f7eb0fe2eb25f9988 HTTP/1.1", request.getRequestLine()); - assertEquals(RestClient.API_BASE_URL.concat("v1/customMetadataFields/629f2e2f7eb0fe2eb25f9988"), - request.getRequestUrl().toString()); - } - - @Test(expected = NotFoundException.class) - public void updateCustomMetaDataFields_404_Expected() - throws InterruptedException, IOException, BadRequestException, NotFoundException, UnknownException { - - MockWebServer server = new MockWebServer(); - server.enqueue(new MockResponse().setResponseCode(404) - .setBody("{\n" + " \"message\": \"No such custom metadata field exists\",\n" - + " \"help\": \"For support kindly contact us at support@imagekit.io .\"\n" + "}")); - server.start(); - RestClient.API_BASE_URL = server.url("/").toString(); - - CustomMetaDataFieldSchemaObject mockCustomMetaDataFieldSchemaObject = new CustomMetaDataFieldSchemaObject(); - mockCustomMetaDataFieldSchemaObject.setMinLength(10); - - CustomMetaDataFieldUpdateRequest customMetaDataFieldUpdateRequest = new CustomMetaDataFieldUpdateRequest(); - customMetaDataFieldUpdateRequest.setId("6296fd7091fa5768106b808E"); - customMetaDataFieldUpdateRequest.setLabel("mockEditLabel"); - customMetaDataFieldUpdateRequest.setSchema(mockCustomMetaDataFieldSchemaObject); - - SUT.updateCustomMetaDataFields(customMetaDataFieldUpdateRequest); - server.takeRequest(); - } - - @Test(expected = BadRequestException.class) - public void updateCustomMetaDataFields_400_Expected() - throws InterruptedException, IOException, BadRequestException, NotFoundException, UnknownException { - - MockWebServer server = new MockWebServer(); - server.enqueue(new MockResponse().setResponseCode(400) - .setBody("{\n" + " \"message\": \"Invalid schema object\",\n" - + " \"help\": \"For support kindly contact us at support@imagekit.io .\",\n" - + " \"errors\": {\n" + " \"minLength\": \"not allowed for this type\"\n" + " }\n" - + "}")); - server.start(); - RestClient.API_BASE_URL = server.url("/").toString(); - - CustomMetaDataFieldSchemaObject mockCustomMetaDataFieldSchemaObject = new CustomMetaDataFieldSchemaObject(); - mockCustomMetaDataFieldSchemaObject.setMinLength(10); - - CustomMetaDataFieldUpdateRequest customMetaDataFieldUpdateRequest = new CustomMetaDataFieldUpdateRequest(); - customMetaDataFieldUpdateRequest.setId("628f189d4e4ea318b69efa9d"); - customMetaDataFieldUpdateRequest.setLabel("mockEditLabel"); - customMetaDataFieldUpdateRequest.setSchema(mockCustomMetaDataFieldSchemaObject); - - SUT.updateCustomMetaDataFields(customMetaDataFieldUpdateRequest); - server.takeRequest(); - } - - @Test - public void updateCustomMetaDataFields_successExpected() - throws InterruptedException, IOException, BadRequestException, NotFoundException, UnknownException { - - MockWebServer server = new MockWebServer(); - server.enqueue(new MockResponse() - .setBody("{\n" + " \"id\": \"6296fd7091fa5768106b808d\",\n" + " \"name\": \"Amount3\",\n" - + " \"label\": \"testPrices\",\n" + " \"schema\": {\n" + " \"minValue\": 0,\n" - + " \"maxValue\": 10,\n" + " \"type\": \"Number\"\n" + " }\n" + "}")); - server.start(); - RestClient.API_BASE_URL = server.url("/").toString(); - - CustomMetaDataFieldSchemaObject mockCustomMetaDataFieldSchemaObject = new CustomMetaDataFieldSchemaObject(); - mockCustomMetaDataFieldSchemaObject.setType(CustomMetaDataTypeEnum.Number); - mockCustomMetaDataFieldSchemaObject.setMinValue(10); - mockCustomMetaDataFieldSchemaObject.setMaxValue(100); - - CustomMetaDataFieldUpdateRequest customMetaDataFieldUpdateRequest = new CustomMetaDataFieldUpdateRequest(); - customMetaDataFieldUpdateRequest.setId("628f189d4e4ea318b69efa9d"); - customMetaDataFieldUpdateRequest.setLabel("mockEditLabel"); - customMetaDataFieldUpdateRequest.setSchema(mockCustomMetaDataFieldSchemaObject); - - SUT.updateCustomMetaDataFields(customMetaDataFieldUpdateRequest); - RecordedRequest request = server.takeRequest(); - - String customMetaDataFieldUpdateRequestJson = "{\"id\":\"628f189d4e4ea318b69efa9d\",\"label\":\"mockEditLabel\",\"schema\":{\"type\":\"Number\",\"minValue\":10,\"maxValue\":100}}"; - String utf8RequestBody = request.getBody().readUtf8(); - assertEquals(customMetaDataFieldUpdateRequestJson, utf8RequestBody); - assertEquals("application/json; charset=utf-8", request.getHeader("Content-Type")); - assertEquals("PATCH /v1/customMetadataFields/628f189d4e4ea318b69efa9d HTTP/1.1", request.getRequestLine()); - assertEquals(RestClient.API_BASE_URL.concat("v1/customMetadataFields/628f189d4e4ea318b69efa9d"), - request.getRequestUrl().toString()); - } -} diff --git a/imagekit-sdk/src/test/java/io/imagekit/sdk/manage/FileTest.java b/imagekit-sdk/src/test/java/io/imagekit/sdk/manage/FileTest.java deleted file mode 100644 index 9e2c7fb..0000000 --- a/imagekit-sdk/src/test/java/io/imagekit/sdk/manage/FileTest.java +++ /dev/null @@ -1,589 +0,0 @@ -package io.imagekit.sdk.manage; - -import com.google.gson.JsonArray; -import com.google.gson.JsonObject; -import io.imagekit.sdk.ImageKit; -import io.imagekit.sdk.ImageKitTest; -import io.imagekit.sdk.exceptions.BadRequestException; -import io.imagekit.sdk.exceptions.ForbiddenException; -import io.imagekit.sdk.exceptions.InternalServerException; -import io.imagekit.sdk.exceptions.NotFoundException; -import io.imagekit.sdk.exceptions.PartialSuccessException; -import io.imagekit.sdk.exceptions.TooManyRequestsException; -import io.imagekit.sdk.exceptions.UnauthorizedException; -import io.imagekit.sdk.exceptions.UnknownException; -import io.imagekit.sdk.models.FileUpdateRequest; -import io.imagekit.sdk.models.GetFileListRequest; -import io.imagekit.sdk.tasks.RestClient; -import io.imagekit.sdk.utils.Utils; -import okhttp3.mockwebserver.MockResponse; -import okhttp3.mockwebserver.MockWebServer; -import okhttp3.mockwebserver.RecordedRequest; -import org.junit.Before; -import org.junit.Test; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import static org.junit.Assert.assertEquals; - -public class FileTest { - - private ImageKit SUT; - - @Before - public void setUp() throws Exception { - SUT = ImageKit.getInstance(); - SUT.setConfig(Utils.getSystemConfig(ImageKitTest.class)); - } - - @Test(expected = UnknownException.class) - public void imageKit_updateDetails_expected_404() - throws IOException, InterruptedException, BadRequestException, InternalServerException, UnknownException, - ForbiddenException, TooManyRequestsException, UnauthorizedException { - - FileUpdateRequest fileUpdateRequest = new FileUpdateRequest("62a9c3ccd875ec6fd658c804"); - MockWebServer server = new MockWebServer(); - String responseJson = "{\n" + " \"message\": \"The requested file does not exist.\",\n" - + " \"help\": \"For support kindly contact us at support@imagekit.io .\"\n" + "}"; - server.enqueue(new MockResponse().setResponseCode(404).setBody(responseJson)); - server.start(); - RestClient.API_BASE_URL = server.url("/").toString(); - SUT.updateFileDetail(fileUpdateRequest); - server.takeRequest(); - } - - @Test(expected = UnknownException.class) - public void imageKit_updateDetails_expected_400() - throws IOException, InterruptedException, BadRequestException, InternalServerException, UnknownException, - ForbiddenException, TooManyRequestsException, UnauthorizedException { - - FileUpdateRequest fileUpdateRequest = new FileUpdateRequest("62a9c3ccd875ec6fd658c804"); - MockWebServer server = new MockWebServer(); - String responseJson = "{\n" + " \"message\": \"The requested file does not exist.\",\n" - + " \"help\": \"For support kindly contact us at support@imagekit.io .\"\n" + "}"; - server.enqueue(new MockResponse().setResponseCode(404).setBody(responseJson)); - server.start(); - RestClient.API_BASE_URL = server.url("/").toString(); - SUT.updateFileDetail(fileUpdateRequest); - server.takeRequest(); - } - - @Test - public void imageKit_updateDetails_returnTrue() - throws IOException, InterruptedException, BadRequestException, InternalServerException, UnknownException, - ForbiddenException, TooManyRequestsException, UnauthorizedException { - - MockWebServer server = new MockWebServer(); - server.enqueue(new MockResponse().setBody("{\n" + - " \"type\": \"file\",\n" + - " \"name\": \"new_car.jpg\",\n" + - " \"createdAt\": \"2022-06-15T11:34:36.294Z\",\n" + - " \"updatedAt\": \"2022-07-04T10:15:50.067Z\",\n" + - " \"fileId\": \"62a9c3ccd875ec6fd658c854\",\n" + - " \"tags\": [\n" + - " \"Software\",\n" + - " \"Developer\",\n" + - " \"Engineer\"\n" + - " ],\n" + - " \"AITags\": [\n" + - " {\n" + - " \"name\": \"Clothing\",\n" + - " \"confidence\": 98.77,\n" + - " \"source\": \"google-auto-tagging\"\n" + - " },\n" + - " {\n" + - " \"name\": \"Smile\",\n" + - " \"confidence\": 95.31,\n" + - " \"source\": \"google-auto-tagging\"\n" + - " },\n" + - " {\n" + - " \"name\": \"Shoe\",\n" + - " \"confidence\": 95.2,\n" + - " \"source\": \"google-auto-tagging\"\n" + - " },\n" + - " {\n" + - " \"name\": \"Street light\",\n" + - " \"confidence\": 91.05,\n" + - " \"source\": \"google-auto-tagging\"\n" + - " },\n" + - " {\n" + - " \"name\": \"Person\",\n" + - " \"confidence\": 96.5,\n" + - " \"source\": \"aws-auto-tagging\"\n" + - " },\n" + - " {\n" + - " \"name\": \"Female\",\n" + - " \"confidence\": 91.27,\n" + - " \"source\": \"aws-auto-tagging\"\n" + - " },\n" + - " {\n" + - " \"name\": \"Flyer\",\n" + - " \"confidence\": 90.62,\n" + - " \"source\": \"aws-auto-tagging\"\n" + - " },\n" + - " {\n" + - " \"name\": \"Poster\",\n" + - " \"confidence\": 90.62,\n" + - " \"source\": \"aws-auto-tagging\"\n" + - " },\n" + - " {\n" + - " \"name\": \"Advertisement\",\n" + - " \"confidence\": 90.62,\n" + - " \"source\": \"aws-auto-tagging\"\n" + - " },\n" + - " {\n" + - " \"name\": \"Plant\",\n" + - " \"confidence\": 96.51,\n" + - " \"source\": \"google-auto-tagging\"\n" + - " },\n" + - " {\n" + - " \"name\": \"Street fashion\",\n" + - " \"confidence\": 89.1,\n" + - " \"source\": \"google-auto-tagging\"\n" + - " },\n" + - " {\n" + - " \"name\": \"Fashion\",\n" + - " \"confidence\": 88.46,\n" + - " \"source\": \"google-auto-tagging\"\n" + - " },\n" + - " {\n" + - " \"name\": \"Tree\",\n" + - " \"confidence\": 87.62,\n" + - " \"source\": \"google-auto-tagging\"\n" + - " },\n" + - " {\n" + - " \"name\": \"Yellow\",\n" + - " \"confidence\": 85.76,\n" + - " \"source\": \"google-auto-tagging\"\n" + - " },\n" + - " {\n" + - " \"name\": \"Happy\",\n" + - " \"confidence\": 84.01,\n" + - " \"source\": \"google-auto-tagging\"\n" + - " },\n" + - " {\n" + - " \"name\": \"Grass\",\n" + - " \"confidence\": 82.89,\n" + - " \"source\": \"google-auto-tagging\"\n" + - " },\n" + - " {\n" + - " \"name\": \"Leisure\",\n" + - " \"confidence\": 81.19,\n" + - " \"source\": \"google-auto-tagging\"\n" + - " },\n" + - " {\n" + - " \"name\": \"Morning\",\n" + - " \"confidence\": 79.09,\n" + - " \"source\": \"google-auto-tagging\"\n" + - " },\n" + - " {\n" + - " \"name\": \"Summer\",\n" + - " \"confidence\": 78.87,\n" + - " \"source\": \"google-auto-tagging\"\n" + - " },\n" + - " {\n" + - " \"name\": \"People\",\n" + - " \"confidence\": 77.9,\n" + - " \"source\": \"google-auto-tagging\"\n" + - " },\n" + - " {\n" + - " \"name\": \"Electric blue\",\n" + - " \"confidence\": 75.57,\n" + - " \"source\": \"google-auto-tagging\"\n" + - " },\n" + - " {\n" + - " \"name\": \"Beauty\",\n" + - " \"confidence\": 75.22,\n" + - " \"source\": \"google-auto-tagging\"\n" + - " },\n" + - " {\n" + - " \"name\": \"Denim\",\n" + - " \"confidence\": 74.91,\n" + - " \"source\": \"google-auto-tagging\"\n" + - " },\n" + - " {\n" + - " \"name\": \"Recreation\",\n" + - " \"confidence\": 74.33,\n" + - " \"source\": \"google-auto-tagging\"\n" + - " },\n" + - " {\n" + - " \"name\": \"Publication\",\n" + - " \"confidence\": 74.24,\n" + - " \"source\": \"google-auto-tagging\"\n" + - " }\n" + - " ],\n" + - " \"versionInfo\": {\n" + - " \"id\": \"62b97749f63122840530fda9\",\n" + - " \"name\": \"Version 4\"\n" + - " },\n" + - " \"embeddedMetadata\": {\n" + - " \"DateCreated\": \"2022-07-04T10:15:50.066Z\",\n" + - " \"DateTimeCreated\": \"2022-07-04T10:15:50.066Z\"\n" + - " },\n" + - " \"customCoordinates\": null,\n" + - " \"customMetadata\": {\n" + - " \"test100\": 10,\n" + - " \"test10\": 11\n" + - " },\n" + - " \"isPrivateFile\": false,\n" + - " \"url\": \"https://ik.imagekit.io/zv3rkhsym/new_car.jpg\",\n" + - " \"thumbnail\": \"https://ik.imagekit.io/zv3rkhsym/tr:n-ik_ml_thumbnail/new_car.jpg\",\n" + - " \"fileType\": \"image\",\n" + - " \"filePath\": \"/new_car.jpg\",\n" + - " \"height\": 354,\n" + - " \"width\": 236,\n" + - " \"size\": 7390,\n" + - " \"hasAlpha\": false,\n" + - " \"mime\": \"image/jpeg\"\n" + - "}")); - server.start(); - RestClient.API_BASE_URL = server.url("/").toString(); - List tags = new ArrayList<>(); - tags.add("Software"); - tags.add("Developer"); - tags.add("Engineer"); - - List aiTags = new ArrayList<>(); - aiTags.add("Plant"); - FileUpdateRequest fileUpdateRequest = new FileUpdateRequest("62a9c3ccd875ec6fd658c854"); - fileUpdateRequest.setRemoveAITags(aiTags); - fileUpdateRequest.setWebhookUrl("https://webhook.site/c78d617f-33bc-40d9-9e61-608999721e2e"); - - JsonObject optionsInnerObject = new JsonObject(); - optionsInnerObject.addProperty("add_shadow", true); - optionsInnerObject.addProperty("bg_color", "yellow"); - JsonObject innerObject1 = new JsonObject(); - innerObject1.addProperty("name", "remove-bg"); - innerObject1.add("options", optionsInnerObject); - JsonObject innerObject2 = new JsonObject(); - innerObject2.addProperty("name", "google-auto-tagging"); - innerObject2.addProperty("minConfidence", 15); - innerObject2.addProperty("maxTags", 20); - JsonArray jsonArray = new JsonArray(); - jsonArray.add(innerObject1); - jsonArray.add(innerObject2); - - fileUpdateRequest.setExtensions(jsonArray); - fileUpdateRequest.setTags(tags); - fileUpdateRequest.setCustomCoordinates("10,10,40,40"); - JsonObject jsonObjectCustomMetadata = new JsonObject(); - jsonObjectCustomMetadata.addProperty("test10", 11); - fileUpdateRequest.setCustomMetadata(jsonObjectCustomMetadata); - - SUT.updateFileDetail(fileUpdateRequest); - RecordedRequest request = server.takeRequest(); - - String requestJson = "{\"fileId\":\"62a9c3ccd875ec6fd658c854\",\"removeAITags\":[\"Plant\"],\"webhookUrl\":\"https://webhook.site/c78d617f-33bc-40d9-9e61-608999721e2e\",\"extensions\":[{\"name\":\"remove-bg\",\"options\":{\"add_shadow\":true,\"bg_color\":\"yellow\"}},{\"name\":\"google-auto-tagging\",\"minConfidence\":15,\"maxTags\":20}],\"tags\":[\"Software\",\"Developer\",\"Engineer\"],\"customCoordinates\":\"10,10,40,40\",\"customMetadata\":{\"test10\":11}}"; - String utf8RequestBody = request.getBody().readUtf8(); - assertEquals(requestJson, utf8RequestBody); - assertEquals("application/json; charset=utf-8", request.getHeader("Content-Type")); - assertEquals("PATCH /v1/files/62a9c3ccd875ec6fd658c854/details HTTP/1.1", request.getRequestLine()); - assertEquals(RestClient.API_BASE_URL.concat("v1/files/62a9c3ccd875ec6fd658c854/details"), - request.getRequestUrl().toString()); - } - - @Test - public void imageKit_getFileList_returnList() - throws InterruptedException, IOException, ForbiddenException, TooManyRequestsException, InternalServerException, UnauthorizedException, BadRequestException, UnknownException, IllegalAccessException, InstantiationException { - - MockWebServer server = new MockWebServer(); - String responseJson = "[\n" + " {\n" + " \"type\": \"file\",\n" - + " \"name\": \"default-image.jpg\",\n" - + " \"createdAt\": \"2022-06-11T07:26:19.294Z\",\n" - + " \"updatedAt\": \"2022-06-11T07:26:19.600Z\",\n" - + " \"fileId\": \"62a4439bce686814dfcce65c\",\n" + " \"tags\": null,\n" - + " \"AITags\": null,\n" + " \"versionInfo\": {\n" - + " \"id\": \"62a4439bce686814dfcce65c\",\n" + " \"name\": \"Version 1\"\n" - + " },\n" + " \"embeddedMetadata\": {\n" - + " \"DateCreated\": \"2022-06-11T07:26:19.599Z\",\n" - + " \"DateTimeCreated\": \"2022-06-11T07:26:19.600Z\"\n" + " },\n" - + " \"customCoordinates\": null,\n" + " \"customMetadata\": {},\n" - + " \"isPrivateFile\": false,\n" - + " \"url\": \"https://ik.imagekit.io/zv3rkhsym/default-image.jpg\",\n" - + " \"thumbnail\": \"https://ik.imagekit.io/zv3rkhsym/tr:n-ik_ml_thumbnail/default-image.jpg\",\n" - + " \"fileType\": \"image\",\n" + " \"filePath\": \"/default-image.jpg\",\n" - + " \"height\": 1000,\n" + " \"width\": 1000,\n" + " \"size\": 147022,\n" - + " \"hasAlpha\": false,\n" + " \"mime\": \"image/jpeg\"\n" + " }\n" + "]"; - server.enqueue(new MockResponse().setBody(responseJson)); - server.start(); - RestClient.API_BASE_URL = server.url("/").toString(); - String[] tags = new String[3]; - tags[0] = "Software"; - tags[1] = "Developer"; - tags[2] = "Engineer"; - GetFileListRequest getFileListRequest = new GetFileListRequest(); - getFileListRequest.setType("file"); - getFileListRequest.setSort("ASC_CREATED"); - getFileListRequest.setPath("/"); - getFileListRequest.setSearchQuery("createdAt >= '2d' OR size < '2mb' OR format='png'"); - getFileListRequest.setFileType("all"); - getFileListRequest.setLimit("1"); - getFileListRequest.setSkip("0"); - getFileListRequest.setTags(tags); - SUT.getFileList(getFileListRequest); - - RecordedRequest request = server.takeRequest(); - String utf8RequestBody = request.getBody().readUtf8(); - assertEquals("", utf8RequestBody); - assertEquals("application/json", request.getHeader("Content-Type")); - assertEquals( - "GET /v1/files?path=/&searchQuery=createdAt%20%3E=%20%272d%27%20OR%20size%20%3C%20%272mb%27%20OR%20format=%27png%27&limit=1&skip=0&sort=ASC_CREATED&type=file&fileType=all&tags=Software,Developer,Engineer HTTP/1.1", - request.getRequestLine()); - assertEquals(RestClient.API_BASE_URL.concat( - "v1/files?path=/&searchQuery=createdAt%20%3E=%20%272d%27%20OR%20size%20%3C%20%272mb%27%20OR%20format=%27png%27&limit=1&skip=0&sort=ASC_CREATED&type=file&fileType=all&tags=Software,Developer,Engineer"), - request.getRequestUrl().toString()); - - } - - @Test(expected = BadRequestException.class) - public void imageKit_getFileList_400_expected() - throws InterruptedException, ForbiddenException, TooManyRequestsException, InternalServerException, - UnauthorizedException, BadRequestException, UnknownException, IOException, IllegalAccessException, InstantiationException { - - MockWebServer server = new MockWebServer(); - String responseJson = "{\n" - + " \"message\": \"Invalid search query - createdAt field must have a valid date value. Make sure the value is enclosed within quotes. Please refer to the documentation for syntax specification.\",\n" - + " \"help\": \"For support kindly contact us at support@imagekit.io .\"\n" + "}"; - server.enqueue(new MockResponse().setResponseCode(400).setBody(responseJson)); - server.start(); - RestClient.API_BASE_URL = server.url("/").toString(); - String[] tags = new String[3]; - tags[0] = "Software"; - tags[1] = "Developer"; - tags[2] = "Engineer"; - GetFileListRequest getFileListRequest = new GetFileListRequest(); - getFileListRequest.setType("file"); - getFileListRequest.setSort("ASC_CREATED"); - getFileListRequest.setPath("/"); - getFileListRequest.setSearchQuery("createdAt >= '2d' OR size < '2mb' OR format='png'"); - getFileListRequest.setFileType("all"); - getFileListRequest.setLimit("1"); - getFileListRequest.setSkip("0"); - getFileListRequest.setTags(tags); - SUT.getFileList(getFileListRequest); - - server.takeRequest(); - } - - @Test(expected = BadRequestException.class) - public void imageKit_getFileDetail__expected_400() - throws IOException, InterruptedException, BadRequestException, InternalServerException, UnknownException, - ForbiddenException, TooManyRequestsException, UnauthorizedException { - - MockWebServer server = new MockWebServer(); - String responseJson = "{\n" + " \"message\": \"Your request contains invalid fileId parameter.\",\n" - + " \"help\": \"For support kindly contact us at support@imagekit.io .\"\n" + "}"; - server.enqueue(new MockResponse().setResponseCode(400).setBody(responseJson)); - server.start(); - RestClient.API_BASE_URL = server.url("/").toString(); - SUT.getFileDetail("fileId"); - - server.takeRequest(); - } - - @Test - public void imageKit_getFileDetail_successExpected() - throws IOException, ForbiddenException, TooManyRequestsException, InternalServerException, - UnauthorizedException, BadRequestException, UnknownException, InterruptedException { - MockWebServer server = new MockWebServer(); - String responseJson = "{\n" + " \"type\": \"file\",\n" + " \"name\": \"sample-image11_g1Qv0wpqP.jpg\",\n" - + " \"createdAt\": \"2022-06-20T05:00:41.830Z\",\n" - + " \"updatedAt\": \"2022-06-20T05:00:43.263Z\",\n" - + " \"fileId\": \"62affef97db937b028f3b47a\",\n" + " \"tags\": [\n" + " \"Software\",\n" - + " \"Developer\",\n" + " \"Engineer\"\n" + " ],\n" + " \"AITags\": null,\n" - + " \"versionInfo\": {\n" + " \"id\": \"62affef97db937b028f3b47a\",\n" - + " \"name\": \"Version 1\"\n" + " },\n" + " \"embeddedMetadata\": {},\n" - + " \"customCoordinates\": null,\n" + " \"customMetadata\": {},\n" - + " \"isPrivateFile\": false,\n" - + " \"url\": \"https://ik.imagekit.io/zv3rkhsym/sample-image11_g1Qv0wpqP.jpg\",\n" - + " \"thumbnail\": \"https://ik.imagekit.io/demo/img/static-file-1.png\",\n" - + " \"fileType\": \"non-image\",\n" + " \"filePath\": \"/sample-image11_g1Qv0wpqP.jpg\",\n" - + " \"size\": 169170\n" + "}"; - server.enqueue(new MockResponse().setBody(responseJson)); - server.start(); - RestClient.API_BASE_URL = server.url("/").toString(); - SUT.getFileDetail("62affef97db937b028f3b47a"); - - RecordedRequest request = server.takeRequest(); - String utf8RequestBody = request.getBody().readUtf8(); - assertEquals("", utf8RequestBody); - assertEquals("application/json", request.getHeader("Content-Type")); - assertEquals("GET /v1/files/62affef97db937b028f3b47a/details HTTP/1.1", request.getRequestLine()); - assertEquals(RestClient.API_BASE_URL.concat("v1/files/62affef97db937b028f3b47a/details"), - request.getRequestUrl().toString()); - } - - @Test - public void imageKit_getFileMetaData_successExpected() - throws IOException, ForbiddenException, TooManyRequestsException, InternalServerException, - UnauthorizedException, BadRequestException, UnknownException, InterruptedException { - MockWebServer server = new MockWebServer(); - String responseJson = "{\n" + " \"height\": 300,\n" + " \"width\": 300,\n" + " \"size\": 51085,\n" - + " \"format\": \"jpg\",\n" + " \"hasColorProfile\": false,\n" + " \"quality\": 0,\n" - + " \"density\": 300,\n" + " \"hasTransparency\": false,\n" + " \"exif\": {\n" - + " \"image\": {\n" + " \"Orientation\": 1,\n" + " \"XResolution\": 300,\n" - + " \"YResolution\": 300,\n" + " \"ResolutionUnit\": 2,\n" - + " \"Software\": \"Adobe Photoshop CS5 (12.0x20100115 [20100115.m.998 2010/01/15:02:00:00 cutoff; m branch]) Windows\",\n" - + " \"ModifyDate\": \"2017:09:11 22:15:46\",\n" + " \"ExifOffset\": 236\n" - + " },\n" + " \"thumbnail\": {\n" + " \"Compression\": 6,\n" - + " \"XResolution\": 72,\n" + " \"YResolution\": 72,\n" - + " \"ResolutionUnit\": 2,\n" + " \"ThumbnailOffset\": 374,\n" - + " \"ThumbnailLength\": 4083\n" + " },\n" + " \"exif\": {\n" - + " \"ColorSpace\": 65535,\n" + " \"ExifImageWidth\": 300,\n" - + " \"ExifImageHeight\": 300\n" + " },\n" + " \"gps\": {},\n" - + " \"interoperability\": {},\n" + " \"makernote\": {}\n" + " },\n" - + " \"pHash\": \"2df5da2dd63c6926\"\n" + "}"; - server.enqueue(new MockResponse().setBody(responseJson)); - server.start(); - RestClient.API_BASE_URL = server.url("/").toString(); - SUT.getFileMetadata("62b43109d23153217b8b8a36"); - - RecordedRequest request = server.takeRequest(); - String utf8RequestBody = request.getBody().readUtf8(); - assertEquals("", utf8RequestBody); - assertEquals("application/json", request.getHeader("Content-Type")); - assertEquals("GET /v1/files/62b43109d23153217b8b8a36/metadata HTTP/1.1", request.getRequestLine()); - assertEquals(RestClient.API_BASE_URL.concat("v1/files/62b43109d23153217b8b8a36/metadata"), - request.getRequestUrl().toString()); - - } - - @Test(expected = BadRequestException.class) - public void imageKit_getFileMetaData_400_Expected() - throws IOException, ForbiddenException, TooManyRequestsException, InternalServerException, - UnauthorizedException, BadRequestException, UnknownException, InterruptedException { - MockWebServer server = new MockWebServer(); - String responseJson = "{\n" + " \"message\": \"Your request contains invalid fileId parameter.\",\n" - + " \"help\": \"For support kindly contact us at support@imagekit.io .\",\n" - + " \"type\": \"INVALID_PARAM_ERROR\"\n" + "}"; - server.enqueue(new MockResponse().setResponseCode(400).setBody(responseJson)); - server.start(); - RestClient.API_BASE_URL = server.url("/").toString(); - SUT.getFileMetadata("fileId"); - server.takeRequest(); - } - - @Test - public void imageKit_getRemoteFileMetaData_successExpected() - throws IOException, ForbiddenException, TooManyRequestsException, InternalServerException, - UnauthorizedException, BadRequestException, UnknownException, InterruptedException { - MockWebServer server = new MockWebServer(); - String responseJson = "{\n" + " \"height\": 1000,\n" + " \"width\": 1000,\n" + " \"size\": 147022,\n" - + " \"format\": \"jpg\",\n" + " \"hasColorProfile\": false,\n" + " \"quality\": 0,\n" - + " \"density\": 72,\n" + " \"hasTransparency\": false,\n" + " \"exif\": {},\n" - + " \"pHash\": \"e0d52b612ad538f6\"\n" + "}"; - server.enqueue(new MockResponse().setBody(responseJson)); - server.start(); - RestClient.API_BASE_URL = server.url("/").toString(); - SUT.getRemoteFileMetadata("https://ik.imagekit.io/zv3rkhsym/default-image.jpg"); - - RecordedRequest request = server.takeRequest(); - String utf8RequestBody = request.getBody().readUtf8(); - assertEquals("", utf8RequestBody); - assertEquals("application/json", request.getHeader("Content-Type")); - assertEquals("GET /v1/metadata?url=https://ik.imagekit.io/zv3rkhsym/default-image.jpg HTTP/1.1", - request.getRequestLine()); - assertEquals( - RestClient.API_BASE_URL.concat("v1/metadata?url=https://ik.imagekit.io/zv3rkhsym/default-image.jpg"), - request.getRequestUrl().toString()); - - } - - @Test(expected = BadRequestException.class) - public void imageKit_getRemoteFileMetaData_400_Expected() - throws ForbiddenException, TooManyRequestsException, InternalServerException, UnauthorizedException, - BadRequestException, UnknownException, InterruptedException, IOException { - MockWebServer server = new MockWebServer(); - String responseJson = "{\n" - + " \"message\": \"remote_url should be accessible using your ImageKit.io account.\",\n" - + " \"help\": \"For support kindly contact us at support@imagekit.io .\"\n" + "}"; - server.enqueue(new MockResponse().setResponseCode(400).setBody(responseJson)); - server.start(); - RestClient.API_BASE_URL = server.url("/").toString(); - SUT.getRemoteFileMetadata("remote_url"); - - server.takeRequest(); - } - - @Test(expected = BadRequestException.class) - public void imageKit_deleteFile_400_Expected() - throws ForbiddenException, TooManyRequestsException, InternalServerException, UnauthorizedException, - BadRequestException, UnknownException, InterruptedException, IOException { - MockWebServer server = new MockWebServer(); - String responseJson = "{\n" + " \"message\": \"Your request contains invalid fileId parameter.\",\n" - + " \"help\": \"For support kindly contact us at support@imagekit.io .\"\n" + "}"; - server.enqueue(new MockResponse().setResponseCode(400).setBody(responseJson)); - server.start(); - RestClient.API_BASE_URL = server.url("/").toString(); - SUT.deleteFile("629f3de17eb0fe4053615450"); - - server.takeRequest(); - } - - @Test - public void imageKit_deleteFile_successExpected() - throws IOException, ForbiddenException, TooManyRequestsException, InternalServerException, - UnauthorizedException, BadRequestException, UnknownException, InterruptedException { - MockWebServer server = new MockWebServer(); - String responseJson = ""; - server.enqueue(new MockResponse().setResponseCode(204).setBody(responseJson)); - server.start(); - RestClient.API_BASE_URL = server.url("/").toString(); - SUT.deleteFile("62affef97db937b028f3b47a"); - - RecordedRequest request = server.takeRequest(); - String utf8RequestBody = request.getBody().readUtf8(); - assertEquals("", utf8RequestBody); - assertEquals("application/json", request.getHeader("Content-Type")); - assertEquals("DELETE /v1/files/62affef97db937b028f3b47a HTTP/1.1", request.getRequestLine()); - assertEquals(RestClient.API_BASE_URL.concat("v1/files/62affef97db937b028f3b47a"), - request.getRequestUrl().toString()); - } - - @Test(expected = NotFoundException.class) - public void imageKit_bulkDeleteFiles_404Expected() throws ForbiddenException, TooManyRequestsException, - InternalServerException, PartialSuccessException, UnauthorizedException, NotFoundException, - BadRequestException, UnknownException, IOException, InterruptedException { - List fileIds = new ArrayList<>(); - fileIds.add("file_id_1"); - fileIds.add("file_id_2"); - fileIds.add("file_id_3"); - MockWebServer server = new MockWebServer(); - String responseJson = "{\n" + " \"message\": \"The requested file(s) does not exist.\",\n" - + " \"help\": \"For support kindly contact us at support@imagekit.io .\",\n" - + " \"missingFileIds\": [\n" + " \"62ad9ece7db937e35ef18dda\"\n" + " ]\n" + "}"; - server.enqueue(new MockResponse().setResponseCode(404).setBody(responseJson)); - server.start(); - RestClient.API_BASE_URL = server.url("/").toString(); - SUT.bulkDeleteFiles(fileIds); - - server.takeRequest(); - } - - @Test - public void imageKit_bulkDeleteFiles_successExpected() throws ForbiddenException, TooManyRequestsException, - InternalServerException, PartialSuccessException, UnauthorizedException, NotFoundException, - BadRequestException, UnknownException, IOException, InterruptedException { - List fileIds = new ArrayList<>(); - fileIds.add("62ad9ece7db937e35ef18dda"); - MockWebServer server = new MockWebServer(); - String responseJson = "{\n" + " \"successfullyDeletedFileIds\": [\n" - + " \"62ad9ece7db937e35ef18dda\"\n" + " ]\n" + "}"; - server.enqueue(new MockResponse().setBody(responseJson)); - server.start(); - RestClient.API_BASE_URL = server.url("/").toString(); - SUT.bulkDeleteFiles(fileIds); - - RecordedRequest request = server.takeRequest(); - String utf8RequestBody = request.getBody().readUtf8(); - assertEquals("{\"fileIds\":[\"62ad9ece7db937e35ef18dda\"]}", utf8RequestBody); - assertEquals("application/json; charset=utf-8", request.getHeader("Content-Type")); - assertEquals("POST /v1/files/batch/deleteByFileIds HTTP/1.1", request.getRequestLine()); - assertEquals(RestClient.API_BASE_URL.concat("v1/files/batch/deleteByFileIds"), - request.getRequestUrl().toString()); - } -} diff --git a/imagekit-sdk/src/test/java/io/imagekit/sdk/manage/FileVersionTest.java b/imagekit-sdk/src/test/java/io/imagekit/sdk/manage/FileVersionTest.java deleted file mode 100644 index 8189f58..0000000 --- a/imagekit-sdk/src/test/java/io/imagekit/sdk/manage/FileVersionTest.java +++ /dev/null @@ -1,267 +0,0 @@ -package io.imagekit.sdk.manage; - -import io.imagekit.sdk.ImageKit; -import io.imagekit.sdk.ImageKitTest; -import io.imagekit.sdk.exceptions.BadRequestException; -import io.imagekit.sdk.exceptions.ForbiddenException; -import io.imagekit.sdk.exceptions.InternalServerException; -import io.imagekit.sdk.exceptions.NotFoundException; -import io.imagekit.sdk.exceptions.TooManyRequestsException; -import io.imagekit.sdk.exceptions.UnauthorizedException; -import io.imagekit.sdk.exceptions.UnknownException; -import io.imagekit.sdk.models.DeleteFileVersionRequest; -import io.imagekit.sdk.tasks.RestClient; -import io.imagekit.sdk.utils.Utils; -import okhttp3.mockwebserver.MockResponse; -import okhttp3.mockwebserver.MockWebServer; -import okhttp3.mockwebserver.RecordedRequest; -import org.junit.Before; -import org.junit.Test; - -import java.io.IOException; - -import static org.junit.Assert.assertEquals; - -public class FileVersionTest { - - private ImageKit SUT; - - @Before - public void setUp() throws Exception { - SUT = ImageKit.getInstance(); - SUT.setConfig(Utils.getSystemConfig(ImageKitTest.class)); - } - - @Test(expected = NotFoundException.class) - public void getFileVersions_404_Expected() - throws InterruptedException, IOException, NotFoundException, BadRequestException, InternalServerException, - UnknownException, ForbiddenException, TooManyRequestsException, UnauthorizedException { - - MockWebServer server = new MockWebServer(); - server.enqueue(new MockResponse().setResponseCode(404) - .setBody("{\n" + " \"message\": \"The requested asset does not exist.\",\n" - + " \"help\": \"For support kindly contact us at support@imagekit.io .\"\n" + "}")); - server.start(); - RestClient.API_BASE_URL = server.url("/").toString(); - SUT.getFileVersions("id"); - server.takeRequest(); - } - - @Test - public void getFileVersions_successExpected() - throws InterruptedException, IOException, NotFoundException, BadRequestException, InternalServerException, - UnknownException, ForbiddenException, TooManyRequestsException, UnauthorizedException { - - MockWebServer server = new MockWebServer(); - server.enqueue(new MockResponse().setBody("[\n" + " {\n" + " \"type\": \"file\",\n" - + " \"name\": \"w2_image.png\",\n" + " \"createdAt\": \"2022-06-07T12:00:33.825Z\",\n" - + " \"updatedAt\": \"2022-06-07T12:00:33.828Z\",\n" - + " \"fileId\": \"629f3de17eb0fe4053615450\",\n" + " \"tags\": [\n" - + " \"tag10\"\n" + " ],\n" + " \"AITags\": [\n" + " {\n" - + " \"name\": \"Colorfulness\",\n" + " \"confidence\": 96.19,\n" - + " \"source\": \"google-auto-tagging\"\n" + " },\n" + " {\n" - + " \"name\": \"Purple\",\n" + " \"confidence\": 86.05,\n" - + " \"source\": \"google-auto-tagging\"\n" + " },\n" + " {\n" - + " \"name\": \"Violet\",\n" + " \"confidence\": 81.08,\n" - + " \"source\": \"google-auto-tagging\"\n" + " },\n" + " {\n" - + " \"name\": \"Rectangle\",\n" + " \"confidence\": 80.99,\n" - + " \"source\": \"google-auto-tagging\"\n" + " }\n" + " ],\n" - + " \"versionInfo\": {\n" + " \"id\": \"629f3de17eb0fe4053615450\",\n" - + " \"name\": \"Version 1\"\n" + " },\n" + " \"embeddedMetadata\": {\n" - + " \"DateCreated\": \"2022-05-26T06:05:18.087Z\",\n" + " \"ImageWidth\": 1006,\n" - + " \"ImageHeight\": 467,\n" - + " \"DateTimeCreated\": \"2022-05-26T06:05:18.088Z\"\n" + " },\n" - + " \"customCoordinates\": null,\n" + " \"customMetadata\": {},\n" - + " \"isPrivateFile\": false,\n" - + " \"url\": \"https://ik.imagekit.io/xyxt2lnil/w2_image.png\",\n" - + " \"thumbnail\": \"https://ik.imagekit.io/xyxt2lnil/tr:n-ik_ml_thumbnail/w2_image.png\",\n" - + " \"fileType\": \"image\",\n" + " \"filePath\": \"/w2_image.png\",\n" - + " \"height\": 467,\n" + " \"width\": 1006,\n" + " \"size\": 47579,\n" - + " \"hasAlpha\": true,\n" + " \"mime\": \"image/png\"\n" + " }\n" + "]")); - server.start(); - RestClient.API_BASE_URL = server.url("/").toString(); - SUT.getFileVersions("629f3de17eb0fe4053615450"); - RecordedRequest request = server.takeRequest(); - - assertEquals("application/json", request.getHeader("Content-Type")); - assertEquals("GET /v1/files/629f3de17eb0fe4053615450/versions HTTP/1.1", request.getRequestLine()); - assertEquals(RestClient.API_BASE_URL.concat("v1/files/629f3de17eb0fe4053615450/versions"), - request.getRequestUrl().toString()); - } - - @Test(expected = NotFoundException.class) - public void getFileVersionDetails_404_Expected() - throws InterruptedException, IOException, NotFoundException, BadRequestException, InternalServerException, - UnknownException, ForbiddenException, TooManyRequestsException, UnauthorizedException { - - MockWebServer server = new MockWebServer(); - server.enqueue(new MockResponse().setResponseCode(404) - .setBody("{\n" + " \"message\": \"The requested asset does not exist.\",\n" - + " \"help\": \"For support kindly contact us at support@imagekit.io .\"\n" + "}")); - server.start(); - RestClient.API_BASE_URL = server.url("/").toString(); - SUT.getFileVersionDetails("629f3de17eb0fe4053615450", "629f3de17eb0fe4053615450"); - server.takeRequest(); - } - - @Test - public void getFileVersionDetails_successExpected() - throws InterruptedException, IOException, NotFoundException, BadRequestException, InternalServerException, - UnknownException, ForbiddenException, TooManyRequestsException, UnauthorizedException { - - MockWebServer server = new MockWebServer(); - server.enqueue(new MockResponse().setBody("{\n" + " \"type\": \"file\",\n" - + " \"name\": \"w2_image.png\",\n" + " \"createdAt\": \"2022-06-07T12:00:33.825Z\",\n" - + " \"updatedAt\": \"2022-06-07T12:00:33.828Z\",\n" - + " \"fileId\": \"629f3de17eb0fe4053615450\",\n" + " \"tags\": [\n" + " \"tag10\"\n" - + " ],\n" + " \"AITags\": [\n" + " {\n" + " \"name\": \"Colorfulness\",\n" - + " \"confidence\": 96.19,\n" + " \"source\": \"google-auto-tagging\"\n" - + " },\n" + " {\n" + " \"name\": \"Purple\",\n" - + " \"confidence\": 86.05,\n" + " \"source\": \"google-auto-tagging\"\n" - + " },\n" + " {\n" + " \"name\": \"Violet\",\n" - + " \"confidence\": 81.08,\n" + " \"source\": \"google-auto-tagging\"\n" - + " },\n" + " {\n" + " \"name\": \"Rectangle\",\n" - + " \"confidence\": 80.99,\n" + " \"source\": \"google-auto-tagging\"\n" - + " }\n" + " ],\n" + " \"versionInfo\": {\n" - + " \"id\": \"629f3de17eb0fe4053615450\",\n" + " \"name\": \"Version 1\"\n" + " },\n" - + " \"embeddedMetadata\": {\n" + " \"DateCreated\": \"2022-05-26T06:05:18.087Z\",\n" - + " \"ImageWidth\": 1006,\n" + " \"ImageHeight\": 467,\n" - + " \"DateTimeCreated\": \"2022-05-26T06:05:18.088Z\"\n" + " },\n" - + " \"customCoordinates\": null,\n" + " \"customMetadata\": {},\n" - + " \"isPrivateFile\": false,\n" - + " \"url\": \"https://ik.imagekit.io/xyxt2lnil/w2_image.png\",\n" - + " \"thumbnail\": \"https://ik.imagekit.io/xyxt2lnil/tr:n-ik_ml_thumbnail/w2_image.png\",\n" - + " \"fileType\": \"image\",\n" + " \"filePath\": \"/w2_image.png\",\n" + " \"height\": 467,\n" - + " \"width\": 1006,\n" + " \"size\": 47579,\n" + " \"hasAlpha\": true,\n" - + " \"mime\": \"image/png\"\n" + "}")); - server.start(); - RestClient.API_BASE_URL = server.url("/").toString(); - SUT.getFileVersionDetails("629f3de17eb0fe4053615450", "629f3de17eb0fe4053615450"); - RecordedRequest request = server.takeRequest(); - - assertEquals("application/json", request.getHeader("Content-Type")); - assertEquals("GET /v1/files/629f3de17eb0fe4053615450/versions/629f3de17eb0fe4053615450 HTTP/1.1", - request.getRequestLine()); - assertEquals( - RestClient.API_BASE_URL.concat("v1/files/629f3de17eb0fe4053615450/versions/629f3de17eb0fe4053615450"), - request.getRequestUrl().toString()); - } - - @Test(expected = BadRequestException.class) - public void deleteFileVersion_400_SuccessWith() - throws IOException, InterruptedException, BadRequestException, NotFoundException, InternalServerException, - UnknownException, ForbiddenException, TooManyRequestsException, UnauthorizedException { - - DeleteFileVersionRequest deleteFileVersionRequest = new DeleteFileVersionRequest(); - deleteFileVersionRequest.setFileId("629d90768482ba272ed17628"); - deleteFileVersionRequest.setVersionId("id"); - - MockWebServer server = new MockWebServer(); - server.enqueue(new MockResponse().setResponseCode(400) - .setBody("{\n" + " \"message\": \"Your request contains invalid versionId parameter.\",\n" - + " \"help\": \"For support kindly contact us at support@imagekit.io .\"\n" + "}")); - server.start(); - RestClient.API_BASE_URL = server.url("/").toString(); - SUT.deleteFileVersion(deleteFileVersionRequest); - server.takeRequest(); - } - - @Test(expected = NotFoundException.class) - public void deleteFileVersion_404_SuccessWith() - throws IOException, InterruptedException, BadRequestException, NotFoundException, InternalServerException, - UnknownException, ForbiddenException, TooManyRequestsException, UnauthorizedException { - - DeleteFileVersionRequest deleteFileVersionRequest = new DeleteFileVersionRequest(); - deleteFileVersionRequest.setFileId("629d90768482ba272ed17628"); - deleteFileVersionRequest.setVersionId("62a9c403d89eedb81721102b"); - - MockWebServer server = new MockWebServer(); - server.enqueue(new MockResponse().setResponseCode(404) - .setBody("{\n" + " \"message\": \"The requested file version does not exist.\",\n" - + " \"help\": \"For support kindly contact us at support@imagekit.io .\"\n" + "}")); - server.start(); - RestClient.API_BASE_URL = server.url("/").toString(); - SUT.deleteFileVersion(deleteFileVersionRequest); - server.takeRequest(); - } - - @Test - public void deleteFileVersion_expectedSuccessWith() - throws IOException, InterruptedException, BadRequestException, NotFoundException, InternalServerException, - UnknownException, ForbiddenException, TooManyRequestsException, UnauthorizedException { - - DeleteFileVersionRequest deleteFileVersionRequest = new DeleteFileVersionRequest(); - deleteFileVersionRequest.setFileId("629d90768482ba272ed17628"); - deleteFileVersionRequest.setVersionId("629d91878482bae8bed177f2"); - - MockWebServer server = new MockWebServer(); - server.enqueue(new MockResponse().setResponseCode(204).setBody("")); - server.start(); - RestClient.API_BASE_URL = server.url("/").toString(); - SUT.deleteFileVersion(deleteFileVersionRequest); - RecordedRequest request = server.takeRequest(); - - String utf8RequestBody = request.getBody().readUtf8(); - assertEquals("", utf8RequestBody); - assertEquals("application/json", request.getHeader("Content-Type")); - assertEquals("DELETE /v1/files/629d90768482ba272ed17628/versions/629d91878482bae8bed177f2 HTTP/1.1", - request.getRequestLine()); - assertEquals( - RestClient.API_BASE_URL.concat("v1/files/629d90768482ba272ed17628/versions/629d91878482bae8bed177f2"), - request.getRequestUrl().toString()); - } - - @Test - public void restoreFileVersion_expectedSuccessWith() - throws IOException, InterruptedException, BadRequestException, NotFoundException, InternalServerException, - UnknownException, ForbiddenException, TooManyRequestsException, UnauthorizedException { - - MockWebServer server = new MockWebServer(); - server.enqueue(new MockResponse().setBody("{\n" + " \"type\": \"file\",\n" - + " \"name\": \"new_car.jpg\",\n" + " \"createdAt\": \"2022-06-15T11:34:36.294Z\",\n" - + " \"updatedAt\": \"2022-06-27T12:11:11.254Z\",\n" - + " \"fileId\": \"62a9c3ccd875ec6fd658c854\",\n" + " \"tags\": [\n" + " \"tagg\",\n" - + " \"tagg1\"\n" + " ],\n" + " \"AITags\": null,\n" + " \"versionInfo\": {\n" - + " \"id\": \"62b97749f63122840530fda9\",\n" + " \"name\": \"Version 1\"\n" + " },\n" - + " \"embeddedMetadata\": {\n" + " \"XResolution\": 250,\n" - + " \"YResolution\": 250,\n" + " \"DateCreated\": \"2022-06-15T11:34:36.702Z\",\n" - + " \"DateTimeCreated\": \"2022-06-15T11:34:36.702Z\"\n" + " },\n" - + " \"customCoordinates\": \"10,10,20,20\",\n" + " \"customMetadata\": {\n" - + " \"test100\": 10\n" + " },\n" + " \"isPrivateFile\": false,\n" - + " \"url\": \"https://ik.imagekit.io/zv3rkhsym/new_car.jpg\",\n" - + " \"thumbnail\": \"https://ik.imagekit.io/zv3rkhsym/tr:n-ik_ml_thumbnail/new_car.jpg\",\n" - + " \"fileType\": \"image\",\n" + " \"filePath\": \"/new_car.jpg\",\n" + " \"height\": 354,\n" - + " \"width\": 236,\n" + " \"size\": 23023,\n" + " \"hasAlpha\": false,\n" - + " \"mime\": \"image/jpeg\"\n" + "}")); - server.start(); - RestClient.API_BASE_URL = server.url("/").toString(); - SUT.restoreFileVersion("62a9c3ccd875ec6fd658c854", "62b97749f63122840530fda9"); - RecordedRequest request = server.takeRequest(); - - String utf8RequestBody = request.getBody().readUtf8(); - assertEquals("", utf8RequestBody); - assertEquals("application/json; charset=utf-8", request.getHeader("Content-Type")); - assertEquals("PUT /v1/files/62a9c3ccd875ec6fd658c854/versions/62b97749f63122840530fda9/restore HTTP/1.1", - request.getRequestLine()); - assertEquals( - RestClient.API_BASE_URL - .concat("v1/files/62a9c3ccd875ec6fd658c854/versions/62b97749f63122840530fda9/restore"), - request.getRequestUrl().toString()); - } - - @Test(expected = NotFoundException.class) - public void restoreFileVersion_expected_404() - throws IOException, InterruptedException, BadRequestException, NotFoundException, InternalServerException, - UnknownException, ForbiddenException, TooManyRequestsException, UnauthorizedException { - - MockWebServer server = new MockWebServer(); - server.enqueue(new MockResponse().setResponseCode(404) - .setBody("{\n" + " \"message\": \"The requested file version does not exist.\",\n" - + " \"help\": \"For support kindly contact us at support@imagekit.io .\"\n" + "}")); - server.start(); - RestClient.API_BASE_URL = server.url("/").toString(); - SUT.restoreFileVersion("62a9c3ccd875ec6fd658c854", "62b97749f63122840530fda9"); - RecordedRequest request = server.takeRequest(); - request.getBody().readUtf8(); - } -} diff --git a/imagekit-sdk/src/test/java/io/imagekit/sdk/manage/TagsTest.java b/imagekit-sdk/src/test/java/io/imagekit/sdk/manage/TagsTest.java deleted file mode 100644 index 3aaeb17..0000000 --- a/imagekit-sdk/src/test/java/io/imagekit/sdk/manage/TagsTest.java +++ /dev/null @@ -1,194 +0,0 @@ -package io.imagekit.sdk.manage; - -import io.imagekit.sdk.ImageKit; -import io.imagekit.sdk.ImageKitTest; -import io.imagekit.sdk.exceptions.BadRequestException; -import io.imagekit.sdk.exceptions.ForbiddenException; -import io.imagekit.sdk.exceptions.InternalServerException; -import io.imagekit.sdk.exceptions.NotFoundException; -import io.imagekit.sdk.exceptions.PartialSuccessException; -import io.imagekit.sdk.exceptions.TooManyRequestsException; -import io.imagekit.sdk.exceptions.UnauthorizedException; -import io.imagekit.sdk.exceptions.UnknownException; -import io.imagekit.sdk.models.AITagsRequest; -import io.imagekit.sdk.models.TagsRequest; -import io.imagekit.sdk.tasks.RestClient; -import io.imagekit.sdk.utils.Utils; -import okhttp3.mockwebserver.MockResponse; -import okhttp3.mockwebserver.MockWebServer; -import okhttp3.mockwebserver.RecordedRequest; -import org.junit.Before; -import org.junit.Test; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import static org.junit.Assert.assertEquals; - -public class TagsTest { - - private ImageKit SUT; - - @Before - public void setUp() throws Exception { - SUT = ImageKit.getInstance(); - SUT.setConfig(Utils.getSystemConfig(ImageKitTest.class)); - } - - @Test(expected = NotFoundException.class) - public void add_tags_expected_404() throws IOException, InterruptedException, NotFoundException, - PartialSuccessException, BadRequestException, InternalServerException, UnknownException, ForbiddenException, - TooManyRequestsException, UnauthorizedException { - - List fileIds = new ArrayList<>(); - fileIds.add("629f3de17eb0fe4053615450"); - List tags = new ArrayList<>(); - tags.add("tag1"); - tags.add("tag2"); - - TagsRequest tagsRequest = new TagsRequest(fileIds, tags); - - MockWebServer server = new MockWebServer(); - String tagsResponseJson = "{\n" + " \"message\": \"The requested file(s) does not exist.\",\n" - + " \"help\": \"For support kindly contact us at support@imagekit.io .\",\n" - + " \"missingFileIds\": [\n" + " \"629f3de17eb0fe4053615450\"\n" + " ]\n" + "}"; - server.enqueue(new MockResponse().setResponseCode(404).setBody(tagsResponseJson)); - server.start(); - RestClient.API_BASE_URL = server.url("/").toString(); - SUT.addTags(tagsRequest); - - server.takeRequest(); - } - - @Test - public void add_tags_expectedSuccessWith() throws IOException, InterruptedException, NotFoundException, - PartialSuccessException, BadRequestException, InternalServerException, UnknownException, ForbiddenException, - TooManyRequestsException, UnauthorizedException { - - List fileIds = new ArrayList<>(); - fileIds.add("62958deef33aa80bdadf7533"); - List tags = new ArrayList<>(); - tags.add("tag1"); - tags.add("tag2"); - - TagsRequest tagsRequest = new TagsRequest(fileIds, tags); - - MockWebServer server = new MockWebServer(); - server.enqueue(new MockResponse().setBody("{\"successfullyUpdatedFileIds\": [\"62958deef33aa80bdadf7533\"]}")); - server.start(); - RestClient.API_BASE_URL = server.url("/").toString(); - SUT.addTags(tagsRequest); - RecordedRequest request = server.takeRequest(); - - String tagsRequestJson = "{\"fileIds\":[\"62958deef33aa80bdadf7533\"],\"tags\":[\"tag1\",\"tag2\"]}"; - String utf8RequestBody = request.getBody().readUtf8(); - assertEquals(tagsRequestJson, utf8RequestBody); - assertEquals("application/json; charset=utf-8", request.getHeader("Content-Type")); - assertEquals("POST /v1/files/addTags HTTP/1.1", request.getRequestLine()); - assertEquals(RestClient.API_BASE_URL.concat("v1/files/addTags"), request.getRequestUrl().toString()); - } - - @Test(expected = NotFoundException.class) - public void remove_tags_expected_404_bad_request() throws InterruptedException, NotFoundException, - PartialSuccessException, BadRequestException, InternalServerException, UnknownException, ForbiddenException, - TooManyRequestsException, UnauthorizedException { - - List fileIds = new ArrayList<>(); - fileIds.add("629f3de17eb0fe4053615450"); - List tags = new ArrayList<>(); - tags.add("tag1"); - - TagsRequest tagsRequest = new TagsRequest(fileIds, tags); - - MockWebServer server = new MockWebServer(); - String tagsResponseJson = "{\n" + " \"message\": \"The requested file(s) does not exist.\",\n" - + " \"help\": \"For support kindly contact us at support@imagekit.io .\",\n" - + " \"missingFileIds\": [\n" + " \"629f3de17eb0fe4053615450\"\n" + " ]\n" + "}"; - server.enqueue(new MockResponse().setResponseCode(404).setBody(tagsResponseJson)); - RestClient.API_BASE_URL = server.url("/").toString(); - SUT.removeTags(tagsRequest); - server.takeRequest(); - } - - @Test - public void remove_tags_expectedSuccessWith() throws IOException, InterruptedException, NotFoundException, - PartialSuccessException, BadRequestException, InternalServerException, UnknownException, ForbiddenException, - TooManyRequestsException, UnauthorizedException { - - List fileIds = new ArrayList<>(); - fileIds.add("62958deef33aa80bdadf7533"); - List tags = new ArrayList<>(); - tags.add("tag1"); - - TagsRequest tagsRequest = new TagsRequest(fileIds, tags); - - MockWebServer server = new MockWebServer(); - server.enqueue(new MockResponse().setBody("{\"successfullyUpdatedFileIds\": [\"62958deef33aa80bdadf7533\"]}")); - server.start(); - RestClient.API_BASE_URL = server.url("/").toString(); - SUT.removeTags(tagsRequest); - RecordedRequest request = server.takeRequest(); - - String tagsRequestJson = "{\"fileIds\":[\"62958deef33aa80bdadf7533\"],\"tags\":[\"tag1\"]}"; - String utf8RequestBody = request.getBody().readUtf8(); - assertEquals(tagsRequestJson, utf8RequestBody); - assertEquals("application/json; charset=utf-8", request.getHeader("Content-Type")); - assertEquals("POST /v1/files/removeTags HTTP/1.1", request.getRequestLine()); - assertEquals(RestClient.API_BASE_URL.concat("v1/files/removeTags"), request.getRequestUrl().toString()); - } - - @Test(expected = NotFoundException.class) - public void removeAITags_404_Expected() throws InterruptedException, IOException, PartialSuccessException, - NotFoundException, BadRequestException, InternalServerException, UnknownException, ForbiddenException, - TooManyRequestsException, UnauthorizedException { - - List fileIds = new ArrayList<>(); - fileIds.add("629f3de17eb0fe4053615450"); - List aiTags = new ArrayList<>(); - aiTags.add("Font"); - - AITagsRequest aiTagsRequest = new AITagsRequest(); - aiTagsRequest.setFileIds(fileIds); - aiTagsRequest.setAITags(aiTags); - - MockWebServer server = new MockWebServer(); - server.enqueue(new MockResponse().setResponseCode(404) - .setBody("{\n" + " \"message\": \"The requested file(s) does not exist.\",\n" - + " \"help\": \"For support kindly contact us at support@imagekit.io .\",\n" - + " \"missingFileIds\": [\n" + " \"629f3de17eb0fe4053615450\"\n" + " ]\n" + "}")); - server.start(); - RestClient.API_BASE_URL = server.url("/").toString(); - SUT.removeAITags(aiTagsRequest); - server.takeRequest(); - } - - @Test - public void removeAITags_successExpected() throws InterruptedException, IOException, PartialSuccessException, - NotFoundException, BadRequestException, InternalServerException, UnknownException, ForbiddenException, - TooManyRequestsException, UnauthorizedException { - - List fileIds = new ArrayList<>(); - fileIds.add("62958deef33aa80bdadf7533"); - List aiTags = new ArrayList<>(); - aiTags.add("Font"); - - AITagsRequest aiTagsRequest = new AITagsRequest(); - aiTagsRequest.setFileIds(fileIds); - aiTagsRequest.setAITags(aiTags); - - MockWebServer server = new MockWebServer(); - server.enqueue(new MockResponse().setBody("{\"successfullyUpdatedFileIds\": [\"62958deef33aa80bdadf7533\"]}")); - server.start(); - RestClient.API_BASE_URL = server.url("/").toString(); - SUT.removeAITags(aiTagsRequest); - RecordedRequest request = server.takeRequest(); - - String aiTagsRequestJson = "{\"fileIds\":[\"62958deef33aa80bdadf7533\"],\"AITags\":[\"Font\"]}"; - String utf8RequestBody = request.getBody().readUtf8(); - assertEquals(aiTagsRequestJson, utf8RequestBody); - assertEquals("application/json; charset=utf-8", request.getHeader("Content-Type")); - assertEquals("POST /v1/files/removeAITags HTTP/1.1", request.getRequestLine()); - assertEquals(RestClient.API_BASE_URL.concat("v1/files/removeAITags"), request.getRequestUrl().toString()); - } -} diff --git a/imagekit-sdk/src/test/java/io/imagekit/sdk/tasks/CalculationTest.java b/imagekit-sdk/src/test/java/io/imagekit/sdk/tasks/CalculationTest.java deleted file mode 100644 index f6e8e5e..0000000 --- a/imagekit-sdk/src/test/java/io/imagekit/sdk/tasks/CalculationTest.java +++ /dev/null @@ -1,104 +0,0 @@ -package io.imagekit.sdk.tasks; - - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import java.util.Calendar; -import java.util.Map; -import java.util.UUID; - -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.*; - -public class CalculationTest { - Calculation SUT; - - @Before - public void setUp() throws Exception { - SUT=new Calculation(); - } - - @Test(expected = RuntimeException.class) - public void nullPrivateKey_getAuthenticatedParams_throwException() { - Calculation.getAuthenticatedParams(UUID.randomUUID().toString(), Calendar.getInstance().getTimeInMillis(),null); - } - - @Test - public void privateKeyProvided_getAuthenticatedParams_with_static_input_ExpectedData() { - String token="your_token"; - String privateKey="private_key_test"; - long expire=1582269249; - Map authenticatedParams = Calculation.getAuthenticatedParams(token, expire, privateKey); - assertEquals(token,authenticatedParams.get("token")); - assertEquals(String.valueOf(expire),authenticatedParams.get("expire")); - assertEquals("e71bcd6031016b060d349d212e23e85c791decdd",authenticatedParams.get("signature")); - } - - @Test - public void privateKeyProvided_getAuthenticatedParams_ExpectedData() { - String token=UUID.randomUUID().toString(); - String privateKey="my_private_key"; - long expire=Calendar.getInstance().getTimeInMillis(); - Map authenticatedParams = Calculation.getAuthenticatedParams(token, expire, privateKey); - assertThat(authenticatedParams.get("token"),is(token)); - assertEquals(String.valueOf(expire),authenticatedParams.get("expire")); - assertNotNull(authenticatedParams.get("signature")); - } - - @Test - public void expireNotProvided_getAuthenticatedParams_ExpectedData() { - String token=UUID.randomUUID().toString(); - String privateKey="my_private_key"; - Map authenticatedParams = Calculation.getAuthenticatedParams(token,0, privateKey); - assertThat(authenticatedParams.get("token"),is(token)); - assertNotNull(authenticatedParams.get("expire")); - assertNotNull(authenticatedParams.get("signature")); - } - - @Test - public void sameImage_getHammingDistance_expectedSuccessWith() { - int hammingDistance = Calculation.getHammingDistance("f06830ca9f1e3e90", "f06830ca9f1e3e90"); - assertEquals(0,hammingDistance); - } - - @Test - public void similarImage_getHammingDistance_expectedSuccessWith() { - int hammingDistance = Calculation.getHammingDistance("2d5ad3936d2e015b", "2d6ed293db36a4fb"); - assertEquals(17,hammingDistance); - } - - @Test - public void dissimilarImage_getHammingDistance_expectedSuccessWith() { - int hammingDistance = Calculation.getHammingDistance("a4a65595ac94518b", "7838873e791f8400"); - assertEquals(37,hammingDistance); - } - - @Test(expected = RuntimeException.class) - public void invalidHash_getHammingDistance_throwException() { - int hammingDistance = Calculation.getHammingDistance("a4a65595ac94518Z", "7838873e791f8400"); - } - - @Test(expected = RuntimeException.class) - public void differentLength_getHammingDistance_throwException() { - int hammingDistance = Calculation.getHammingDistance("a4a65595ac94518b3", "7838873e791f8400"); - } - - @Test - public void correctHex_isValidHex_trueExpected() { - boolean result=Calculation.isValidHex("a4a65595ac94518b"); - assertTrue(result); - } - - @Test - public void incorrectHex_isValidHex_falseExpected() { - boolean result=Calculation.isValidHex("a4a65595ac94518T"); - assertFalse(result); - } - - @After - public void tearDown() throws Exception { - SUT=null; - } -} \ No newline at end of file diff --git a/imagekit-sdk/src/test/java/io/imagekit/sdk/tasks/MultipartBuilderTest.java b/imagekit-sdk/src/test/java/io/imagekit/sdk/tasks/MultipartBuilderTest.java deleted file mode 100644 index 9b1a705..0000000 --- a/imagekit-sdk/src/test/java/io/imagekit/sdk/tasks/MultipartBuilderTest.java +++ /dev/null @@ -1,239 +0,0 @@ -package io.imagekit.sdk.tasks; - -import com.google.gson.Gson; -import io.imagekit.sdk.models.FileCreateRequest; -import io.imagekit.sdk.models.FileUpdateRequest; -import okhttp3.*; -import okhttp3.mockwebserver.Dispatcher; -import okhttp3.mockwebserver.MockResponse; -import okhttp3.mockwebserver.MockWebServer; -import okhttp3.mockwebserver.RecordedRequest; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.TimeUnit; -import static org.junit.Assert.assertEquals; - - -public class MultipartBuilderTest { - MockWebServer server; - Map headers; - OkHttpClient okHttpClient; - MultipartBuilder SUT; - - @Before - public void setUp() throws Exception { - SUT=new MultipartBuilder(); - - String credential = Credentials.basic("private_key_test",""); - headers=new HashMap<>(); - headers.put("Accept-Encoding","application/json"); - headers.put("Content-Type","application/json"); - headers.put("Authorization",credential); - - server = new MockWebServer(); - MockResponse response=new MockResponse() - .setResponseCode(200) - .setBody("{isSuccessful=true, message='Your request contains invalid file.', help='For support kindly contact us at support@imagekit.io .', fileId='null', name='null', url='null', thumbnail='null', height=0, width=0, size=0, filePath='null', tags='null', isPrivateFile=false, customCoordinates='null', fileType='null'}"); - - server.setDispatcher(new Dispatcher() { - @Override - public MockResponse dispatch(RecordedRequest request) throws InterruptedException { - return response; - } - }); - server.start(); - - okHttpClient= new OkHttpClient.Builder() - .connectTimeout(2, TimeUnit.SECONDS) - .readTimeout(2, TimeUnit.SECONDS) - .writeTimeout(2, TimeUnit.SECONDS) - .build(); - - } - - @After - public void tearDown() throws Exception { - server.shutdown(); - } - - @Test - public void build_test_with_FileCreateRequest() throws Exception{ - - FileCreateRequest fileCreateRequest=new FileCreateRequest("f06830ca9f1e3e90","demo.jpg"); - fileCreateRequest.setPrivateFile(true); - - MultipartBody body = SUT.build(fileCreateRequest); - - HttpUrl baseUrl = server.url("/api/v1/files/upload"); - Request request=new Request.Builder() - .url(baseUrl) - .post(body) - .headers(Headers.of(headers)) - .build(); - - Response response = okHttpClient.newCall(request).execute(); - - String boundary=body.boundary(); - - String expectedMultipartData="--"+boundary+"\r\n" + - "Content-Disposition: form-data; name=\"file\"\r\n" + - "Content-Length: 16\r\n\r\n" + - "f06830ca9f1e3e90\r\n" + - "--"+boundary+"\r\n" + - "Content-Disposition: form-data; name=\"fileName\"\r\n" + - "Content-Length: 8\r\n\r\n" + - "demo.jpg\r\n" + - "--"+boundary+"\r\n" + - "Content-Disposition: form-data; name=\"useUniqueFileName\"\r\n" + - "Content-Length: 4\r\n\r\n" + - "true\r\n" + - "--"+boundary+"\r\n" + - "Content-Disposition: form-data; name=\"isPrivateFile\"\r\n" + - "Content-Length: 4\r\n\r\n" + - "true\r\n" + - "--"+boundary+"--\r\n"; - - // It's capture multipart request - RecordedRequest recordedRequest=server.takeRequest(); - - String data=recordedRequest.getBody().readUtf8(); - - assertEquals(expectedMultipartData, data); - } - - @Test - public void build_test_with_FileCreateRequest_more_params() throws Exception{ - - FileCreateRequest fileCreateRequest=new FileCreateRequest("f06830ca9f1e3e90","demo.jpg"); - fileCreateRequest.setPrivateFile(true); - fileCreateRequest.setFolder("/sample-folder"); - List tags=new ArrayList<>(); - tags.add("Software"); - tags.add("Developer"); - tags.add("Engineer"); - fileCreateRequest.setTags(tags); - fileCreateRequest.setCustomCoordinates("10,10,100,100"); - List responseFields=new ArrayList<>(); - responseFields.add("metadata"); - fileCreateRequest.setResponseFields(responseFields); - - MultipartBody body = SUT.build(fileCreateRequest); - - HttpUrl baseUrl = server.url("/api/v1/files/upload"); - Request request=new Request.Builder() - .url(baseUrl) - .post(body) - .headers(Headers.of(headers)) - .build(); - - Response response = okHttpClient.newCall(request).execute(); - - String boundary=body.boundary(); - - String expectedMultipartData="--"+boundary+"\r\n" + - "Content-Disposition: form-data; name=\"file\"\r\n" + - "Content-Length: 16\r\n\r\n" + - "f06830ca9f1e3e90\r\n" + - "--"+boundary+"\r\n" + - "Content-Disposition: form-data; name=\"fileName\"\r\n" + - "Content-Length: 8\r\n\r\n" + - "demo.jpg\r\n" + - "--"+boundary+"\r\n" + - "Content-Disposition: form-data; name=\"useUniqueFileName\"\r\n" + - "Content-Length: 4\r\n\r\n" + - "true\r\n" + - "--"+boundary+"\r\n" + - "Content-Disposition: form-data; name=\"tags\"\r\n" + - "Content-Length: 27\r\n\r\n" + - "Software,Developer,Engineer\r\n" + - "--"+boundary+"\r\n" + - "Content-Disposition: form-data; name=\"folder\"\r\n" + - "Content-Length: 14\r\n\r\n" + - "/sample-folder\r\n" + - "--"+boundary+"\r\n" + - "Content-Disposition: form-data; name=\"isPrivateFile\"\r\n" + - "Content-Length: 4\r\n\r\n" + - "true\r\n" + - "--"+boundary+"\r\n" + - "Content-Disposition: form-data; name=\"customCoordinates\"\r\n" + - "Content-Length: 13\r\n\r\n" + - "10,10,100,100\r\n" + - "--"+boundary+"\r\n" + - "Content-Disposition: form-data; name=\"responseFields\"\r\n" + - "Content-Length: 8\r\n\r\n" + - "metadata\r\n" + - "--"+boundary+"--\r\n"; - - - // It's capture multipart request - RecordedRequest recordedRequest=server.takeRequest(); - - String data=recordedRequest.getBody().readUtf8(); - - assertEquals(expectedMultipartData, data); - } - - @Test - public void build_test_with_FileUpdateRequest() throws Exception{ - - FileUpdateRequest fileUpdateRequest=new FileUpdateRequest("598821f949c0a938d57563bd"); - List tags=new ArrayList<>(); - tags.add("t-shirt"); - tags.add("round-neck"); - tags.add("sale2020"); - fileUpdateRequest.setTags(tags); - - RequestBody body=SUT.build(fileUpdateRequest); - - HttpUrl baseUrl = server.url(String.format("/v1/files/%s/details",fileUpdateRequest.getFileId())); - Request request=new Request.Builder() - .url(baseUrl) - .post(body) - .headers(Headers.of(headers)) - .build(); - - Response response = okHttpClient.newCall(request).execute(); - - - String expectedRequestObject="{\"fileId\":\"598821f949c0a938d57563bd\",\"tags\":[\"t-shirt\",\"round-neck\",\"sale2020\"]}"; - - // It's capture multipart request - RecordedRequest recordedRequest=server.takeRequest(); - - String data=recordedRequest.getBody().readUtf8(); - - assertEquals(expectedRequestObject, data); - } - - @Test - public void build_test_with_From_Json_String() throws Exception{ - - String json="{\"fileIds\":[\"598821f949c0a938d57534bd\",\"338821f949c0a938d57563bz\",\"987821f949c0a938d57563rt\"]}"; - - RequestBody body=SUT.build(json); - - HttpUrl baseUrl = server.url("/v1/files/batch/deleteByFileIds"); - Request request=new Request.Builder() - .url(baseUrl) - .post(body) - .headers(Headers.of(headers)) - .build(); - - Response response = okHttpClient.newCall(request).execute(); - - - String expectedRequestObject="{\"fileIds\":[\"598821f949c0a938d57534bd\",\"338821f949c0a938d57563bz\",\"987821f949c0a938d57563rt\"]}"; - - // It's capture multipart request - RecordedRequest recordedRequest=server.takeRequest(); - - String data=recordedRequest.getBody().readUtf8(); - - assertEquals(expectedRequestObject, data); - } -} \ No newline at end of file diff --git a/imagekit-sdk/src/test/java/io/imagekit/sdk/tasks/QueryMakerTest.java b/imagekit-sdk/src/test/java/io/imagekit/sdk/tasks/QueryMakerTest.java deleted file mode 100644 index 6eb0816..0000000 --- a/imagekit-sdk/src/test/java/io/imagekit/sdk/tasks/QueryMakerTest.java +++ /dev/null @@ -1,30 +0,0 @@ -package io.imagekit.sdk.tasks; - -import org.junit.Before; -import org.junit.Test; - -import static org.junit.Assert.*; - -public class QueryMakerTest { - - QueryMaker SUT; - - @Before - public void setUp() throws Exception { - SUT=new QueryMaker(); - } - - @Test - public void prepareQueary_returnQueryString() { - SUT.put("public=allow"); - SUT.put("user=guest"); - String param = SUT.get(); - assertEquals("public=allow&user=guest",param); - } - - @Test - public void withoutEntry_prepareQueary() { - String param = SUT.get(); - assertNull(param); - } -} \ No newline at end of file diff --git a/imagekit-sdk/src/test/java/io/imagekit/sdk/tasks/UrlGenTest.java b/imagekit-sdk/src/test/java/io/imagekit/sdk/tasks/UrlGenTest.java deleted file mode 100644 index 1b379a8..0000000 --- a/imagekit-sdk/src/test/java/io/imagekit/sdk/tasks/UrlGenTest.java +++ /dev/null @@ -1,32 +0,0 @@ -package io.imagekit.sdk.tasks; - -import org.junit.Test; - -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.*; - -public class UrlGenTest { - @Test - public void signUrl_tests() { - String url="https://test-domain.com/test-endpoint/tr:w-100/test-signed-url.png"; - String signature = UrlGen.signUrl("private_key_test", url, "https://test-domain.com/test-endpoint/", 100); - assertThat("5e5037a31a7121cbe2964e220b4338cc6e1ba66d",is(signature)); - - } - - @Test - public void signUrl_tests_expire_zero() { - String url="https://test-domain.com/test-endpoint/tr:w-100/test-signed-url.png"; - String signature = UrlGen.signUrl("private_key_test", url, "https://test-domain.com/test-endpoint/", 0); - assertThat("41b3075c40bc84147eb71b8b49ae7fbf349d0f00",is(signature)); - - } - - @Test - public void signUrl_tests_without_slash_expire_zero() { - String url="https://test-domain.com/test-endpoint/tr:w-100/test-signed-url.png"; - String signature = UrlGen.signUrl("private_key_test", url, "https://test-domain.com/test-endpoint", 0); - assertThat("41b3075c40bc84147eb71b8b49ae7fbf349d0f00",is(signature)); - - } -} \ No newline at end of file diff --git a/imagekit-sdk/src/test/java/io/imagekit/sdk/utils/UtilsTest.java b/imagekit-sdk/src/test/java/io/imagekit/sdk/utils/UtilsTest.java deleted file mode 100644 index e68b206..0000000 --- a/imagekit-sdk/src/test/java/io/imagekit/sdk/utils/UtilsTest.java +++ /dev/null @@ -1,90 +0,0 @@ -package io.imagekit.sdk.utils; - -import io.imagekit.sdk.config.Configuration; -import org.junit.Test; - -import java.io.File; -import java.io.IOException; -import java.net.URL; -import java.util.ArrayList; -import java.util.List; - -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.*; -import static org.mockito.Mockito.mock; - -public class UtilsTest { - - @Test - public void empty_listToString_returnTrue() { - List list=new ArrayList<>(); - String data=Utils.listToString(list); - assertNotNull(data); - } - - @Test - public void withElements_listToString_returnTrue() { - List list=new ArrayList<>(); - list.add("Element 1"); - list.add("Element 2"); - list.add("Element 3"); - String data=Utils.listToString(list); - assertThat("Element 1,Element 2,Element 3",is(data)); - } - - @Test - public void withNullElements_listToString_returnTrue() { - List list=new ArrayList<>(); - list.add("Element 1"); - list.add(null); - list.add("Element 2"); - String data=Utils.listToString(list); - assertEquals("Element 1,Element 2",data); - } - - @Test - public void withNullElements_listToString_returnFalse() { - List list=new ArrayList<>(); - list.add("Element 1"); - list.add(null); - list.add("Element 2"); - String data=Utils.listToString(list); - assertNotEquals("Element 1,null,Element 2",data); - } - - @Test - public void validFile_fileToBase64_expectedTrue() { - URL imageURL = UtilsTest.class.getClassLoader().getResource("sample1.jpg"); - File file=new File(imageURL.getPath()); - String base64 = Utils.fileToBase64(file); - assertNotNull(base64); - } - - @Test(expected = Exception.class) - public void noFile_fileToBase64_expectedTrue() { - File file=mock(File.class); - String base64 = Utils.fileToBase64(file); - assertNull(base64); - } - - @Test - public void validFile_fileToBytes_expectedTrue() { - URL imageURL = UtilsTest.class.getClassLoader().getResource("sample1.jpg"); - File file=new File(imageURL.getPath()); - byte[] bytes = Utils.fileToBytes(file); - assertNotNull(bytes); - } - - @Test(expected = Exception.class) - public void noFile_fileToBytes_expectedTrue() { - File file=mock(File.class); - byte[] bytes = Utils.fileToBytes(file); - assertNull(bytes); - } - - @Test - public void test_getSystemConfig_expectedSuccess() throws IOException { - Configuration config=Utils.getSystemConfig(UtilsTest.class); - assertNotNull(config); - } -} \ No newline at end of file diff --git a/imagekit-sdk/src/test/resources/config.properties b/imagekit-sdk/src/test/resources/config.properties deleted file mode 100644 index a7cbc4a..0000000 --- a/imagekit-sdk/src/test/resources/config.properties +++ /dev/null @@ -1,6 +0,0 @@ -# Copy this sample file add rename it to "config.properties" -# Put essential values of keys [UrlEndpoint, PrivateKey, PublicKey] - -UrlEndpoint=https://ik.imagekit.io/imagekit_id -PrivateKey=private_key_test -PublicKey=public_key_test \ No newline at end of file diff --git a/imagekit-sdk/src/test/resources/sample1.jpg b/imagekit-sdk/src/test/resources/sample1.jpg deleted file mode 100644 index 3a52a95..0000000 Binary files a/imagekit-sdk/src/test/resources/sample1.jpg and /dev/null differ diff --git a/release-please-config.json b/release-please-config.json new file mode 100644 index 0000000..8f98719 --- /dev/null +++ b/release-please-config.json @@ -0,0 +1,67 @@ +{ + "packages": { + ".": {} + }, + "$schema": "https://raw.githubusercontent.com/stainless-api/release-please/main/schemas/config.json", + "include-v-in-tag": true, + "include-component-in-tag": false, + "versioning": "prerelease", + "prerelease": true, + "bump-minor-pre-major": true, + "bump-patch-for-minor-pre-major": false, + "pull-request-header": "Automated Release PR", + "pull-request-title-pattern": "release: ${version}", + "changelog-sections": [ + { + "type": "feat", + "section": "Features" + }, + { + "type": "fix", + "section": "Bug Fixes" + }, + { + "type": "perf", + "section": "Performance Improvements" + }, + { + "type": "revert", + "section": "Reverts" + }, + { + "type": "chore", + "section": "Chores" + }, + { + "type": "docs", + "section": "Documentation" + }, + { + "type": "style", + "section": "Styles" + }, + { + "type": "refactor", + "section": "Refactors" + }, + { + "type": "test", + "section": "Tests", + "hidden": true + }, + { + "type": "build", + "section": "Build System" + }, + { + "type": "ci", + "section": "Continuous Integration", + "hidden": true + } + ], + "release-type": "simple", + "extra-files": [ + "README.md", + "build.gradle.kts" + ] +} \ No newline at end of file diff --git a/scripts/build b/scripts/build new file mode 100755 index 0000000..f406348 --- /dev/null +++ b/scripts/build @@ -0,0 +1,8 @@ +#!/usr/bin/env bash + +set -e + +cd "$(dirname "$0")/.." + +echo "==> Building classes" +./gradlew build testClasses -x test diff --git a/scripts/format b/scripts/format new file mode 100755 index 0000000..65db176 --- /dev/null +++ b/scripts/format @@ -0,0 +1,21 @@ +#!/usr/bin/env bash + +set -e + +cd "$(dirname "$0")/.." + +if command -v ktfmt &> /dev/null; then + echo "==> Running ktfmt" + ./scripts/kotlin-format +else + echo "==> Running gradlew formatKotlin" + ./gradlew formatKotlin +fi + +if command -v palantir-java-format &> /dev/null; then + echo "==> Running palantir-java-format" + ./scripts/java-format +else + echo "==> Running gradlew formatJava" + ./gradlew formatJava +fi diff --git a/scripts/java-format b/scripts/java-format new file mode 100755 index 0000000..ad5febc --- /dev/null +++ b/scripts/java-format @@ -0,0 +1,7 @@ +#!/usr/bin/env bash + +set -e + +cd "$(dirname "$0")/.." + +find . -name "*.java" -not -path "./buildSrc/build/*" -print0 | xargs -0 -r palantir-java-format --palantir --replace "$@" diff --git a/scripts/kotlin-format b/scripts/kotlin-format new file mode 100755 index 0000000..3b8be9e --- /dev/null +++ b/scripts/kotlin-format @@ -0,0 +1,7 @@ +#!/usr/bin/env bash + +set -e + +cd "$(dirname "$0")/.." + +find . -name "*.kt" -not -path "./buildSrc/build/*" -print0 | xargs -0 -r ktfmt --kotlinlang-style "$@" diff --git a/scripts/lint b/scripts/lint new file mode 100755 index 0000000..dbc8f77 --- /dev/null +++ b/scripts/lint @@ -0,0 +1,23 @@ +#!/usr/bin/env bash + +set -e + +cd "$(dirname "$0")/.." + +echo "==> Running lints" + +if command -v ktfmt &> /dev/null; then + echo "==> Checking ktfmt" + ./scripts/kotlin-format --dry-run --set-exit-if-changed +else + echo "==> Running gradlew lintKotlin" + ./gradlew lintKotlin +fi + +if command -v palantir-java-format &> /dev/null; then + echo "==> Checking palantir-java-format" + ./scripts/java-format --dry-run --set-exit-if-changed +else + echo "==> Running gradlew lintJava" + ./gradlew lintJava +fi diff --git a/scripts/mock b/scripts/mock new file mode 100755 index 0000000..0b28f6e --- /dev/null +++ b/scripts/mock @@ -0,0 +1,41 @@ +#!/usr/bin/env bash + +set -e + +cd "$(dirname "$0")/.." + +if [[ -n "$1" && "$1" != '--'* ]]; then + URL="$1" + shift +else + URL="$(grep 'openapi_spec_url' .stats.yml | cut -d' ' -f2)" +fi + +# Check if the URL is empty +if [ -z "$URL" ]; then + echo "Error: No OpenAPI spec path/url provided or found in .stats.yml" + exit 1 +fi + +echo "==> Starting mock server with URL ${URL}" + +# Run prism mock on the given spec +if [ "$1" == "--daemon" ]; then + npm exec --package=@stainless-api/prism-cli@5.15.0 -- prism mock "$URL" &> .prism.log & + + # Wait for server to come online + echo -n "Waiting for server" + while ! grep -q "✖ fatal\|Prism is listening" ".prism.log" ; do + echo -n "." + sleep 0.1 + done + + if grep -q "✖ fatal" ".prism.log"; then + cat .prism.log + exit 1 + fi + + echo +else + npm exec --package=@stainless-api/prism-cli@5.15.0 -- prism mock "$URL" +fi diff --git a/scripts/test b/scripts/test new file mode 100755 index 0000000..047bc1d --- /dev/null +++ b/scripts/test @@ -0,0 +1,56 @@ +#!/usr/bin/env bash + +set -e + +cd "$(dirname "$0")/.." + +RED='\033[0;31m' +GREEN='\033[0;32m' +YELLOW='\033[0;33m' +NC='\033[0m' # No Color + +function prism_is_running() { + curl --silent "http://localhost:4010" >/dev/null 2>&1 +} + +kill_server_on_port() { + pids=$(lsof -t -i tcp:"$1" || echo "") + if [ "$pids" != "" ]; then + kill "$pids" + echo "Stopped $pids." + fi +} + +function is_overriding_api_base_url() { + [ -n "$TEST_API_BASE_URL" ] +} + +if ! is_overriding_api_base_url && ! prism_is_running ; then + # When we exit this script, make sure to kill the background mock server process + trap 'kill_server_on_port 4010' EXIT + + # Start the dev server + ./scripts/mock --daemon +fi + +if is_overriding_api_base_url ; then + echo -e "${GREEN}✔ Running tests against ${TEST_API_BASE_URL}${NC}" + echo +elif ! prism_is_running ; then + echo -e "${RED}ERROR:${NC} The test suite will not run without a mock Prism server" + echo -e "running against your OpenAPI spec." + echo + echo -e "To run the server, pass in the path or url of your OpenAPI" + echo -e "spec to the prism command:" + echo + echo -e " \$ ${YELLOW}npm exec --package=@stainless-api/prism-cli@5.15.0 -- prism mock path/to/your.openapi.yml${NC}" + echo + + exit 1 +else + echo -e "${GREEN}✔ Mock prism server is running with your OpenAPI spec${NC}" + echo +fi + +echo "==> Running tests" +./gradlew test "$@" diff --git a/settings.gradle b/settings.gradle deleted file mode 100644 index 07bd3b1..0000000 --- a/settings.gradle +++ /dev/null @@ -1,3 +0,0 @@ -rootProject.name = 'imagekit-java' -include 'imagekit-sdk' - diff --git a/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 0000000..554a1a8 --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1,14 @@ +rootProject.name = "image-kit-java-root" + +val projectNames = rootDir.listFiles() + ?.asSequence() + .orEmpty() + .filter { file -> + file.isDirectory && + file.name.startsWith("image-kit-java") && + file.listFiles()?.asSequence().orEmpty().any { it.name == "build.gradle.kts" } + } + .map { it.name } + .toList() +println("projects: $projectNames") +projectNames.forEach { include(it) }